package com.multictrl.common.handler;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.multictrl.common.constant.BusinessConstant;
import com.multictrl.common.exception.ExceptionUtils;
import com.multictrl.common.utils.CacheUtils;
import com.multictrl.common.utils.JsonUtils;
import com.multictrl.common.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;

/**
 * MQTT消息处理器
 */
@Slf4j
@Component
public class Mqtt2MessageHandler implements MessageHandler {
    @Autowired
    @Qualifier("mqttExecutor2")
    private ExecutorService executor;
    private static final List<String> VALID_METHODS = Arrays.asList(
            "drone_emergency_stop",
            "drc_speaker_play_volume_set",
            "drc_speaker_play_mode_set",
            "drc_speaker_tts_set",
            "drc_speaker_play_stop",
            "drc_speaker_replay",
            "drc_speaker_tts_play_start"
    );

    @Override
    public void handleMessage(@NotNull Message<?> message) throws MessagingException {
        try {
            executor.submit(() -> {
                String topic = String.valueOf(message.getHeaders().get(MqttHeaders.RECEIVED_TOPIC));
                String payload = message.getPayload().toString();
                try {
//                    log.debug("client2接收到的消息:{} {}", topic, message.getPayload());
                    String method = Utils.getLastTwoSegments(topic, "/");
                    String afterProduct = StrUtil.subAfter(topic, "product/", false); // "8UUXP1P00A107D/drc/up"
                    String gateway = StrUtil.subBefore(afterProduct, "/", false);
                    if ("drc/up".equals(method)) {
                        JSONObject messageJson = JsonUtils.parseObject(payload, JSONObject.class);
                        if (messageJson != null) {
                            String methodJson = messageJson.getStr(BusinessConstant.METHOD);
                            if (VALID_METHODS.contains(methodJson)) {
                                log.debug("drc 回复--> topic:{} ,payload:{}", topic, payload);
                                JSONObject dataJson = messageJson.getJSONObject(BusinessConstant.DATA);
                                if (dataJson == null) {
                                    dataJson = new JSONObject();
                                    dataJson.set("result", 0);
                                }
                                CacheUtils.set(gateway + "_" + methodJson, dataJson);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("消费信息异常: {}", ExceptionUtils.getErrorStackTrace(e));
                }
            });
        } catch (Exception e) {
            log.error("handleMessage异常: {}", ExceptionUtils.getErrorStackTrace(e));
        }
    }
}
