package com.multictrl.modules.business.handler;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.common.utils.Utils;
import com.multictrl.modules.business.entity.CacheEntity;
import com.multictrl.modules.business.service.CacheService;
import com.multictrl.modules.business.service.DJIBaseService;
import com.multictrl.modules.business.service.MqttPushService;
import com.multictrl.modules.business.service.SrsService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * state状态数据处理
 * 设备推送状态数据，设备在状态变化时上报
 *
 * @author Sdy
 * @since 1.0.0 2026/4/25
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class StateHandler implements MessageHandler {
    private final MqttPushService mqttPushService;
    private final DJIBaseService djiBaseService;
    private final SrsService srsService;
    private final CacheService cacheService;

    @Override
    public void handleMessage(String topic, String payload, String gateway) {
        log.debug("state --> topic: {}, payload: {}", topic, payload);
        JSONObject message = JsonUtils.parseObject(payload, JSONObject.class);
        if (message != null) {
            String dockSn = message.getStr(BusinessConstant.GATEWAY);
            JSONObject data = message.getJSONObject(BusinessConstant.DATA);
            Integer needReply = message.getInt(BusinessConstant.NEED_REPLY);
            if (needReply != null && needReply == 1) {
                log.debug("state --> 需要回复");
                data.clear();
                data.set("result", 0);
                message.remove(BusinessConstant.NEED_REPLY);
                mqttPushService.pushMessageByClient1(topic + BusinessConstant._REPLY, message.toString());
                log.debug("state --> 回复成功，topic: {}, payload: {}", topic + BusinessConstant._REPLY, message);
            }
            //重新赋值
            message = JsonUtils.parseObject(payload, JSONObject.class);
            if (message == null || message.isEmpty()) {
                return;
            }
            data = message.getJSONObject(BusinessConstant.DATA);
            if (data == null || data.isEmpty()) {
                return;
            }
            if (gateway.equals(dockSn)) {
//                log.debug("dock state --> topic: {}, payload: {}", topic, payload);
                if (data.containsKey("live_capacity")) {//网关设备直播能力
                    JSONObject liveCapacity = data.getJSONObject("live_capacity");
                    log.debug("state --> 网关设备直播能力: {}", liveCapacity.toString());
                    JSONArray deviceList = liveCapacity.getJSONArray("device_list");
                    if (deviceList.isEmpty()) {
                        return;
                    }
                    for (Object object : deviceList) {
                        JSONObject device = (JSONObject) object;
                        String sn = device.getStr("sn");
                        JSONArray cameraList = device.getJSONArray("camera_list");
                        if (gateway.equals(sn)) {
                            if (!cameraList.isEmpty()) {
                                JSONObject camera = (JSONObject) cameraList.get(0);
                                String cameraIndex = camera.getStr("camera_index");
                                JSONArray videoList = camera.getJSONArray("video_list");
                                if (!videoList.isEmpty()) {
                                    JSONObject video = (JSONObject) videoList.get(0);
                                    String videoIndex = video.getStr("video_index");
                                    String videoId = sn + "/" + cameraIndex + "/" + videoIndex;
                                    String key = BusinessConstant.DOCK_VIDEO_ID + dockSn;
                                    CacheUtils.set(key, videoId, 365 * 24 * 60 * 1000L);
                                    cacheService.saveOrUpdateCache(key, videoId);
                                    log.debug("state --> 机场video_id已设置: {}", videoId);
                                    //开启机场视频
                                    int tryCount = 30;
                                    while (tryCount-- > 0) {
                                        JSONObject dataJson = new JSONObject();
                                        dataJson.set("url_type", 1);
                                        dataJson.set("url", srsService.getDockPushLiveUrl(dockSn));
                                        dataJson.set("video_id", videoId);
                                        dataJson.set("video_quality", 1);
                                        try {
                                            String result = djiBaseService.executeAndReturnResult(dockSn, "live_start_push", dataJson);
                                            log.debug("state --> 开启机场视频结果: {}", result);
                                            break;
                                        } catch (Exception e) {
                                            String eMessage = e.getMessage();
                                            JSONObject jsonObject = JsonUtils.parseObject(eMessage, JSONObject.class);
                                            if (jsonObject != null && jsonObject.getInt("code") == 513003) {
                                                log.error("state --> 机场视频已开启，无需重复开启: {}", eMessage);
                                                break;
                                            }
                                            log.error("state --> 开启机场视频失败: {}", eMessage);
                                        }
                                        Utils.sleep(1000);
                                    }
                                }
                            }
                        } else {
                            if (!cameraList.isEmpty()) {
                                //只取最后一个，机场3有两个 0是fpv 1是云台，机场2（没有fpv）只有一个 0是云台
                                JSONObject camera = (JSONObject) cameraList.get(cameraList.size() - 1);
                                String cameraIndex = camera.getStr("camera_index");
                                CacheUtils.set(BusinessConstant.UAV_CAMERA_INDEX + dockSn, cameraIndex);
                                JSONArray videoList = camera.getJSONArray("video_list");
                                if (!videoList.isEmpty()) {
                                    JSONObject video = (JSONObject) videoList.get(0);
                                    String videoIndex = video.getStr("video_index");
                                    String videoId = sn + "/" + cameraIndex + "/" + videoIndex;
                                    String key = BusinessConstant.UAV_VIDEO_ID + dockSn;
                                    CacheUtils.set(key, videoId, 365 * 24 * 60 * 1000L);
                                    cacheService.saveOrUpdateCache(key, videoId);
                                    log.debug("state --> 飞机video_id已设置: {}", videoId);
                                    //开启飞机视频
                                    int tryCount = 30;
                                    while (tryCount-- > 0) {
                                        JSONObject dataJson = new JSONObject();
                                        dataJson.set("url_type", 1);
                                        dataJson.set("url", srsService.getUavPushLiveUrl(dockSn));
                                        dataJson.set("video_id", videoId);
                                        dataJson.set("video_quality", 4);
                                        try {
                                            String result = djiBaseService.executeAndReturnResult(dockSn, "live_start_push", dataJson);
                                            log.debug("state --> 开启飞机视频结果: {}", result);
                                            break;
                                        } catch (Exception e) {
                                            String eMessage = e.getMessage();
                                            if (eMessage.contains("code")) {
                                                JSONObject jsonObject = JsonUtils.parseObject(eMessage, JSONObject.class);
                                                if (jsonObject != null && jsonObject.getInt("code") == 513003) {
                                                    log.error("state --> 飞机视频已开启，无需重复开启: {}", eMessage);
                                                    break;
                                                }
                                            }
                                            log.error("state --> 开启飞机视频失败: {}", eMessage);
                                        }
                                        Utils.sleep(1000);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                log.debug("uav state --> topic: {}, payload: {}", topic, payload);
                JSONArray psdkWidgetValues = data.getJSONArray("psdk_widget_values");
                if (psdkWidgetValues != null && !psdkWidgetValues.isEmpty()) {
                    for (Object psdkWidgetValue : psdkWidgetValues) {
                        JSONObject psdkJson = (JSONObject) psdkWidgetValue;
                        String name = psdkJson.getStr("psdk_name");
                        if ("Speaker".equals(name)) {//喊话器
                            Integer speakerIndex = psdkJson.getInt("psdk_index");
                            if (speakerIndex != null) {
                                CacheUtils.set(BusinessConstant.UAV_SPEAKER_INDEX + dockSn, speakerIndex);
                            }
                        } else if ("".equals(name)) {//探照灯
                            Integer lightIndex = psdkJson.getInt("psdk_index");
                            if (lightIndex != null) {
                                CacheUtils.set(BusinessConstant.UAV_LIGHT_INDEX + dockSn, lightIndex);
                            }
                        }
                    }
                }
            }
        } else {
            log.debug("state --> payload解析失败，解析后为null");
        }
    }
}
