<?php

namespace App\Http\Controllers;

use App\Model\DeviceInfo;
use App\Model\LockInfo;
use App\Model\SystemConfig;
use App\Server\DeviceServer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Cache;
use QL\QueryList;

class IndexController extends Controller
{
    public function testOpreation(Request $request)
    {
        return view('test_opreation',[]);
    }

    function object_array($array) {
        if(is_object($array)) {
            $array = (array)$array;
        }
        if(is_array($array)) {
            foreach($array as $key=>$value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }

    //下发协议
    public function send_protocol()
    {
        $type = request('type');
        $id = request('id');
        $status = request('status');
        $device  = DeviceInfo::where('device_name',$id)->first();
        $cache_key = $id .'rule_type';
        $re_type = Cache::get($cache_key);

        $time1 = 240;//3分钟定时
        $opt = 180;
        $cpt = 240;
        if($status !== '在营'){
            return json_encode(['code'=>604,'msg'=>'设备不在线，无法下发命令']);
        }
        if(empty($type) || empty($id)){
            return json_encode(['code'=>601,'msg'=>'缺少必要参数']);
        }
        if(empty($device)){
            return json_encode(['code'=>602,'msg'=>'设备不存在']);
        }
//        echo '缓存类型--'.$re_type.' 当前类型:--'.$type;

        if(empty($re_type) && in_array([4,5,6],$re_type)){
            if($type == 4) Cache::put($cache_key,$re_type,$time1);
        } else {
            if($type != $re_type) return json_encode(['code'=>603,'msg'=>'设备下发协议冲突']);
        }
//        return json_encode(['code'=>200,'msg'=>'不重复']);
        switch ($type){
            case 1:
                $rule = ['cmd'=>'start_test'];
                break;
            case 2:
                $rule = ["cmd"=>"stop_test"];
                sleep(6);
                break;
            case 3:
                $open_time = date('H:i',(time() + $opt));
                $close_time = date('H:i',(time() + $cpt));
                $start_time = date('Y-m-d H:i:s',(time() - 60));
                $type_arr = [1=>4,2=>5,3=>5,4=>6];
                for ($i = 1; $i<=$type_arr[$type]; $i++){
                    $rule = ['box'.$i=>[['type'=>1,'start'=>$start_time,'open'=>$open_time,'close'=>$close_time,'value'=>'']],'query'=>3600];
                    $res = (new DeviceServer())->sendMsg($device->device_name ,json_encode($rule));
                    sleep(22);
                }
                break;
            case 4:
                $box_name = request('box_name');
                if(empty($box_name)){
                    return json_encode(['code'=>601,'msg'=>'缺少必要参数']);
                }
                $open_time = date('H:i',(time() + $opt));
                $close_time = date('H:i',(time() + $cpt));
                $start_time = date('Y-m-d H:i',(time() - 60));
                $rule = ['box'.$box_name=>[['type'=>1,'start'=>$start_time,'open'=>$open_time,'close'=>$close_time,'value'=>''],],'query'=>3600];
                break;
            case 5:
                $rule = ["cmd"=>"start_update"];
                break;
            case 6:
                $rule = ["cmd"=>"reset"];
                break;
            default:
                $rule = [];
        }
//        $rule = ["cmd"=>"stop_test"];
//        dd(json_encode($rule));
        if($type != 3){
            $res = (new DeviceServer())->sendMsg($device->device_name,json_encode($rule));
        }
        if(!empty($res) && $res['Success'] == true){
            return json_encode(['code'=>200,'msg'=>'下发命令成功']);
        } else {
            return json_encode(['code'=>601,'msg'=>'下发命令失败']);
        }


    }

    //获取设备信息
    public function get_boxname()
    {
        $id = request('id');
        $device  = DeviceInfo::where('device_name',$id)->first();
        if(empty($device)){
            return json_encode(['code'=>200,'msg'=>'ok','data'=>[]]);
        }
        $lock_config = SystemConfig::get('lock_config');


        $data['id'] = $device->id;
        $data['device_name'] = $device->device_name;
        $data['device_type'] = $device->device_type;
        $deviceService = (new DeviceServer());
        $iot_id = $device->iot_id;
        $device_property = $deviceService->getProperty($iot_id);
        $res = $deviceService->getDeviceStatus($iot_id);
        $sta_arr = DeviceInfo::getStatus();

        $data['status'] = $sta_arr[$res];
        $data['version'] = $device_property['data']['version'];


        $img_field_arr = [
            1=>'box_img_four',
            2=>'box_img_five',
            3=>'box_img_refour',
            4=>'box_img_refive',
        ];
        if(empty($device->device_type)){
            $data['device_image'] = $lock_config['box_img_four'];
        } else {
            $data['device_image'] = $lock_config[$img_field_arr[$device->device_type]];

        }

        return json_encode(['code'=>200,'msg'=>'ok','data'=>$data]);
    }

    //设备升级与重置命令
    public function updateDevice()
    {
        $device_name = request('id');
        $type = request('type'); //设备类型
        $phone = request('phone'); //电话
        $deviceService = (new DeviceServer());
        if(empty($type) || empty($phone)){
            return genApiData(601,'参数错误');
        }
        if(!preg_match("/^1[34578]\d{9}$/",$phone,$match)){
            return genApiData(601,'手机号码错误');
        }
        $data['device_type'] = $type;
        $data['phone'] = $phone;
        $device_info = DeviceInfo::where(['device_name'=>$device_name])->first();
        if($device_info->device_type == $type){
            return genApiData(602,'设备类型重复请重新选择');
        }
        $device_property = $deviceService->getProperty($device_info->iot_id);
        $res = DeviceInfo::where('device_name',$device_name)->update($data);
        $last_version = SystemConfig::get('lock_config','soft_version');

        if($res){
            if($device_property['data']['version'] == '' || $device_property['data']['version'] != $last_version){
                $rule = ["cmd"=>"start_update"];
                $res = $deviceService->sendMsg($device_name ,json_encode($rule));
                if($res['Success'] == 'success') {
                    return genApiData(200,'设备更新新中');
                }
            } else {
                $res = DeviceInfo::where('device_name',$device_name)->update($data);
            }
            return genApiData(200,'更新成功');
        }
        return genApiData(601,'异常设备,请联系后台管理员',$res);
    }


    //设备版本号升级信息
    public function getDevice()
    {
        $id = request('id');
        if(empty($id)){
            return genApiData(601,'设别号必须');
        }
        $device_info = DeviceInfo::where(['device_name'=>$id])->first();

        if(empty($device_info)){
            return genApiData('601','无效设备');
        }
        $iot_id = $device_info->iot_id;
        $deviceService = (new DeviceServer());
        $last_version = SystemConfig::get('lock_config','soft_version');

        $res = $deviceService->getDeviceStatus($iot_id);
        $property = $deviceService->getProperty($iot_id);



        $sta_arr = DeviceInfo::getStatus();
        $data['id'] = $id;
        $data['status'] = $sta_arr[$res];
        $data['version'] = $property['data']['version'];
        $data['device_type'] = $device_info['device_type'];
        $data['phone'] = $device_info['phone'];
        $data['is_last'] = 1;
        if($property['data']['version'] !== $last_version){
            $data['is_last'] = 0;
        }

        return genApiData(200,'ok',$data);
    }


    //更新设备版本
    public function upVersion()
    {
        $id = request('id');
        $type = request('type');

        if(empty($id) || empty($type))
        {
            return genApiData(601,'参数缺失');
        }

        $last_version = SystemConfig::get('lock_config','soft_version');

        $device_info = DeviceInfo::where(['device_name'=>$id])->first();
        if(empty($device_info)){
            return genApiData('601','无效设备');
        }

        $iot_id = $device_info->iot_id;
        $device_name = $device_info->device_name;
        $deviceService = (new DeviceServer());
        $property = $deviceService->getProperty($iot_id);
        if(!empty($property['data']['version']) && $last_version != $property['data']['version']  && $type == 1 ){
            return genApiData(603,'设备已是最新版本，无需更新');
        }
        $type == 1 ? $rule = ['cmd'=>'start_update'] : $rule = ['ResDefault'=>0];
        $res = $deviceService->sendMsg($device_name ,json_encode($rule));

        if($res['Success'] == 'success') {
            return genApiData(200,'操作成功');
        }

        return genApiData(602,'操作失败');
    }

    //获取设备列表
    public function getDevcielist()
    {
      $list = DeviceInfo::pluck('device_name')->toArray();
      return genApiData(200,'ok',$list);
    }

}

