<?php
/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
namespace app\crm\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class Runimport extends Command{

    protected function configure()
    {
        $this->setName('runimport')->setDescription('Suxuan system service: pi liang dao ru');
    }
    
    protected function execute(Input $input, Output $output)
    {
        /**
         *要操作的类，此类必须在LIB下面
         * 
         */
        $controller = 'ListenRedis';
        /**
         * 类里的方法
         */
        $method = 'excelImport';
        
        if(!class_exists('app\\crm\\lib\\'.ucwords($controller))){
            echo '没有发现这个类：'.$controller."\r\n";
            exit();
        }
        $instance = new \ReflectionClass('app\\crm\\lib\\'.ucwords($controller));
        if (!$instance->hasMethod($method)) {
            echo '没有发现这个方法：'.$method."\r\n";
            exit();
        }
        $objMethod = $instance->getMethod($method);
        $handle = $instance->newInstance();
        $startVersion = md5_file(APP_PATH.'const.php');

        $runimportDay = cache('runimportDay');
        if (!$runimportDay) {
            cache('runimportDay',date('Ymd'));
            $runimportDay = date('Ymd',time());
        }
        while (1){
            $dbData = db()->master()->query("select sysdate() as time");
            echo "Start new loop run at ".date('Y-m-d H:i:s').",dbDate:".$dbData[0]['time']."\r\n";
            try{
                $objMethod->invokeArgs($handle, array($this->apiParams,  $this->appId));
                $nowVersion = md5_file(APP_PATH.'const.php');
                if($nowVersion != $startVersion){
                    //防止应用升级后，忘记重启服务的情况
                    //版本发生变化，直接停止服务，让守护进程来重启
                    cache('runimportDay',date('Ymd'));
                    die;
                }
                // 持续运行超过30天
                if ((date('Ymd')-$runimportDay)>30) {
                    cache('runimportDay',date('Ymd'));
                    die;
                }

            }  catch (\Exception $e){
                if(!file_exists(ROOT_PATH.DS.'runtime'.DS.'logs'.DS.  date('Ym'))){
                    mkdir(ROOT_PATH.DS.'runtime'.DS.'logs'.DS.  date('Ym'),0777,true);
                }
                file_put_contents(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym').DS.'runimport.log', date('Y-m-d H:i:s')."\t".'run error '.$e->getMessage().  json_encode($e->getTraceAsString()),FILE_APPEND);
                sleep(1);
            }
        }
        
    }

}