<?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 Runfp extends Command{

    protected function configure()
    {
        $this->setName('runfp')->setDescription('Suxuan system service:kezifenpei');
    }
    
    protected function execute(Input $input, Output $output)
    {
        /**
         *要操作的类，此类必须在LIB下面
         * 
         */
        $controller = 'ListenRedis';
        /**
         * 类里的方法
         */
        $method = 'customerFp';
        
        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();
        }
        /*
        $cacheKey = 'sx_server_'.config('APP_ID');
        $con = \think\Cache::init();
        
        if(!$con){
            exit('Can not access cache system.'."\r\n");
        }
        $cacheData = cache($cacheKey);
        if(is_string($cacheData)){
            $cacheData = json_decode($cacheKey,TRUE);
        }
        if($cacheData && $cacheData['active']+30 >= time()){
            exit('System in running,please try later.'."\r\n");
        }
        */

        $objMethod = $instance->getMethod($method);
        $handle = $instance->newInstance();

        $startVersion = md5_file(APP_PATH.'const.php');
        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){
                    //防止应用升级后，忘记重启服务的情况
                    //版本发生变化，直接停止服务，让守护进程来重启
                    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.'runfp.log', date('Y-m-d H:i:s')."\t".'run error '.$e->getMessage().  json_encode($e->getTraceAsString()),FILE_APPEND);
                sleep(1);
            }
        }
        
    }

}