<?php
namespace process;

use FilesystemIterator;
use Workerman\Timer;
use support\Db;
use support\Log;
use support\ApiTask;

class TaskBPM
{
    private $task;
    public function onWorkerStart()
    {
        set_time_limit(3600 * 100);
        ini_set('memory_limit', '2048M');
        
        $this->task = new ApiTask('TaskBPM');
        // 每隔60秒检查一次
        Timer::add(15, function(){
    		$data = $this->task->get();
    		if($data->enable 
    		   && time()>strtotime($data->begin_start_time) //开始时间
    		   && (empty($data->access_time) || time()-strtotime($data->access_time) > $data->interval)
    		){
                $nowTime = getNowTime();
                if($data->interval >= 86400){ //达到或超过1天时
                    $t = explode(' ',$data->begin_start_time); 
                    $jgTime = $t[1];
                    $t = explode(' ',getNowTime()); 
                    $date = $t[0];
                    $nowTime  = $date .' '. $jgTime;
                }
    			$this->task->begin($nowTime);
    			$this->execute($data->access_time,$nowTime);
                $this->task->complete(getNowTime());
    		}
        });
    }

    public function execute($beginTime,$endTime)
    {
        $row = Db::table('smt_bpm_check')
                ->join('smt_rules', 'smt_bpm_check.sbc_sr_id', '=', 'smt_rules.sr_id')
                ->join('api_crm_customer', 'smt_bpm_check.sbc_cid', '=', 'api_crm_customer.guid')
                ->join('smt_customer', 'smt_bpm_check.sbc_cid', '=', 'smt_customer.c_id')
                ->join('copy_pdc_gsp_adm_user', 'smt_customer.c_au_id', '=', 'copy_pdc_gsp_adm_user.au_id')
                ->where('sbc_is_send',0)->orderBy('sbc_id', 'desc')
                ->first();
 	   //Log::channel('task_bpm')->info(json_encode($row));
       if(empty($row)) return;

        $rRows = Db::table('smt_report')
                ->join('smt_pro', 'smt_report.smt_report_pid', '=', 'smt_pro.smt_p_id')
                ->join('copy_pdc_pro_cate', 'smt_pro.smt_p_bigcate', '=', 'copy_pdc_pro_cate.id')
                ->select('id','cn_name','en_name')->distinct()
                ->where('smt_report_ver',$row->sbc_ver)
                ->where('smt_report_cid',$row->sbc_cid)->get();

        $productLine  = '';
        $productLineArr = []; 
        if($rRows) foreach($rRows as $rRow){
			switch($rRow->id){
				case 146: $productLineArr[1] = true; break;
				case 183: $productLineArr[2] = true; break;
				case 242: $productLineArr[3] = true; break;
				case 157: $productLineArr[4] = true; break;
				default:  $productLineArr[5] = true;
			}
            $productLine = implode(',',array_keys($productLineArr));
        }
		$area = $row->reserve3;
		$area = preg_replace("/\(.*\)/is",'',$area);

        $recommendId = base64_encode($row->sbc_ver.'-'.$row->sbc_cid);
        $applyReason = '规则:'.$row->sr_title. ", 数量: ".$row->sbc_count;
        $remark = "客户: ".$row->Name;
        $send = [
            'userNo'=> $row->au_jobno ?? $row->au_id,
            'productLine'=> $productLine,
            'area'=> $area,
            'customCode'=> $row->AccountNumber,
            'applyReason'=> $applyReason,
            'remark'=> $remark,
            'recommendId'=> $recommendId
        ];    
        if($this->callBPM($send)){
            Db::table('smt_bpm_check')
                ->where('sbc_id', $row->sbc_id)
                ->update([
                        'sbc_is_send'=>1
                ]);
        }
    }

    public function callBPM($data)
    {
		$json = curl([
            /*
			'url'=>'http://test.edi-runtime.jdl.cn/api/sap/CreateCatalogApply',
			'auth'=>[
				'type'=>'BASIC',
				'username'=>'gspcpgl',
				'password'=>'sPEj3kGMfy*7!$+V'
			],
            */
			'url'=>'http://edi-runtime.gsp.cn/api/sap/CreateCatalogApply',
			'auth'=>[
				'type'=>'BASIC',
				'username'=>'gspcpgl',
				'password'=>'Ib1hBGz/4AhO80i_'
			],
			'timeout'=>900,
			'dataType'=>'json',
			'data'=> $data
		]);
		if(empty($json) || !isset($json['status']) || !$json['status']){
			Log::channel('task_bpm')->info('curl:'.json_encode([$data,$json],JSON_UNESCAPED_UNICODE));
		}
        return $json['status'];
    }

}