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.common.CommonResponse;
import com.ruoyi.dj.mqtt.utils.ParseMethodUtil;
import com.ruoyi.dj.websocket.service.MessagingService;
import com.ruoyi.system.domain.FlightTasks;
import com.ruoyi.system.domain.MinioFile;
import com.ruoyi.system.domain.Missions;
import com.ruoyi.system.domain.VideoInfo;
import com.ruoyi.system.mapper.FlightTasksMapper;
import com.ruoyi.system.service.IFlightTasksService;
import com.ruoyi.system.service.IMinioFileService;
import com.ruoyi.system.service.IMissionsService;
import com.ruoyi.system.service.IVideoInfoService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class EventsHandler {
    @Resource
    private MessagingService messagingService;
    @Resource
    private IFlightTasksService flightTasksService;
    @Resource
    private IVideoInfoService videoInfoService;
    @Resource
    private IMissionsService missionsService;
    private ObjectMapper objectMapper = new ObjectMapper();

    public void handle(String matchedPart, String message) {
        log.info("eventHandler 中的 message:{}", message);
        CommonResponse commonResponse = ParseMethodUtil.parseMethod(message);
        if (commonResponse != null) {
            if (commonResponse.getMethod().equals("putter_open")) {
                messagingService.sendMessage("putter_open", matchedPart, message);
            }
            if (commonResponse.getMethod().equals("flighttask_ready")) {
                log.info("下发任务后的任务就绪通知:{}", message);
            }
            // 打开充电进度
            if (commonResponse.getMethod().equals("charge_open")) {
                messagingService.sendMessage("charge_open", matchedPart, message);
            }
            // DRC 链路状态通知
            if (commonResponse.getMethod().equals("drc_status_notify")) {
                log.info("eventHandler 中的 drc_status_notify,{}", message);
                messagingService.sendMessage("drc_status_notify", matchedPart, message);
            }
            // 关闭充电进度
            if (commonResponse.getMethod().equals("charge_close")) {
                messagingService.sendMessage("charge_close", matchedPart, message);
            }
            // 拍照进度
            if (commonResponse.getMethod().equals("camera_photo_take_progress")) {
                log.info("eventHandler 中的 camera_photo_take_progress,{}", message);
                messagingService.sendMessage("camera_photo_take_progress", matchedPart, message);
            }
            // 航线任务的执行状态
            if (commonResponse.getMethod().equals("flighttask_progress")) {
                log.info("eventHandler 中的 flighttask_progress,{}", message);
                messagingService.sendMessage("flighttask_progress", matchedPart, message);
                JsonNode rootNode = null;
                try {
                    rootNode = objectMapper.readTree(message);
                    // 获取flightId
                    JsonNode flightIdNode = rootNode.path("data").path("output").path("ext").path("flight_id");
                    // 获取状态
                    JsonNode statusNode = rootNode.path("data").path("output").path("status");
                    String flightId = flightIdNode.asText();
                    String status = statusNode.asText();
                    // 创建状态与汉字的映射表
                    Map<String, String> statusMap = new HashMap<>();
                    statusMap.put("canceled", "取消或终止");
                    statusMap.put("failed", "失败");
                    statusMap.put("in_progress", "执行中");
                    statusMap.put("ok", "执行成功");
                    statusMap.put("partially_done", "部分完成");
                    statusMap.put("paused", "暂停");
                    statusMap.put("rejected", "拒绝");
                    statusMap.put("sent", "已下发");
                    statusMap.put("timeout", "超时");
                    // 获取对应的中文状态
                    String chineseStatus = statusMap.getOrDefault(status, "未知状态");
                    // 根据flightId更新任务状态
                    Date date = new Date();
                    Missions missions = new Missions();
                    missions.setFlightId(Long.valueOf(flightId));
                    missions.setState(chineseStatus);  // 设置汉字状态
                    missions.setLastTime(date);
                    missionsService.updateMissionsByFlightId(missions);
                    flightTasksService.updateFlightTasksStatus(flightId, chineseStatus, date);
                    log.info("任务状态更新为: flightId={}, state={}, lastTime={}", flightId, chineseStatus, date);
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }

            if (commonResponse.getMethod().equals("flighttask_ready")) {
                log.info("eventHandler 中的 flighttask_ready,{}", message);
            }
        }

        try {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(message);
            JsonNode methodNode = rootNode.get("method");

            if (methodNode != null) {
                String method = methodNode.asText();
                messagingService.sendMessage(method, matchedPart, message);
            }

            JsonNode dataNode = rootNode.get("data");
            if (dataNode != null && dataNode.has("reason")) {
                log.info("Reason found in data: " + message);
            }
        } catch (Exception e) {
            log.error("Error processing JSON message", e);
        }
    }
}
