package com.usky.park.controller.web;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.common.core.util.HttpUtils;
import com.usky.common.core.util.JsonUtils;
import com.usky.common.security.utils.SecurityUtils;
import com.usky.park.ApplicationRun;
import com.usky.park.domain.DmpDevice;
import com.usky.park.service.DmpDeviceService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

/**
 * @author zyj
 * @date 2023/2/24 14:52:05
 */
@RestController
@RequestMapping("deviceHttp")
public class DeviceHttpController {

    private static final Logger LOGGER = LoggerFactory.getLogger(DeviceHttpController.class);

    @Autowired
    private DmpDeviceService dmpDeviceService;


    public static final String light_url = "http://172.17.35.51:15224";
    public static final String video_url = "http://172.17.35.51:15225";
    public static final String video1_url = "http://172.17.35.51:15226";
    public static final String guard_url = "http://172.17.35.51:15227";
    public static final String video_devinfo = "http://172.17.35.51:15228";
    public static final String guard_devinfo = "http://172.17.35.51:15229";
    public static final String elevator_devinfo = "http://172.17.35.51:15230";
    public static final String generator_devinfo = "http://172.17.35.51:15231";

    /**
     * 设备管理-照明开关状态控制
     *
     * @param deviceId  设备Id
     * @param switchStatus  开关状态(0 关 1 开)
     * @return
     */
    @GetMapping("lightControl")
    public static String lightControl(@RequestParam(value = "deviceId") String deviceId,
                                      @RequestParam(value = "switchStatus") Integer switchStatus){
        String result;
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","lightControl");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("device_id",deviceId);
        map1.put("switch_status",switchStatus);
        map.put("params",map1);
        map.put("id",3);
        try {
            result  = HttpUtils.postJson(light_url,map,null);
        } catch (IOException e) {
            result = "{\"code\": \"0\",\"msg\": \"success\",\"data\": \""+e.getMessage()+"\"}";
        }
        return result;
    }

    /**
     * 设备管理-监控系统实时视频预览取流
     *
     * @param deviceId  设备Id
     * @param streamType  码流类型，0:主码流 1:子码流 2:第三码流 参数不填，默认为主码流
     * @param protocol  取流协议（应用层协议），“rtsp”:RTSP协议,“rtmp”:RTMP协议,“hls”:HLS协议（HLS协议只支持海康SDK协议、EHOME协议、GB28181协议、ONVIF协议接入的设备；只支持H264视频编码和AAC音频编码）,参数不填，默认为RTSP协议
     * @param transmode  传输协议（传输层协议），0:UDP 1:TCP 默认是TCP 注： GB28181 2011及以前版本只支持UDP传输
     * @return
     */
    @GetMapping("videoUrl")
    public static String videoUrl(@RequestParam(value = "deviceId") String deviceId,
                                  @RequestParam(value = "streamType") Integer streamType,
                                  @RequestParam(value = "protocol") String protocol,
                                  @RequestParam(value = "transmode") Integer transmode){
        String result;
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","videoUrl");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("device_id",deviceId);
        map1.put("streamType",streamType);
        map1.put("protocol",protocol);
        map1.put("transmode",transmode);
        map.put("params",map1);
        map.put("id",3);
        try {
            result  = HttpUtils.postJson(video_url,map,null);
        } catch (IOException e) {
            throw new BusinessException("设备管理-监控系统实时视频预览取流http调用异常"+e.getMessage());
        }
        return result;
    }

    /**
     * 设备管理-监控系统云台操作
     *
     * @param deviceId  设备Id
     * @param action  0-开始 1-停止 注：GOTO_PRESET命令下填任意值均可转到预置点,建议填0即可
     * @param command  不区分大小写 说明： LEFT 左转 RIGHT右转 UP 上转 DOWN 下转 ZOOM_IN 焦距变大 ZOOM_OUT 焦距变小 LEFT_UP 左上 LEFT_DOWN 左下 RIGHT_UP 右上 RIGHT_DOWN 右下 FOCUS_NEAR 焦点前移 FOCUS_FAR 焦点后移 IRIS_ENLARGE 光圈扩大 IRIS_REDUCE 光圈缩小 WIPER_SWITCH 接通雨刷开关 START_RECORD_TRACK 开始记录轨迹 STOP_RECORD_TRACK 停止记录轨迹 START_TRACK 开始轨迹 STOP_TRACK 停止轨迹 以下命令presetIndex不可 为空： GOTO_PRESET到预置点
     * @param speed  云台速度，取值范围为1-100，默认50
     * @param presetIndex 预置点编号，整数，通常在300以内
     * @return
     */
    @GetMapping("videoControl")
    public static String videoControl(@RequestParam(value = "deviceId") String deviceId,
                                    @RequestParam(value = "action") Integer action,
                                    @RequestParam(value = "command") String command,
                                    @RequestParam(value = "speed") Integer speed,
                                     @RequestParam(value = "presetIndex") Integer presetIndex){
        String result;
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","videoControl");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("device_id",deviceId);
        map1.put("action",action);
        map1.put("command",command);
        map1.put("speed",speed);
        map1.put("presetIndex",presetIndex);
        map.put("params",map1);
        map.put("id",3);
        try {
            result  = HttpUtils.postJson(video1_url,map,null);
        } catch (IOException e) {
            throw new BusinessException("设备管理-监控系统云台操作http调用异常"+e.getMessage());
        }
        return result;
    }

    /**
     * 设备管理-门禁系统门禁点反控
     *
     * @param deviceId  设备Id
     * @param controlType  0-常开 1-门闭 2-门开 3-常闭
     * @return
     */
    @GetMapping("guardControl")
    public static String guardControl(@RequestParam(value = "deviceId") String deviceId,
                                      @RequestParam(value = "controlType") Integer controlType){
        String result;
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","guardControl");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("device_id",deviceId);
        map1.put("controlType",controlType);
        map.put("params",map1);
        map.put("id",3);
        try {
            result  = HttpUtils.postJson(guard_url,map,null);
        } catch (IOException e) {
            throw new BusinessException("设备管理-门禁系统门禁点反控http调用异常"+e.getMessage());
        }
        return result;
    }

    /**
     * 设备管理-监控系统、门禁系统、梯控系统设备信息同步
     *
     * @param deviceType  设备类型（501、监控系统  502、门禁系统  503、梯控系统 ）
     * @param regionIndexCodes  所在区域
     * @return
     */
    @GetMapping("DeviceInfo")
    public String DeviceInfo(@RequestParam(value = "deviceType") Integer deviceType,
                                      @RequestParam(value = "regionIndexCodes") List<String> regionIndexCodes){
        String result = "";
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","DeviceInfo");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("regionIndexCodes",regionIndexCodes);
        map.put("params",map1);
        map.put("id",3);
        try {
            if(deviceType == 501){
                result  = HttpUtils.postJson(video_devinfo,map,null);
            }else if(deviceType == 502){
                result  = HttpUtils.postJson(guard_devinfo,map,null);
            }else if(deviceType == 503){
                result  = HttpUtils.postJson(elevator_devinfo,map,null);
            }
            Map data_map = JsonUtils.fromJson(result,Map.class);
            List<Map<String,Object>> data = (List) JSONObject.parseArray(JSONObject.toJSONString(data_map.get("data")));
            for(int i=0;i<data.size();i++){
                int flag = (int)(data.get(i).get("flag"));   //1 新增 0 更新 -1 删除
                String device_id = data.get(i).get("device_id").toString();
                String device_code = data.get(i).get("device_code").toString();
                String device_name = data.get(i).get("device_name").toString();
                String product_id = data.get(i).get("product_id").toString();
                String company_code = data.get(i).get("company_code").toString();


                if(flag == -1){
                    LambdaUpdateWrapper<DmpDevice> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(DmpDevice::getDeviceId,device_id)
                            .set(DmpDevice::getProductId,product_id)
                            .set(DmpDevice::getUpdatedTime,LocalDateTime.now())
                            .set(DmpDevice::getDeleteFlag,1)
                            .eq(DmpDevice::getDeviceCode,device_code);
                    dmpDeviceService.update(updateWrapper);

                }else if(flag == 0){
                    LambdaUpdateWrapper<DmpDevice> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(DmpDevice::getDeviceId,device_id)
                            .set(DmpDevice::getDeviceName,device_name)
                            .set(DmpDevice::getProductId,product_id)
                            .set(DmpDevice::getUpdatedTime,LocalDateTime.now())
                            .eq(DmpDevice::getDeviceCode,device_code);
                    dmpDeviceService.update(updateWrapper);
                }else if(flag == 1){
                    DmpDevice dmpDevice = new DmpDevice();
                    dmpDevice.setDeviceId(device_id);
                    dmpDevice.setDeviceCode(device_code);
                    dmpDevice.setDeviceName(device_name);
                    dmpDevice.setDeviceType(deviceType);
                    dmpDevice.setProductId(Integer.parseInt(product_id));
                    dmpDevice.setCompanyCode(company_code);
                    dmpDevice.setDeleteFlag(0);
                    dmpDevice.setCreatedTime(LocalDateTime.now());
                    dmpDeviceService.save(dmpDevice);
                }
            }

        } catch (IOException e) {
            throw new BusinessException("设备管理-监控系统、门禁系统、梯控系统设备信息同步http调用异常"+e.getMessage());
        }

        String data = "{\"code\": \"0\",\"msg\": \"success\",\"data\": \"\"}";
        return data;
    }

    /**
     * 设备管理-机房系统设备信息同步
     *
     * @param sceneId  项目ID
     * @return
     */
    @GetMapping("GeneratorDevInfo")
    public String GeneratorDevInfo(@RequestParam(value = "sceneId") String sceneId){
        String result = "";
        Map<String,Object> map = new HashMap<>();
        map.put("jsonrpc","2.0");
        map.put("method","GeneratorDevInfo");
        Map<String,Object> map1 = new HashMap<>();
        map1.put("scene_id",sceneId);
        map.put("params",map1);
        map.put("id",3);
        String str = "";
        try {
            result  = HttpUtils.postJson(generator_devinfo,map,null);

            Map data_map = JsonUtils.fromJson(result,Map.class);
            List<Map<String,Object>> data = (List) JSONObject.parseArray(JSONObject.toJSONString(data_map.get("data")));
            LOGGER.info(JSONObject.toJSONString(data));
            for(int i=0;i<data.size();i++){
                int flag = (int)(data.get(i).get("flag"));   //1 新增 0 更新 -1 删除
                String device_id = data.get(i).get("device_id").toString();
                String device_code = data.get(i).get("device_code").toString();
                String device_name = data.get(i).get("device_name").toString();
                String product_id = data.get(i).get("product_id").toString();
                String company_code = data.get(i).get("company_code").toString();

                if(flag == -1){
//                    LambdaQueryWrapper<DmpDevice> queryWrapper = Wrappers.lambdaQuery();
//                    queryWrapper.eq(DmpDevice::getDeleteFlag,0)
//                            .eq(DmpDevice::getDeviceCode,device_code);
//                    List<DmpDevice> list = dmpDeviceService.list(queryWrapper);
//
//                    if(CollectionUtils.isNotEmpty(list)){
//                        DmpDevice dmpDevice = new DmpDevice();
//                        dmpDevice.setId(list.get(0).getId());
//                        dmpDevice.setDeviceId(device_id);
//                        dmpDevice.setDeviceCode(device_code);
//                        dmpDevice.setDeviceName(device_name);
//                        dmpDevice.setDeviceType(504);
//                        dmpDevice.setProductId(Integer.parseInt(product_id));
//                        dmpDevice.setCompanyCode(company_code);
//                        dmpDevice.setUpdatedTime(LocalDateTime.now());
//                        if(flag == -1){
//                            dmpDevice.setDeviceName(list.get(0).getDeviceName());
//                            dmpDevice.setDeleteFlag(1);
//                           dmpDeviceService.updateById(dmpDevice);
//                        }else if(flag == 0){
//                            dmpDeviceService.updateById(dmpDevice);
//                        }
//                    }
                    LambdaUpdateWrapper<DmpDevice> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(DmpDevice::getDeviceId,device_id)
                            .set(DmpDevice::getProductId,product_id)
                            .set(DmpDevice::getUpdatedTime,LocalDateTime.now())
                            .set(DmpDevice::getDeleteFlag,1)
                            .eq(DmpDevice::getDeviceCode,device_code);
                    dmpDeviceService.update(updateWrapper);

                }else if(flag == 0){
                    LambdaUpdateWrapper<DmpDevice> updateWrapper = Wrappers.lambdaUpdate();
                    updateWrapper.set(DmpDevice::getDeviceId,device_id)
                            .set(DmpDevice::getDeviceName,device_name)
                            .set(DmpDevice::getProductId,product_id)
                            .set(DmpDevice::getUpdatedTime,LocalDateTime.now())
                            .eq(DmpDevice::getDeviceCode,device_code);
                    dmpDeviceService.update(updateWrapper);
                }else if(flag == 1){
                    DmpDevice dmpDevice = new DmpDevice();
                    dmpDevice.setDeviceId(device_id);
                    dmpDevice.setDeviceCode(device_code);
                    dmpDevice.setDeviceName(device_name);
                    dmpDevice.setDeviceType(504);
                    dmpDevice.setProductId(Integer.parseInt(product_id));
                    dmpDevice.setCompanyCode(company_code);
                    dmpDevice.setDeleteFlag(0);
                    dmpDevice.setCreatedTime(LocalDateTime.now());
                    dmpDeviceService.save(dmpDevice);
                }
            }

        } catch (IOException e) {
            throw new BusinessException("设备管理-机房系统设备信息同步http调用异常"+e.getMessage());
        }
        String data = "{\"code\": \"0\",\"msg\": \"success\",\"data\": \"\"}";
        return data;
    }
}
