<?php

namespace App\Admin\Actions\Device;

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;
        $device_name = $this->row->device_name;
        $box_info = DeviceBox::where(['device_id'=>$id])->get();
        if(!empty($box_info)){
            foreach ($box_info as $box){
                $box_name = $box->name;
                $lock_info = LockInfo::where(['box_id'=>$box->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,
                    ];
                }

                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()->error($box_name.'下发失败');
                        continue;
                    }
                    sleep(22);
                }
            }
            return $this->response()->success('下发成功')->refresh();
        }
    }
}
