<?php

namespace App\Listeners;

use App\Console\Commands\SendDeviceRule;
use App\Model\DeviceBox;
use App\Model\DeviceInfo;
use App\Model\DeviceType;
use App\Model\DeviceTypeBox;
use App\Model\LockInfo;
use App\Model\SystemConfig;
use App\Server\DeviceServer;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use App\Events\DeviceEvent;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Console\Scheduling\Schedule;


class DeviceEventListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  object  $event
     * @return void
     */
    public function handle(DeviceEvent $event)
    {
        $device = $event->device;
        if(!empty($device->device_type)){
            $this->addBox($device);
            Log::info('有数据'.$device->device_type);
        } else {
            Log::info('没数据'.$device->device_type);
        }

        return true;
    }

    public function  addBox($device){
        $lock_config = SystemConfig::get('lock_config');
        $type = $device->device_type;
        switch($type) {
            case  DeviceInfo::BOXFOUR;
                $n = 4;
                break;
            case DeviceInfo::BOXFIVE;
                $n = 5;
                break;
            case DeviceInfo::BOXFOURRECYCLE;
                $n = 5;
                break;
            case DeviceInfo::BOXFIVERECYCLE;
                $n = 6;
                break;
            default;
                $n = 4;
                break;
        }

        $now = date('Y-m-d H:i:s',time());

        $lcount = LockInfo::where(['device_id' =>$device->id])->count();
        Log::info('现有多少个·'.$lcount);

        if($lcount != 0){
            LockInfo::where(['device_id'=>$device->id])->delete();
        }
        for($i=1;$i<=$n;$i++){
            $data = ['device_id'=>$device->id,'type'=>2,'time_type'=>1,'open_time'=>$lock_config['am_open'],'close_time'=>$lock_config['am_close'],'start_time'=>$now,'box_type'=>$i,'value'=>'','status'=>1,'created_at'=>$now,'updated_at'=>$now];
            LockInfo::insert($data);
            $data = ['device_id'=>$device->id,'type'=>2,'time_type'=>2,'open_time'=>$lock_config['pm_open'],'close_time'=>$lock_config['pm_close'],'start_time'=>$now,'box_type'=>$i,'value'=>'','status'=>1,'created_at'=>$now,'updated_at'=>$now];
            LockInfo::insert($data);
        }
        Log::info('----执行开始---');
//          Artisan::call('SDR 1 '.$device->id);
//        Artisan::call('email:send 1 --queue=default');
//        $schedule = new Schedule();
//        $schedule->command(SendDeviceRule::class, [1,$device->id]);

        Log::info('----执行结束---');

        return true;
    }
}
