<?php


namespace app\queue;


use app\common\model\Config;
use app\common\model\Orders;
use app\common\model\SmsLog;
use app\common\util\AppMsg;
use think\Db;
use think\queue\Job;
use tools\Qxsms;

class Jobs
{
    /**
     * 发送极光推送
     * @param Job $job
     * @param $data 例:{"users":[1,2,3],"type":1,"msg":"有新订单需要你的处理","extra"=>[]}
     */
    public function jpush(Job $job, $data){
        $ndata = json_decode($data,true);
        $ret = $this->sendJpush($ndata['users'],$ndata['type'],$ndata['msg'],$ndata['extra']);
        if($ret){
            $job->delete();
        }else{
            if ($job->attempts() > 2) { //重试2次任务失败后记录失败日志
                $this->jobFail('jpush',$data);
                $job->delete(); // 删除任务
            }else{
                $job->release(3); // 3秒后重新执行
            }
        }

        // 增加信号量分发方法 暂时隐藏
       // pcntl_signal_dispatch();
    }

    /**
     * 短信发送
     * @param Job $job
     * @param $data {"orgId":1,"mobiles":["13838379498","13838379497"],"msg":"有新订单需要你的处理","fromId":0,"type":1}
     */
    public function qxsms(Job $job, $data){
        $ndata = json_decode($data,true);
        $ret = $this->sendSms($ndata['mobiles'],$ndata['msg'],$ndata['orgId'],$ndata['type']);
        if($ret){
            $job->delete();
        }else{
            if ($job->attempts() > 2) { //重试2次任务失败后记录失败日志
                $this->jobFail('qxsms',$data);
                $job->delete(); // 删除任务
            }else{
                $job->release(3); // 3秒后重新执行
            }
        }

        // 增加信号量分发方法
        //pcntl_signal_dispatch();
    }

    // 任务失败记录
    private function jobFail($cate,$data){
        Db::name('jobs_fail')->insert([
            'cate' => $cate,
            'payload' => $data,
            'create_time' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 发送短信
     * @param array $mobiles 手机号
     * @param string $msg 短信内容
     * @param int $orgId
     * @return bool
     */
    private function sendSms($mobiles=[],$msg='',$orgId=0,$fromId=0,$type=1){
        if(!$mobiles){
            return true;
        }
        try{
            $config = config('app.sms_config');
            if(empty($config['qx_corpid']) || empty($config['qx_pwd']) || empty($config['name'])){
                exception('短信配置缺少');
            }
            $msg = '【'.$config['name'].'】'.$msg;
            $sms = new Qxsms($config);
            $smsonoff = (new Config())->getConfig('web_send_sms');
            $smsorgonoff = (new Config())->getConfig('org_send_sms',$orgId);
            if($smsonoff && $smsorgonoff){
                $ret = $sms->send(implode(',',$mobiles),$msg);
                if(!$ret){
                    exception($sms->getError());
                }

                // 短信日志
                (new SmsLog())->addLog(implode(',',$mobiles),$msg,$orgId,$fromId,$type);
            }
            return true;
        }catch (\Exception $e){
            trace('短信发送失败:'.$e->getMessage());
            trace('短信发送号码:'.implode(',',$mobiles));
            trace('短信发送内容:['.$orgId.']'.$msg);
            return false;
        }
    }

    /**
     * 极光推送
     * @param array $userids
     * @param string $msg
     * @param array $extras
     */
    private function sendJpush($userids,$type,$msg='',$extra=array()){
        if(!$userids){
            return true;
        }
        try { //不管推送成功与失败,不能影响正常业务流程
            $jpushconfig = config('app.jpush');
            $client = new \JPush\Client($jpushconfig['appkey'], $jpushconfig['mastersecret'],null);
            $push = $client->push();
            $push->setOptions(null,null,null, true);
            $push->setPlatform(array('ios', 'android'));
            foreach ($userids as $k=>$v){
                $userids[$k] = (string)$v;
            }
            $push->addAlias($userids);

            $extras = array('type'=>$type);
            if($extra){
                foreach ($extra as $k=>$v){
                    if($k != 'type'){
                        $extras[$k] = $v;
                    }
                }
            }

            $msg = AppMsg::getPushMsg($type,$msg);
            $push->androidNotification($msg, array(
                'extras' => $extras
            ));
            $sound = 'default';
            if($type == 2 || $type == 7){
                $sound = 'type'.$type.'.mp3';
            }
            $push->iosNotification($msg, array(
                'sound' => $sound,
                'badge' => '+1',
                'extras' => $extras
            ));
            $ret = $push->send();
            trace($ret);
            return true;
        } catch (\Exception $e) {
            trace('push-error:'.$e->getMessage());
            return false;
        }
    }

    /**
     * 自动派单轮转
     * @param Job $job
     */
    public function autoSend(Job $job, $data){
        $ndata = json_decode($data,true);
        $ret = $this->toAutoSend($ndata);
        if($ret){
            $job->delete();
        }else{
            if ($job->attempts() > 2) { //重试2次任务失败后记录失败日志
                $this->jobFail('autoSend',$data);
                $job->delete(); // 删除任务
            }else{
                $job->release(3); // 3秒后重新执行
            }
        }
    }

    public function toAutoSend($ndata){
        $min= (new Config())
            ->getConfig('org_auto_send_time');
        $time = intval($min);
        if($time <5){
            return true;
        }
        $orgId = $ndata['org_id'];
        $orgGrabOrder = (new Config())
            ->getConfig('org_grab_order1',$orgId);
        if(!$orgGrabOrder){
            return true;
        }
        $send_off= (new Config())
            ->getConfig('org_auto_send',$orgId);
        if(!$send_off){
            return true;
        }
        $date = date('Y-m-d H:i:s',time()-(60*$time));
        $orders = Db::name('orders')
            ->alias('a')
            ->join('order_repair b','a.id=b.order_id')
            ->where('a.order_mode',1)
            ->where('a.work_type_mode',1)
            ->where('a.org_id',$orgId)
            ->where('a.del',0)
            ->where('a.create_time','<=',$date)
            ->where('b.type_id','>',0)
            ->field('a.id')
            ->select();
        foreach ($orders as $k=>$v){
            (new Orders())->autoSend($v['id']);
        }
        return true;
    }
}