<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Modules\Subscribe\Services\OrderService;
use Redis;
use App\Libs\AliSMS;
use Log;
use DB;
use App\Modules\Subscribe\Models\Order;

class FailOrderAlertV2 extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'foav2';

    /**
     * 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()
    {
        $this->payAlert();
    }

    private function payAlert()
    {
        $pay_ids = $this->getPayId();
        if(!$pay_ids){
            return '';
        }
        foreach ($pay_ids as $pay_id){
            $this->payAlertOne($pay_id);
        }
        return '';
    }

    private function payAlertOne($pay_id)
    {

        $phone_arr = ['15868100210',  '18668029091', '15262937943','18367118561'];
        $pay_info = Redis::hgetall('pay_merchant:'.$pay_id);
        $is_need_alert = false;
        $ntime = time();
        $time_str = 180;   
        // 10min 15min 1.5min 3min 未支付的订单报警规则  96/103 倍道  97树羽
        $alert_time_diff = ['1'=>180,'2'=>180];
        if($pay_info)
        {
            $last_alert_time = isset($pay_info['last_alert_time']) ? (int)$pay_info['last_alert_time'] : 0;//上次报警时间
            if($ntime - $last_alert_time > 180)//2小时内不重复报警
            {
                $unpaid_num = isset($pay_info['unpaid_num']) ?  (int)$pay_info['unpaid_num'] : 0;
                $last_create_time = isset($pay_info['last_create_time']) ?  (int)$pay_info['last_create_time'] : 0;

                $order_num = 10;
                if($unpaid_num  >= $order_num)//超过30条都是失败订单报警
                {
                    $is_need_alert = true;
                    $content = '订单预警!!!支付通道: '.$pay_id.',最近'.$order_num.'个订单都是未支付订单,尽快排查。。';
                    $template_type = 'order_remind';
                    
                    $back_pay = DB::table('pay_merchants')
                        ->where('name','BD_BACK_UP_MAIN')
                        ->where('is_enabled',1)
                        ->select('id')->orderBy('id','desc')->first();
                    if($back_pay){
                        DB::table('distribution_channels')->where('pay_merchant_id',$pay_id)->update([
                            'pay_merchant_id'=>$back_pay->id,
                            'updated_at'=>date('Y-m-d H:i:s')
                        ]);

                        DB::table('pay_merchants')->where('id',$pay_id)->update(['name'=>'BD_DEFAULT2','updated_at'=>date('Y-m-d H:i:s')]);
                        DB::table('pay_merchants')->where('id',$back_pay->id)->update(['name'=>'BD_DEFAULT','updated_at'=>date('Y-m-d H:i:s')]);

                        $param = ['pay_id'=>$pay_id,'new_pay_id' => $back_pay->id];
                        foreach ($phone_arr as $phone){
                            $this->sendSms($phone, 'pay_channel_change',$param);
                            $this->sendSms($phone, 'order_remind',$param);
                        }

                    }else{
                       $param = ['pay_id'=>$pay_id];
                        foreach ($phone_arr as $phone){
                            $this->sendSms($phone, $template_type,$param);
                        } 
                    }
                }

                if(isset($alert_time_diff[$pay_id])  && $last_create_time && ($ntime - $last_create_time) > $alert_time_diff[$pay_id] ){
                    $is_need_alert = true;
                    $content = '支付通道: '.$pay_id.' ,最近'.$time_str.'秒内没有产生一条订单,尽快排查';
                    $template_type = 'order_halfhour_remind';
                    $param = ['pay_id'=>$pay_id];
                    foreach ($phone_arr as $phone){
                        $this->sendSms($phone, $template_type,$param);
                    }
                }

                if($is_need_alert)//更新报警时间
                {
                    Redis::hset('pay_merchant:'.$pay_id,'last_alert_time',$ntime);
                }
            }
        }
    }

    /**
     * 发送预警
     */
    private function sendSms($phone, $template_type,$param){
        if(empty($phone)){
            return false;
        }
        return AliSMS::send($phone, $template_type,$param);
    }

    private function getPayId(){
        $sql = 'select distinct pay_merchant_id from distribution_channels where pay_merchant_id <>0 and id !=14';
        $res = DB::select($sql);
        $id_array = [];
        if($res){
            foreach ($res as $v){
                $id_array[] = $v->pay_merchant_id;
            }
        }
        return $id_array;
    }
}