<?php

namespace App\Console\Commands;

use App\Models\DocterOrganization;
use App\Models\Order;
use App\Models\SystemConfig;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class overTimeOrder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order {type}';

    /**
     * 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()
    {
        $type = $this->argument('type');
        if(!in_array($type,['orderOut','appiontOut','thenOut','thenLose'])){
            dd('请输入正确的参数');
        }
        if($type == 'orderOut'){
            //订单超时
            $this->overTimeOrers();
        } else if($type == 'appiontOut'){
            //预约超时
            $this->AppointReminder();
        }else if($type == 'thenOut'){
            //认证到期
            $this->OutThenReminder();
        }else if($type == 'thenLose'){
            //认证失效
            $this->InvalidThenReminder();
        }
        dd('ok');
    }

    /**
    * 	确认超时提醒 当天的预约订单，医生还未点击完成的订单，23：00给医生发送提醒
    */
    public function AppointReminder(){

        $beginToday=mktime(0,0,0,date('m'),date('d'),date('Y'));
        $endToday=mktime(0,0,0,date('m'),date('d')+1,date('Y'))-1;
        $Order = Order::with(['orderPatient','docter','user'])->where(['order_status'=>3,'payment_status'=>2,'product_type'=>3])->whereBetween('receiving_time',[$beginToday,$endToday])->get();
        foreach ($Order as $k=>$v){
            if ($v['docter']){
                if ($v['docter']['openid']){
                    $send = send_wechatSubscription_message('appoint_reminder',[$v['docter']['openid'], "pages/index/index",$v['order_sn'],$v['user']['nickname'],$v['user']['phone'],$v['created_at']]);
                }
            }
        }
    }

    /**
     * 签约失效提醒
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function InvalidThenReminder(){
        $list = DocterOrganization::with('docter','organization')->get();
        if($list){
            foreach ($list as $k=>$v){
                if ($v['docter']['openid']&& time()>=strtotime($v['authentication_end_time'])){
                    $send = send_wechatSubscription_message('out_then_reminder',[$v['docter']['openid'],  "pages/index/index", $v['organization']['name'],date('Y-m-d',strtotime($v['authentication_end_time']))]);
                }
            }
        }

    }


    /**
     * 认证到期提醒
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function OutThenReminder(){
        $list = DocterOrganization::with('docter','organization')->get();
        if($list){
            foreach ($list as $k=>$v){
                if ($v['docter']['openid']&& (strtotime($v['authentication_end_time'])-strtotime($v['authentication_time']))<=(1*60*60*24)){
                    $send = send_wechatSubscription_message('out_then_reminder',[$v['docter']['openid'],  "pages/index/index", $v['organization']['name'],date('Y-m-d',strtotime($v['authentication_end_time']))]);
                }
            }
        }
    }

    /**
     * 订单超时自动完成（定时）
     */
    public function overTimeOrers(){
        $config_chat =  SystemConfig::get('docter_config','chat_complete_time');
        $config_phone =  SystemConfig::get('docter_config','phone_complete_time');

        // 换算为秒
        $config_chat = intval($config_chat)*60;
        $config_phone = intval($config_phone)*60;

        $inOrder = Order::with('orderPatient')->where(['order_status'=>3,'payment_status'=>2])->get();
        $catNewIds = [];
        $menNewIds = [];
        foreach ($inOrder as $k=>$v){
            if ($v['product_type']==1){
                if ((time()-$v['receiving_time'])>=$config_chat){
                    $catNewIds[$k] = $v['id'];
                }
            }else if($v['product_type']==2){
                if ((time()-$v['receiving_time'])>=$config_phone){
                    $catNewIds[$k] = $v['id'];
                }
            }else if($v['product_type']==3){
                if ((time()-$v['receiving_time'])>=(1*60*60*24)){
                    $menNewIds[$k] = $v['id'];
                }
            }

        }
        if ($catNewIds || $menNewIds){
            // 操作图文和电话订单为已完成
            Order::whereIn('id',$catNewIds)->update(['order_status'=>4]);
            // 操作门诊订单为已超时
            Order::whereIn('id',$menNewIds)->update(['order_status'=>6]);
        }
    }
}
