<?php

namespace App\Admin\Actions\Device;

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

class testRule extends RowAction
{
    public $name = '测试命令';

    public function handle(Model $model, Request $request)
    {
        set_time_limit(1200);
        $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;
                $test_json = $request->get($box_name);
                if(is_null(json_decode($test_json))){
                    return $this->response()->error($box_name.'下发数据必须是json');
                }
                if(!empty($test_json) && json_decode($test_json)){
                    Log::info($test_json.PHP_EOL);
                    (new DeviceServer())->sendMsg($device_name,$test_json);
                    sleep(18);
                }
            }
            return $this->response()->success('下发成功')->refresh();

        }
    }


    public function form()
    {
        $id = $this->row->id;
        $box_info = DeviceBox::where(['device_id'=>$id])->get();
        if(!empty($box_info)){
            foreach ($box_info as $box){
                $box_name = $box->name;
                $this->textarea($box_name,'请输入'.$box_name.'测试json');
            }
        }
    }

}
