<?php

namespace App\Console\Commands;

use App\Model\DeviceInfo;
use App\Model\LockInfo;
use App\Server\DeviceServer;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class SendDeviceRule extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'SDR:{id} {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()
    {
        $arguments = $this->arguments();
        Log::info('执行了自动下发协议');
        $id = $arguments['id'];
        if($arguments['type'] == 1){
            $this->sendDevice($id);
        } else {
            $this->sendBox($id);
        }
        dd('ok');
    }

    public function sendDevice($id){
        //找出需要重新下发的设备
        $device_info = LockInfo::where(['status'=>1,'send_status'=>1])->distinct('device_id')->pluck('device_id');
        foreach ( $device_info as $device_id){
            //找出要重新下发的锁位
            $lock_info = LockInfo::where(['device_id'=>$device_id,'status'=>1,'send_status'=>1])->distinct('box_type')->pluck('box_type');
            $device_name = DeviceInfo::where(['id'=>$id])->value('device_name');
            //没有设备名称跳出
            if(empty($device_name)) continue;
            foreach ($lock_info as $box_type){
                //没有锁协议跳出
                $lock = LockInfo::where(['device_id'=>$id,'box_type'=>$box_type])->get();
                if(empty($lock)) continue;
                //dd($lock->toArray());
                $send_rule = [];
                foreach ($lock as $protol){
                    $send_rule["box".$protol->box_type][] = [
                        'open'=>$protol->open_time,
                        'close'=>$protol->close_time,
                        'start'=>$protol['start_time'],
                        'type'=>$protol['type'],
                        'value'=>$protol['value']
                    ];
                    LockInfo::where(['id'=>$protol->id])->updated(['sned_status'=>2]);
                }
                $send_rule['query'] = 3600;
                $res = (new DeviceServer())->sendMsg($device_name ,json_encode($send_rule));
                sleep('20');
                if($res['success'] == 'success') {
                    DeviceInfo::
                }
                Log::info('执行规则'.json_encode($send_rule).PHP_EOL);
            }

        }
        dd($lock_info->toArray());

    }
}
