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.cmd.CmdConstant;
import com.ruoyi.dj.mqtt.common.CommonFields;
import com.ruoyi.dj.mqtt.common.CommonFieldsVo;
import com.ruoyi.dj.mqtt.common.CommonResponse;
import com.ruoyi.dj.mqtt.domain.AppConfig;
import com.ruoyi.dj.mqtt.domain.StorageConfig;
import com.ruoyi.dj.mqtt.utils.ParseMethodUtil;
import com.ruoyi.dj.mqtt.utils.PayloadUtil;
import com.ruoyi.dj.mqtt.utils.StorageConfigUtil;
import com.ruoyi.dj.websocket.service.MessagingService;
import com.ruoyi.system.domain.DroneMissions;
import com.ruoyi.system.domain.FlightPaths;
import com.ruoyi.system.domain.Missions;
import com.ruoyi.system.service.IDroneMissionsService;
import com.ruoyi.system.service.IFlightPathsService;
import com.ruoyi.system.service.IMissionsService;
import io.minio.credentials.Credentials;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Slf4j
@Component
public class RequestsHandler {

    private static final String REQUEST_REPLY_TOPIC = "thing/product/?/requests_reply";
    @Resource
    private DJICloudMQTTClient djiCloudMQTTClient;
    @Resource
    private IDroneMissionsService droneMissionsService;
    @Autowired
    private Environment environment;
    private ObjectMapper objectMapper = new ObjectMapper();
    @Resource
    private IMissionsService missionsService;
    @Resource
    private IFlightPathsService flightPathsService;

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

        // 新任务资源获取
        if (commonResponse.getMethod().equals("flighttask_resource_get")) {
            log.info("request 中的 flighttask_resource_get:{}", message);
            // 提取 message 中的 flight_id 字段
            try {
                JsonNode rootNode = objectMapper.readTree(message);
                JsonNode dataNode = rootNode.path("data");
                String flightId = dataNode.path("flight_id").asText();

                Missions missions = new Missions();
                missions.setFlightId(Long.valueOf(flightId));
                Missions missions1 = missionsService.selectMissionsList(missions).get(0);
                // 查询航线文件URL和签名
                String fileId = missions1.getFileId();
                FlightPaths flightPaths = flightPathsService.selectFlightPathsById(Long.valueOf(fileId));

                CommonFieldsVo commonFieldsVo = new CommonFieldsVo();
                commonFieldsVo.setGateway(matchedPart);
                commonFieldsVo.setMethod(commonResponse.getMethod());
                commonFieldsVo.setTid(commonResponse.getTid());
                commonFieldsVo.setBid(commonResponse.getBid());

                Map<String, Object> fileMap = new HashMap<>();
                fileMap.put("fingerprint", flightPaths.getFileMd5());
                fileMap.put("url", flightPaths.getFileUrl());

                Map<String, Object> outputMap = new HashMap<>();
                outputMap.put("file", fileMap);

                Map<String, Object> dataMap = new HashMap<>();
                dataMap.put("output", outputMap);
                dataMap.put("result", 0);

                String payload = PayloadUtil.generatePayload(commonFieldsVo, dataMap);
                log.info("Generated Payload: " + payload);
                djiCloudMQTTClient.publishMessage(REQUEST_REPLY_TOPIC.replace("?", matchedPart), payload);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }

        // 获取上传临时凭证
        if (commonResponse.getMethod().equals("storage_config_get")) {
            try {
                // 将消息字符串转换为 JsonNode
                JsonNode jsonNode = objectMapper.readTree(message);
                log.info("请求凭证的原始消息: " + message);
                // 检查 data 属性是否存在并包含 module 属性
                if (jsonNode.has("data") && jsonNode.get("data").has("module")) {
                    // 转换为 StorageConfigRequest 对象
                    StorageConfig storageConfigRequest = objectMapper.treeToValue(jsonNode, StorageConfig.class);
                    // 获取 json 字符串中的 gateway、bid、tid、timestamp、method
                    String gateway = jsonNode.has("gateway") ? jsonNode.get("gateway").asText() : null;
                    String bid = jsonNode.has("bid") ? jsonNode.get("bid").asText() : null;
                    String tid = jsonNode.has("tid") ? jsonNode.get("tid").asText() : null;
                    String topic = REQUEST_REPLY_TOPIC.replace("?", gateway);
                    CommonFields commonFields = new CommonFields();
                    commonFields.setBid(bid);
                    commonFields.setGateway(gateway);
                    commonFields.setMethod(commonResponse.getMethod());
                    commonFields.setTid(tid);
                    commonFields.setTimestamp(System.currentTimeMillis());
                    // 异步发送消息、避免minio阻塞
                    CompletableFuture.runAsync(() -> {
                        try {
                            Map<String, Object> map = StorageConfigUtil.createStorageConfig(matchedPart);
                            if (map == null) {
                                log.error("MinIO 服务异常，配置返回为空");
                                String payload = PayloadUtil.generatePayload(commonFields, map);
                                log.info("下发凭证信息: " + payload);
                                // 发送消息给无人机
                                djiCloudMQTTClient.publishMessage(topic, payload);
                            } else {
                                String payload = PayloadUtil.generatePayload(commonFields, map);
                                djiCloudMQTTClient.publishMessage(topic, payload);
                            }
                        } catch (Exception e) {
                            log.error("MinIO 配置生成异常", e);
                        }
                    });
                }
            } catch (JsonProcessingException e) {
                log.error("JSON 处理错误: ", e);
            }
        }

        // 获取配置的方法【本地内网部署需要同步时钟周期】
        if (commonResponse.getMethod().equals("config")) {
            try {
                // 将消息字符串转换为 JsonNode
                JsonNode jsonNode = objectMapper.readTree(message);
                log.info("获取配置的原始消息: " + message);
                // 检查 data 属性是否存在并包含 app_id 属性
                if (jsonNode.has("data") && jsonNode.get("data").has("app_id")) {
                    // 转换为 AppConfig 对象
                    AppConfig appConfig = objectMapper.treeToValue(jsonNode, AppConfig.class);
                    // 获取 json 字符串中的 gateway、bid、tid、timestamp、method
                    String gateway = jsonNode.has("gateway") ? jsonNode.get("gateway").asText() : null;
                    String bid = jsonNode.has("bid") ? jsonNode.get("bid").asText() : null;
                    String tid = jsonNode.has("tid") ? jsonNode.get("tid").asText() : null;
                    String topic = REQUEST_REPLY_TOPIC.replace("?", gateway);
                    CommonFields commonFields = new CommonFields();
                    commonFields.setBid(bid);
                    commonFields.setGateway(gateway);
                    commonFields.setMethod(commonResponse.getMethod());
                    commonFields.setTid(tid);
                    commonFields.setTimestamp(System.currentTimeMillis());
                    Map<String, Object> map = new HashMap<>();
                    map.put("app_id", environment.getProperty("deploy.appid"));
                    map.put("app_key", environment.getProperty("deploy.appKey"));
                    map.put("app_license", environment.getProperty("deploy.appLicense"));
                    map.put("ntp_server_host", environment.getProperty("deploy.ntpServerHost"));
                    map.put("ntp_server_port", environment.getProperty("deploy.ntpServerPort"));
                    String payload = PayloadUtil.generatePayload(commonFields, map);
                    log.info("下发配置更新的信息: " + payload);
                    // 发送消息给无人机
                    djiCloudMQTTClient.publishMessage(topic, payload);
                }
            } catch (JsonProcessingException e) {
                log.error("JSON 处理错误: ", e);
            }
        }
    }
}
