<?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 app\admin\model\StockList as StockListModel;
use util\RedisUtil;
use util\QuotationRedis;
use function Swoole\Coroutine\run;
use \co\Http\Client;
/**
 * 获取当前活跃股票的行情数据
 */
class StockList extends Command
{
    protected $stockFlag = 0;
    protected $countFlag = 0;

    protected function configure()
    {
        $this->setName('stocklist')->setDescription('初始化股票列表');
    }

    /**
     * 入口
     *
     * @param Input  $input
     * @param Output $output
     *
     * @return int|void|null
     * @throws \Exception
     */
    protected function execute(Input $input, Output $output)
    {
        swoole_timer_tick(5000, function (){
            /*启动股票列表客户端*/
        	$this->startIntStockList();
        	/*启动热门行业客户端*/
        	$this->startHotIndustrys();
        	/*启动行业分类客户端*/
        	$this->startgatNodeclass();
        });
		\Swoole\Event::wait();
    }
    /*
     * 初始化股票列表
     */
    private function startIntStockList()
    {
	    if(!checkTradeTime()) {
	        $this->stockFlag = 0;
	        return false;
	    }
	    if($this->stockFlag === 0) {
	        //$data = eastStockList() ?: [];
	        $data = apiStockList() ?: [];
            if(!empty($data)) {
                $res = StockListModel::intStockList($data['items']);
                if($res) $this->stockFlag = 1;
            }
	    }
    }
    private function startHotIndustrys()
    {
        $res = getSinahy();
		if($res){
		    go(function () use ($res) {
                QuotationRedis::cacheIndustrys($res);
            });
		}
    }
    private function startgatNodeclass()
    {
        $res = RedisUtil::getHotIndustrys();
        if(!$res) return false;
        foreach ($res as $k => $item) {
            go(function () use ($item) {
                $data = getSinaNodeclass($item[0]);
                //print_r($data);return;
                if($data) QuotationRedis::cacheNodeclass($item[0],$data);
            });
            sleep(2);
        }
    }
    /**
     * 缓存行业内容
     */
    protected function cacheIndustrys($data)
    {
        // 每次创建一个连接
        $redis = new \Swoole\Coroutine\Redis();
        $redis->connect(REDIS_SERVER_IP, REDIS_SERVER_PORT);
        $key   = 'Hot_Industrys';
        // 删除之前的列表
        $redis->del($key);
        $redis->Set($key, serialize($data));
    }
    /**
     * 缓存行业分类
     */
    protected function cacheNodeclass($item,$data)
    {
        // 每次创建一个连接
        $redis = new \Swoole\Coroutine\Redis();
        $redis->connect(REDIS_SERVER_IP, REDIS_SERVER_PORT);
        $key   = 'Hot_Nodeclass_' . $item;
        // 删除之前的列表
        $redis->del($key);
        $redis->Set($key, serialize($data));
    }
}

