<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Models\StrategyTask;
use App\Service\StrategyService;
//use App\Http\Controllers\Tool;

class CreatedTaskCommand extends Command
{
    //use Tool;
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:CreatedTaskCommand';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '每天早上6点创建任务';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $StrategyService = new StrategyService();
        $StrategyService->createdTask();
        
        $StrategyService->createdTask(); //对失败数据重试3次，没有失败数据直接返回
        
        $StrategyService->createdTask();
        
        $StrategyService->createdTask();
        
        //新建任务、失败原任务重呼3次，接口调用失败重试3次
        /* //$userInfo = $this->getAllowLoginUser();
        $userInfo = ['user_name'=>'yxl001','user_sn'=>'SYSUSER|9da548a2e392a679eb274a0b2abeb627','parent_sn'=>'ljs'];
        $today = date('Y-m-d');
        $taskInfo = StrategyTask::where([['is_created',0],['call_date',$today],['created_fail_number','<=','3']])->get()->toArray(); //获取当天需要新建任务的数据
        $url = "https://test117.ciopaas.com/api/addJsonNoLogin";
        //dd($taskInfo);
        foreach ($taskInfo as $k=>$v){//批量调用接口新建任务
            $failLabTemp = 0;
            $failReason = '';
            //处理参数
            if (empty($v['project_sn'])){
                break;
            }
            $client_info_json = [
                [
                    '姓名'=>$v['name'],
                    '电话'=>$v['phone'],
                    '地址'=>'',
                    '公司名称'=>'',
                    '备注'=>'',
                    '手机号码'=>$v['phone'],
                    '值班日期'=>$v['duty_date']                    
                ]                
            ];
            
            $params = [
                'user_sn'=>$v['user_sn'],
                'project_sn'=>trim($v['project_sn']),
                'source'=>date('YmdHis').$k, //任务名称，年月日时分秒，加上循环键值避免重复任务名
                'ai_user_sn'=>$v['user_sn'],//$v['user_sn'],
                'is_zidong'=>'off',//是否自动启动，否，任务定时启动
                'is_open_remove_duplication'=>'0',
                'is_auto_fail_recall'=>'1', //是否自动重呼，是
                'total_fail_recall_times'=>'3', //重呼次数
                'fail_recall_interval'=>'3',//重呼间隔时间
                'recall_auto'=>1, //重呼方式； 0新建任务1原任务重呼
                'mark'=>'值班策略创建任务',
                'fail_recall_of_reason'=>'关机,来电提醒,稍后再拨,停机,无法接通,正在通话中,用户正忙,用户拒接,欠费,无人应答,其他,对方示忙',
                'is_auto_stop'=>2, //0非自动暂停，1自动暂停 2 定时启动任务
                'timed_started_at'=>$v['call_date'].' '.$v['call_time'], //定时启动
                'yd_display_phone'=>$v['user_sn'].'@vos:'.$v['call_number'] //主叫号码传输格式
                //'ai_distribution_type'=>'0'//0公用ai 1按主账号分配ai（6.2人工外呼分配方式 0平均，1抢拨）
            ];
            
            $params['client_info_json'] = json_encode(['data'=>$client_info_json]);
            
            
            $params['url'] = substr(md5(json_encode($params)),1,8);
            $requestReturn = $this->requestPost($url,$params);
            
            $requestReturnArr = json_decode($requestReturn,true);
            if (isset($requestReturnArr['code'])){ 
                if ($requestReturnArr['code'] == 0){//接口请求返回成功
                    if ($requestReturnArr['data']['total'] == $requestReturnArr['data']['success']){//全部成功
                        StrategyTask::where('id',$v['id'])->update(['is_created'=>1]); //设为已创建
                    }else{//存在失败数据
                        $failLabTemp = 1;
                        $failReason = substr($requestReturnArr['msg'],0,490);
                    }
                }else{ //接口请求返回异常
                    $failLabTemp = 1;
                    $failReason = substr($requestReturnArr['msg'],0,490);
                }
            }else{
                $failLabTemp = 1;
                $failReason = substr($requestReturn,0,490);
            }
            
            if ($failLabTemp == 1){
                StrategyTask::where('id',$v['id'])->update(['created_fail_number'=>($v['created_fail_number'] + 1),'create_fail_reason'=>$failReason]); //设为已创建
            }
        }
         */
        
    }
    
    
    
    public function requestPost($url = '', $post_data = array(),$header=array()) {
        if (empty($url) || empty($post_data)) {
            return false;
        }
        
        $o = "";
        if(is_array($post_data) && count($post_data)){
            foreach ( $post_data as $k => $v )
            {
                $o.= "$k=" . urlencode( $v ). "&" ;
            }
            $post_data = substr($o,0,-1);
        }
        $postUrl = $url;
        $curlPost = $post_data;
        $ch = curl_init();//初始化curl
        if(!empty($header)){
            curl_setopt( $ch, CURLOPT_HTTPHEADER, $header);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        return $data;
    }
}
