<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Subscribe\Services\OrderService;
use Redis;
use App\Libs\SMS;
use Log;
use DB;
use App\Jobs\SendTexts;
class FailOrderAlert extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'foa {--qrcode}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '失败订单预警';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $options = $this->option('qrcode');
        if($options){
            return $this->forceSubscribeErrorAlert();
        } else{
            $this->tooLongNoOrderAlert();
            return  $this->start();

        }
    }

    private function start(){
        if(!$this->isCanAlert()) return 1;
        $sorce = $this->getPaySource();
        if(!$sorce){
            return false;
        }
        foreach ($sorce as $v){
            $is_all_fail= $this->isAllFail($v->source);
            $too_long = $this->lastOrderTooLong();
            $content = '';
            if($is_all_fail){
                $content = '订单预警,'.$v->source.'通道最近20个订单都是未支付订单,尽快排查';
            }

            if($too_long){
                $content = $v->source.'通道最近半小时没有产生一条订单,尽快排查';
            }
            if(!$content) return 2;

            $phone_arr = ['15868100210','18072713392','15088790066','13858057394','18668029091','18668420256'];
            //$phone_arr = ['18668029091'];
            foreach ($phone_arr as $phone){
                $this->sendAndRecord(1,$phone,$content);
            }
            $key = 'distribution_channel_id:orderalert';
            $field = 'sendalert';
            Redis::hset($key,$field,time());
        }

        return 3;

    }

    private function forceSubscribeErrorAlert(){
        $errors = Redis::SMEMBERS('force_subscribe_qrcode:error');
        if(!$errors){
            return false;
        }

        $res = [];
        foreach ($errors as $value){
            $temp = explode('_',$value);
            $res[$temp[0]][] = $temp[1];
        }
        $phone_arr = ['15868100210','18072713392','15088790066','13858057394','18668029091','18668420256'];
        //$phone_arr = ['18668029091'];
        if($res){
            foreach ($res as $k=>$v){
                if(count($v) >= 5){
                    $content = 'appid='.$k.'的公众号获取强关二维码出问题了！！,一分钟之内出现'.count($v).'次';
                    foreach ($phone_arr as $phone){
                        SMS::send($phone,$content);
                    }
                    //break;
                }
            }
        }
        Redis::srem('force_subscribe_qrcode:error',$errors);
        return false;
    }

    private  function tooLongNoOrderAlert(){
        $last = DB::table('orders')->orderBy('id','desc')->first();
        if(time()-strtotime($last->created_at) >= 150){
            $phone_arr = ['15868100210','18072713392','15088790066','13858057394','18668029091','18668420256'];
            //$phone_arr = ['18668029091'];
            $content = '订单预警,最近两分半没有产生一条订单，尽快排查';
            foreach ($phone_arr as $phone){
                echo SMS::send($phone,$content);
            }
        }
    }

    private function getAllChannel(){
        return OrderService::getAllChannelId();
    }

    private function getPaySource(){
        $sql = 'select distinct pay_merchant_id from distribution_channels where pay_merchant_id <>0';
        $res = DB::select($sql);
        $id_array = [];
        if($res){
            foreach ($res as $v){
                $id_array[] = $v->pay_merchant_id;
            }
        }
        $ssql = 'select distinct source from pay_merchants where id in('.implode(',',$id_array).')';
        $source = DB::select($ssql);;
        return $source;
    }
    /**
     * 最近20订单是否全部失败
     * @param $channel
     * @param int $num
     * @return bool
     */
    private  function isAllFail($source,$num=20){
        $order = OrderService::getLatestOrderByChannleId($source,$num);

        if(!$order)  return false;
        if($order && count($order) < $num){
            return false;
        }
        foreach ($order as $val){
            if($val->status == 'PAID'){
                return false;
            }

        }
        return true;
    }

    /**
     * 最后一条订单距离现在是否超过半小时
     * @return bool
     */
    private function lastOrderTooLong(){
        $order = OrderService::getLastOrder();
        if(time()-strtotime($order->created_at) > 1800){
            return true;
        }
        return false;
    }

    /**
     * 是否可以发送预警
     * @param $channel
     * @return bool
     */
    private function isCanAlert(){
        $key = 'distribution_channel_id:orderalert';
        $field = 'sendalert';
        $res = Redis::hget($key,$field);
        if($res && (time()-$res) < 1800 ){
            return false;
        }
        return true;
    }

    /**
     * 发送预警，并记录
     * @param $channel_info
     * @param $content
     * @return bool
     */
    private function sendAndRecord($channel,$phone,$content){
        if(empty($phone)){
            return false;
        }
        $status = SMS::send($phone,$content);

        $record = json_encode([
            'phone'=>$phone,
            'status'=>$status,
            'time'=>time()
        ]);
        $key = 'distribution_channel_id:orderalert:record';
        Redis::rpush($key,$record);
    }
}
