package com.fuyuanshen.global.mqtt.receiver;

import cn.hutool.core.lang.Dict;
import cn.hutool.json.JSONObject;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.equipment.domain.Device;
import com.fuyuanshen.equipment.domain.DeviceType;
import com.fuyuanshen.equipment.domain.form.DeviceForm;
import com.fuyuanshen.equipment.domain.query.DeviceTypeQueryCriteria;
import com.fuyuanshen.equipment.mapper.DeviceMapper;
import com.fuyuanshen.equipment.mapper.DeviceTypeMapper;
import com.fuyuanshen.equipment.service.DeviceService;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleContext;
import com.fuyuanshen.global.mqtt.base.NewMqttRuleEngine;
import com.fuyuanshen.global.mqtt.config.MqttGateway;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
import com.fuyuanshen.global.queue.MqttMessageQueueConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHandler;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.MessagingException;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Objects;

import static com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants.DEVICE_KEY_PREFIX;

/**
 * 注册设备消息接收处理
 */
@Service
@Slf4j
public class RegisEquipReceiverMessageHandler implements MessageHandler {

    @Autowired
    private NewMqttRuleEngine newRuleEngine;

    @Autowired
    private MqttGateway mqttGateway;


    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private DeviceService deviceService;

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;


    @Override
    public void handleMessage(Message<?> message) throws MessagingException {

        Object payload = message.getPayload();
        MessageHeaders headers = message.getHeaders();
        String receivedTopic = Objects.requireNonNull(headers.get("mqtt_receivedTopic")).toString();

        // 只处理 regis/equip/# 主题的消息
        if (!receivedTopic.startsWith("regis/equip/")) {
            return;
        }

        // 从主题中提取设备ID
        String[] topicParts = receivedTopic.split("/");
        if (topicParts.length < 3) {
            log.warn("Invalid topic format: {}", receivedTopic);
            return;
        }
        String deviceTypeName = topicParts[2]; // HBY100-J

        String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
        String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();

        log.info("MQTT3 payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
                payload, receivedTopic, receivedQos, timestamp);

        // 解析JSON payload获取imei和mac
        Dict payloadDict = JsonUtils.parseMap(payload.toString());
        if (payloadDict == null) {
            log.warn("Failed to parse payload JSON");
            return;
        }

        String imei = payloadDict.getStr("imei");
        String mac = payloadDict.getStr("mac");

        log.info("Extracted IMEI: {}, MAC: {}", imei, mac);

        // 验证必要字段
        if (StringUtils.isEmpty(imei) || StringUtils.isEmpty(mac)) {
            log.warn("Missing required fields - IMEI: {}, MAC: {}", imei, mac);
            return;
        }

        DeviceTypeQueryCriteria criteria = new DeviceTypeQueryCriteria();
        criteria.setTypeName(deviceTypeName);
        DeviceType deviceType = deviceTypeMapper.queryByName(criteria);
        if (deviceType == null) {
            log.warn("Device type not found for name: {}", deviceTypeName);
            return;
        }

        Device device = deviceMapper.selectDeviceByImei(imei);
        if (device != null) {
            log.warn("Device already exists for IMEI: {}", imei);
            String redisKey = GlobalConstants.GLOBAL_REDIS_KEY + DEVICE_KEY_PREFIX +
                    imei + ":regis";
            Object value = RedisUtils.getCacheObject(redisKey);
            if (value != null) {
                log.warn("regis/imei发送次数频率过快: {}", imei);
                return;
            }
//            sendSuccessMessage(imei);
            RedisUtils.setCacheObject(redisKey, payload.toString(), Duration.ofSeconds(10));
            return;
        }

        // 提取MAC地址后6位
        String macSuffix = mac.replaceAll(":", "").substring(6); // 43:73:43:33:53:33 -> 335333
        // 构建设备名称和蓝牙名称：设备类型+MAC后6位
        String deviceName = deviceTypeName + "-" + macSuffix; // HBY100-335333

        DeviceForm deviceForm = new DeviceForm();
        deviceForm.setDeviceImei(imei);
        deviceForm.setDeviceMac(mac);
        deviceForm.setDeviceName(deviceName);
        deviceForm.setBluetoothName(deviceName);
        deviceForm.setDeviceType(deviceType.getId());

        try {
            deviceService.addDevice(deviceForm);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        sendSuccessMessage(imei);

    }

    private void sendSuccessMessage(String imei) {
        // 解析原始JSON数据
        JSONObject originalData = new JSONObject();
        originalData.put("code", 200);
        // 发送到MQTT
        String topic = "regis/" + imei;
        mqttGateway.sendMsgToMqtt(topic, originalData.toString());
    }


}
