<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;

use util\RedisUtil;
use util\QuotationRedis;

use function Swoole\Coroutine\run;
use \co\Http\Client;
/**
 * 获取当前活跃股票的行情数据
 */
class Alive extends Command
{
    protected $stockClient;
    protected $stockHost     = LOCAL_STOCK_HOST;
    protected $stockPort     = LOCAL_STOCK_PORT;
    protected $stockPath     = '/api/market/getstocks';
    
    protected function configure()
    {
        $this->setName('alive')->setDescription('更新持仓股票行情');
    }

    /**
     * 入口
     *
     * @param Input  $input
     * @param Output $output
     *
     * @return int|void|null
     * @throws \Exception
     */
    protected function execute(Input $input, Output $output)
    {
        /*启动行情客户端*/
    	swoole_timer_tick(LOCAL_STOCK_TIMES*1000, function (){
		    //if(!checkTradeTime()) return false;
		    $list = QuotationRedis::aliveStockList();
            if(empty($list)) return;
            foreach($list as $key => $item){
                if(!$item) continue;
                $this->getStocks($this->toStrCodes($item));
            }
		});
		\Swoole\Event::wait();
    }
    /*组合代码*/
    protected function toStrCodes($item)
    {
        $num = '';
        foreach ($item as $k => $v) {
            $data = explode("_", $v);
            if(strlen($data[0]) != 6 || strlen($data[1]) != 2) continue;
            $dian = count($item) == ($k+1) ? "" : ",";
            $num .= strtolower($data[1]) . $data[0] . $dian;
        }
        return $num;
    }
    /*获取行情*/
    protected function getStocks($codes)
    {
        $this->stockClient = new Client($this->stockHost, $this->stockPort);
        $this->stockClient->setHeaders([
            'User-Agent'      => 'Chrome/49.0.2587.3',
            'Accept'          => 'text/html,application/xhtml+xml,application/xml',
            'Accept-Encoding' => 'gzip',
            'Access-Token'    => LOCAL_TRADING_TOKEN,
            'Client-Host'     => RedisUtil::getClientHost(),
        ]);
        $this->stockClient->post($this->stockPath,array('codes'=>$codes));
        $this->onMessage($this->stockClient->body);
        $this->stockClient->close();
    }
    /**
     * 处理行情客户端接收到的消息
     */
    protected function onMessage($data)
    {
        if($data){
            $recData = json_decode($data, true);
            $stockData = isset($recData['data']) ? $recData['data'] : [];
            foreach ($stockData as $k => $item) {
                go(function () use ($item) {
                    QuotationRedis::cacheStockData($item);
                    //$this->output->writeln(date('Y-m-d H:i:s')." ".strtoupper($item[0]) . $item[2].' 更新完毕');
                });
            } 
        }
        
    }
    
}

