<?php

namespace App\Admin\Actions\Box;

use App\Model\DeviceBox;
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;
        $box_name = $this->row->name;
        $device_name = $this->row->devices->device_name;
        $lock_info = LockInfo::where(['box_id'=>$id,'status'=>1])->get();
        $rule = [];
        foreach ($lock_info as $val){
            $rule[$box_name][] =  [
                'open'=>$val->open_time,
                'close'=>$val->close_time,
                'start'=>$val->start_time,
                'type'=>$val->type,
                'value'=>$val->value,
            ];
        }
//        return $this->response()->success(json_encode($rule))->refresh();

        if(!empty($rule)){
            $rule['query'] = 1800;
            Log::info(json_encode($rule).PHP_EOL);
            $res = (new DeviceServer())->sendMsg($device_name,json_encode($rule));
            if($res['Success'] == true){
                return $this->response()->success('下发成功')->refresh();
            }
        }
        return $this->response()->error('下发失败')->refresh();
    }

}
