package com.ruoyi.dj.mqtt.handler;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.dj.mqtt.client.DJICloudMQTTClient;
import com.ruoyi.dj.mqtt.common.CommonFields;
import com.ruoyi.dj.mqtt.common.CommonResponse;
import com.ruoyi.dj.mqtt.domain.StorageConfig;
import com.ruoyi.dj.mqtt.domain.UpdateTopoRequest;
import com.ruoyi.dj.mqtt.utils.JsonKeyRemover;
import com.ruoyi.dj.mqtt.utils.ParseMethodUtil;
import com.ruoyi.dj.mqtt.utils.PayloadUtil;
import com.ruoyi.system.domain.VideoInfo;
import com.ruoyi.system.service.IDroneService;
import com.ruoyi.system.service.IVideoInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
public class StatusHandler {
    @Resource
    private IVideoInfoService videoInfoService;

    private final ObjectMapper objectMapper;

    @Resource
    private DJICloudMQTTClient djiCloudMQTTClient;
    private static final String STATUS_REPLY = "sys/product/?/status_reply";

    public StatusHandler() {
        this.objectMapper = new ObjectMapper();
    }

    public void handle(String matchedPart, String message) {
        CommonResponse commonResponse = ParseMethodUtil.parseMethod(message);

        // 检查方法是否为 "update_topo"
        if (!"update_topo".equals(commonResponse.getMethod())) {
            return;
        }

        // 处理消息回复
        try {
            String topic = STATUS_REPLY.replace("?", matchedPart);
            JsonNode jsonNode = objectMapper.readTree(message);

            // 提取必要的字段
            CommonFields commonFields = extractCommonFields(jsonNode, commonResponse.getMethod());
            String payload = generatePayloadWithRemovedKeys(commonFields);

            // 异步发送消息以防止阻塞
            sendAsyncMessage(topic, payload);
        } catch (JsonProcessingException e) {
            log.error("解析或生成 JSON 失败", e);
        }

        // 处理更新拓扑请求
        try {
            UpdateTopoRequest request = objectMapper.readValue(message, UpdateTopoRequest.class);
            updateVideoInfoByGateway(matchedPart, request);
        } catch (JsonProcessingException e) {
            log.error("JSON消息转换错误", e);
        }
    }

    /**
     * 提取公共字段
     */
    private CommonFields extractCommonFields(JsonNode jsonNode, String method) {
        String bid = jsonNode.has("bid") ? jsonNode.get("bid").asText() : null;
        String tid = jsonNode.has("tid") ? jsonNode.get("tid").asText() : null;

        CommonFields commonFields = new CommonFields();
        commonFields.setBid(bid);
        commonFields.setTid(tid);
        commonFields.setMethod(method);
        commonFields.setTimestamp(System.currentTimeMillis());

        return commonFields;
    }

    /**
     * 生成去除特定键的负载数据
     */
    private String generatePayloadWithRemovedKeys(CommonFields commonFields) throws JsonProcessingException {
        Map<String, Object> map = new HashMap<>();
        map.put("result", 0);

        String payload = PayloadUtil.generatePayload(commonFields, map);
        List<String> keysToRemove = Collections.singletonList("gateway");
        return JsonKeyRemover.removeKeysFromJson(keysToRemove, payload);
    }

    /**
     * 异步发送消息
     */
    private void sendAsyncMessage(String topic, String payload) {
        CompletableFuture.runAsync(() -> {
            djiCloudMQTTClient.publishMessage(topic, payload);
        });
    }

    /**
     * 更新网关的设备信息
     */
    private void updateVideoInfoByGateway(String matchedPart, UpdateTopoRequest request) {
        List<VideoInfo> videoInfoByGateway = videoInfoService.findVideoInfoByGateway(matchedPart);
        VideoInfo videoInfoGateway = videoInfoService.selectVideoByCondition(matchedPart, "机场");

        UpdateTopoRequest.DeviceData data = request.getData();
        if (data != null && videoInfoGateway != null) {
            videoInfoGateway.setDeviceType(data.getDomain() + "-" + data.getType() + "-" + data.getSub_type());
            videoInfoService.updateVideoInfo(videoInfoGateway);
        }

        VideoInfo videoInfoDrone = videoInfoService.selectVideoByCondition(matchedPart, "飞机");
        // 检查子设备并更新设备信息
        if (data != null && data.getSub_devices() != null && !data.getSub_devices().isEmpty()) {
            UpdateTopoRequest.DeviceData.SubDevice subDevice = data.getSub_devices().get(0);
            if (subDevice != null && videoInfoDrone != null) {
                videoInfoDrone.setDeviceType(subDevice.getDomain() + "-" + subDevice.getType() + "-" + subDevice.getSub_type());
                videoInfoDrone.setFlyIndex("0");
                videoInfoService.updateVideoInfo(videoInfoDrone);
            }
        }
    }
}
