<?php

namespace App\Console\Commands;

use App\Models\InnerDevice;
use App\Models\Order;
use App\Models\OrderDevice;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class UpdateApplyDevice extends Command
{

    protected $name = 'updateApplyDevice';
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:apply';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description apply';

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

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        /*
         * 归还时间逻辑 前天时间<订单结束时间<今天时间
         * 订单完成逻辑 订单里但凡有一个未到期，就算未完成，最后一个设备到期了，才算完成
         * 归还设备逻辑 到期的设备的状态直接变为闲置
         * */
        //当天日期
        $today_time = date('Y-m-d');
        Log::info($today_time."开始处理归还设备");
        //前天日期
        $before_yesterday_time = date('Y-m-d',strtotime('-2 days'));
        //获取到订单内有过期设备的订单数据
        $all_orders = OrderDevice::whereBetween('end_date',[$before_yesterday_time,$today_time])->whereNotNull('inner_device_id')->get(['order_id','inner_device_id'])->toArray();
        foreach ($all_orders as $value){
            //查找订单下是否有未过期的设备
            $conut = OrderDevice::where('order_id',$value['order_id'])->where('end_date','>',$today_time)->get()->count();
            //如果没有过期时间大于当天的设备就将他完成
            if ($conut == 0)
            {
                Log::info($value['order_id']."订单已完成");
                Order::where('id',$value['order_id'])->update(['status'=>3]);
            }
            //设备状态置为闲置
            Log::info($value['order_id']."订单".$value['inner_device_id']."设备闲置");
            InnerDevice::where('id',$value['inner_device_id'])->update(['status'=>6]);
        }
    }
}
