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

    protected function configure()
    {
        
        $this->setName('runsocket')->setDescription('Suxuan system service: socket server');
    }
    
    protected function execute(Input $input, Output $output)
    {


        /**
         *要操作的类，此类必须在LIB下面
         * 
         */
        $controller = 'Runsocket';
        /**
         * 类里的方法
         */
        $method = 'Run';
        
        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');
        try{
            $objMethod->invokeArgs($handle, array());
            $nowVersion = md5_file(APP_PATH.'const.php');
            if($nowVersion != $startVersion){
                //防止应用升级后，忘记重启服务的情况
                //版本发生变化，直接停止服务，让守护进程来重启
                die;
            }
        }  catch (\Exception $e){
            if(!file_exists(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym'))){
                @mkdir(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym'),0777,true);
            }
            @file_put_contents(ROOT_PATH.DS.'runtime'.DS.'log'.DS.  date('Ym').DS.'runsocket.log', date('Y-m-d H:i:s')."\t".'run error '.$e->getMessage().  json_encode($e->getTraceAsString()),FILE_APPEND);
        }
        
        
    }

}