<?php

namespace App\Console\Commands;

use App\Models\OrderPack;
use Illuminate\Console\Command;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '服务包过期检测，定时任务1个小时跑一次';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $hour = date('H');
        if ($hour == 12) {
            //还差3天过期
            $this->checkPackExpire(1);
            //还差1天过期
            $this->checkPackExpire(2);
        }

        //已经过期了
        $this->checkPackExpire(3);

        return true;
    }

    private function checkPackExpire($expire_type)
    {
        $end_time = strtotime('+3 days');
        $send_type = 8;
        $expire_type_arr = [1];
        $expire_type_new = 2;
        if ($expire_type == 2) {
            $end_time = strtotime('+1 days');
            $expire_type_arr = [1,2];
            $expire_type_new = 3;
        }
        if ($expire_type == 3) {
            $end_time = time();
            $send_type = 9;
            $expire_type_arr = [1,2,3];
            $expire_type_new = 4;
        }
        $orderPack = OrderPack::with(['user'])->whereIn('expire_type', $expire_type_arr)->where('end_time', '<', $end_time)->get()->toArray();
        if (!empty($orderPack)) {
            foreach ($orderPack as $k => $v) {
                //更新订单服务包过期类型
                OrderPack::where('id', $v['id'])->update(['expire_type' => $expire_type_new]);
                //发送微信消息
                $official_arr = [$v['user']['openid'], $v['pack_name'], date('Y-m-d H:i:s', $v['start_time']), date('Y-m-d H:i:s', $v['end_time'])];
                $service_time = date('Y/m/d', $v['start_time']). ' - '. date('Y/m/d', $v['end_time']);
                $subscribe_arr = [$v['user']['openid'], $v['pack_name'], $service_time, $v['user']['nickname']];
                send_wechat_message($send_type, $official_arr, $subscribe_arr);
            }
        }

        return true;
    }
}
