package com.yfd.platform.modules.robotcomand.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yfd.platform.component.WebSocketServer;
import com.yfd.platform.config.HttpServerConfig;
import com.yfd.platform.config.ResponseResult;
import com.yfd.platform.modules.basedata.domain.SubstationDevice;
import com.yfd.platform.modules.basedata.domain.SubstationPatroldevice;
import com.yfd.platform.modules.basedata.service.ISubstationDeviceService;
import com.yfd.platform.modules.basedata.service.ISubstationPatroldeviceService;
import com.yfd.platform.modules.robotcomand.service.RobotUdpService;
import com.yfd.platform.system.service.ISysDictionaryItemsService;
import com.yfd.platform.utils.HttpRESTfulUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * @Date: 2023/9/21 16:40
 * @Description:
 */
@RestController
@RequestMapping("/robot/udp")
@Api(value = "RobotUdpController", tags = "机器人指令发送")
@Slf4j
public class RobotUdpController {

    @Resource
    private RobotUdpService robotUdpService;
    @Resource
    private HttpRESTfulUtils httpRESTfulUtils;
    @Resource
    private HttpServerConfig httpServerConfig;

    @Resource
    private ISysDictionaryItemsService sysDictionaryItemsService;
    @Resource
    private ISubstationDeviceService substationDeviceService;
    @Resource
    private ISubstationPatroldeviceService substationPatroldeviceService;

    @ApiOperation("控制机器人")
    @GetMapping("/sendCommand")
    public ResponseResult sendCommand(String command) {
        String data = robotUdpService.sendSimple(command);
        return ResponseResult.successData(data);
    }

    @ApiOperation("测试字典")
    @GetMapping("/test")
    public ResponseResult test(String command) {
        List<Map<String, Object>> pictureDefectAnalysisTypeList = sysDictionaryItemsService.getDeviceByType(
                "PictureDefectAnalysisType");
        Set<String> customList = pictureDefectAnalysisTypeList.stream().filter(c -> ObjectUtil.isNotEmpty(c.get(
                "custom1"))).map(c -> c.get("custom1").toString()).collect(Collectors.toSet());
        String value = "";
        for (String custom : customList) {
            if (JSONUtil.isTypeJSONArray(custom)) {
                cn.hutool.json.JSONArray jsonArray = JSONUtil.parseArray(custom);
                for (int i = 0; i < jsonArray.size(); i++) {
                    cn.hutool.json.JSONObject jsonObject = jsonArray.getJSONObject(i);
                    // 检查当前对象的key字段是否与目标key匹配
                    if (jsonObject.getStr("key").equals("bj_bpps")) {
                        // 如果匹配，取出对应的value字段的值
                        value = jsonObject.getStr("value");
                        break; // 找到后跳出循环
                    }
                }
            }

        }
        return ResponseResult.successData(value);
    }

    @ApiOperation("发送机器人坐标")
    @GetMapping("/sendMessage")
    public void sendMessage(String coordinate_pixel, String coordinate_geography) throws InterruptedException {
        //        patroldevice_name string 巡视设备名称
        //patroldevice_code string 巡视设备编码
        //time string 时间
        //coordinate_pixel string 坐标 格式：”x,y,z,a”，x、y、z为地图文
        //件的坐标，a为巡视设备航向角
        //coordinate_geography s
        int z = -6;
        int x = 0;
        for (int i = -80; i <= 69; i++) {

            Thread.sleep(1000);
            if (i <= -40) {
                x = i;
            } else {
                z = z - 3;
            }
            JSONArray jsonArray = new JSONArray();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("patroldevice_name", "机器狗");
            jsonObject.put("patroldevice_code", "0001");
            jsonObject.put("time", DateUtil.now());
            jsonObject.put("coordinate_pixel", x + "," + z);
            jsonObject.put("coordinate_geography", x + "," + z);
            jsonArray.add(jsonObject);
            WebSocketServer.sendInfo("robot_status_data", jsonArray.toString());
        }
    }

    @ApiOperation("退出机器人")
    @GetMapping("/exitRobot")
    public ResponseResult exitRobot(String command) {
        String data = robotUdpService.exitRobotSession(command);
        return ResponseResult.successData(data);
    }

    @ApiOperation("登录机器人")
    @PostMapping("/userLogin")
    public ResponseResult userLogin(String Name, String Pass) {
        String api = "cgi-bin/user?Operation=Login&Name=" + Name + "&Pass=" + Pass;
        JSONObject jsonObject = httpRESTfulUtils.sendHttpPostStr("192.168.1.67", "80", api, null, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("获取设备当前色标")
    @GetMapping("/getDMColor")
    public ResponseResult getDMColor() {
        String api = "cgi-bin/system?Module=DMColor";
        JSONObject jsonObject = httpRESTfulUtils.sendHttpGetStr("192.168.1.67", "80", api, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("设置设备当前色标")
    @PostMapping("/setDMColor")
    public ResponseResult setDMColor(String RuleId, String Status) {
        String api = "cgi-bin/system?Module=DMColor&RuleId=" + RuleId + "&Status=" + Status;
        JSONObject jsonObject = httpRESTfulUtils.sendHttpPostStr("192.168.1.67", "80", api, null, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("获取设备分辨率")
    @GetMapping("/getDeviceResolution")
    public ResponseResult getDeviceResolution() {
        String api = "cgi-bin/system?Module=Query&Type=DM6xResolution";
        JSONObject jsonObject = httpRESTfulUtils.sendHttpGetStr("192.168.1.67", "80", api, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("设置点测温目标")
    @PostMapping("/setPointTemperature")
    public ResponseResult setPointTemperature(String Index, String Enable, String StartX, String StartY) {
        String api =
                "cgi-bin/system?Module=DMMeasure&Type=Point&Index=" + Index + "&Enable=" + Enable + "&StartX=" + StartX + "&StartY=" + StartY;
        JSONObject jsonObject = httpRESTfulUtils.sendHttpPostStr("192.168.1.67", "80", api, null, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("设置区域测温目标")
    @PostMapping("/setAreaTemperature")
    public ResponseResult setAreaTemperature(String Index, String Enable, String StartX, String StartY, String EndX,
                                             String EndY) {
        String api =
                "cgi-bin/system?Module=DMMeasure&Type=Area&Index=" + Index + "&Enable=" + Enable + "&StartX=" + StartX + "&StartY=" + StartY + "&EndX=" + EndX + "&EndY=" + EndY;
        JSONObject jsonObject = httpRESTfulUtils.sendHttpPostStr("192.168.1.67", "80", api, null, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("测温数据获取")
    @GetMapping("/getTemperatureData")
    public ResponseResult getTemperatureData() {
        String api = "cgi-bin/system?Module=DMTtl";
        JSONObject jsonObject = httpRESTfulUtils.sendHttpGetStr("192.168.1.67", "80", api, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("实时测温数据持续回传")
    @GetMapping("/getRealTimeTemperature")
    public ResponseResult getRealTimeTemperature() {
        String api = "cgi-bin/alarm?Mode=UDP&Port=7200";
        JSONObject jsonObject = httpRESTfulUtils.sendHttpGetStr("192.168.1.67", "80", api, null);
        return ResponseResult.successData(jsonObject);
    }

    @ApiOperation("同步大华摄像机规则信息")
    @GetMapping("/synchronizationRuleList")
    public ResponseResult synchronizationRuleList(String ipaddr) {
        LambdaQueryWrapper<SubstationPatroldevice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SubstationPatroldevice::getType, "10").in(SubstationPatroldevice::getVideoMode, "2", "3");
        if (StrUtil.isNotBlank(ipaddr)) {
            queryWrapper.eq(SubstationPatroldevice::getIpaddr, ipaddr);
        }
        List<SubstationPatroldevice> list = substationPatroldeviceService.list(queryWrapper);
        if (list.size() == 1) {
            SubstationPatroldevice substationPatroldevice = list.get(0);
            String api = "getThermometryRuleAll";
            if (StrUtil.isNotBlank(httpServerConfig.getDahuaApp())) {
                api = httpServerConfig.getDahuaApp() + "/getThermometryRuleAll";
            }
            Map<String, Object> param = new HashMap<>();
            param.put("ip", substationPatroldevice.getIpaddr());
            param.put("port", 37777);
            param.put("username", "admin");
            param.put("password", "a1234567");
            param.put("channel", 1);
            JSONObject jsonObject = httpRESTfulUtils.sendHttpPost("json", httpServerConfig.getSdkIp(),
                    httpServerConfig.getDahuaPort(), "", api
                    , param, null);
            String code = jsonObject.getString("code");
            if (!"0".equals(code)) {
                log.error("失败");
                return ResponseResult.error();
            }
            String internationalId = substationPatroldevice.getInternationalId();
            List<Map<String, Object>> deviceByJson = substationDeviceService.getDeviceByJson(internationalId);
            log.info("成功");
            JSONArray data = jsonObject.getJSONArray("data");
            Map<String, List<Object>> ruleMap =
                    data.stream().collect(Collectors.groupingBy(d -> JSONUtil.parseObj(d).getStr("nPresetId")));
            for (Map<String, Object> map : deviceByJson) {
                if (ObjectUtil.isEmpty(map.get("patroldevicePos"))) {
                    continue;
                }
                List<Object> list1 = ruleMap.get(map.get("patroldevicePos").toString());
                if (list1 != null && list1.size() > 0) {
                    cn.hutool.json.JSONObject jsonObject1 = JSONUtil.parseObj(list1.get(0));
                    int nRuleId = jsonObject1.getInt("nRuleId");
                    String szName = jsonObject1.getStr("szName");
                    int nMeterType = jsonObject1.getInt("nMeterType");
                    String type = "rectangle";
                    if (1 == nMeterType) {
                        type = "point";
                    }
                    if (2 == nMeterType) {
                        type = "line";
                    }
                    cn.hutool.json.JSONArray coors = jsonObject1.getJSONArray("coors");
                    cn.hutool.json.JSONObject outsideAngle = new cn.hutool.json.JSONObject();
                    outsideAngle.putOnce("type", type);
                    outsideAngle.putOnce("ruleId", nRuleId);
                    outsideAngle.putOnce("ruleName", szName);
                    outsideAngle.putOnce("pos", coors);
                    String deviceId = map.get("deviceId").toString();
                    LambdaUpdateWrapper<SubstationDevice> updateWrapper = new LambdaUpdateWrapper<>();
                    updateWrapper.eq(SubstationDevice::getDeviceId, deviceId).set(SubstationDevice::getOutsideAngle,
                            outsideAngle.toString());
                    substationDeviceService.update(updateWrapper);
                }
            }

        }
        return ResponseResult.success();
    }

}
