<?php

namespace App\Admin\Actions\Device;

use App\Model\DeviceBox;
use App\Model\DeviceInfo;
use App\Model\LockInfo;
use App\Server\DeviceServer;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class sendRule extends RowAction
{
    public $name = '下发协议';


    public function handle(Model $model, Request $request)
    {
        $id = $this->row->id;
        $device_name = $this->row->device_name;
        if(empty($device_name)) return true;
        $lock_info = LockInfo::where(['device_id'=>$id,'status'=>1])->orderBy('box_type','asc')->get()->GroupBy('box_type');
        foreach ($lock_info as $lock){
            if(empty($lock)) continue;
            $send_rule = [];
            foreach ($lock as $protol){
                $data = [
                    'open'=>$protol->open_time,
                    'close'=>$protol->close_time,
                    'start'=>$protol->start_time,
                    'type'=>$protol['type'],
                ];
                if(empty($protol->value[0])) {
                    $data['value']= '';
                } else {
                    $data['value']= $protol->value;
                }
                $send_rule["box".$protol->box_type][] = $data;
            }
            if(!empty($send_rule)) {
                $send_rule['query'] = 3600;
                $res = (new DeviceServer())->sendMsg($device_name,json_encode($send_rule));
                sleep('22');
//                    if($res['Success'] != true){
//                        return $this->response()->error($device_name.'下发失败');
//                        continue;
//                    }
                Log::info('执行规则'.json_encode($send_rule).PHP_EOL);
            }
        }
        return $this->response()->success('下发成功')->refresh();
    }
}
