package com.fuyuanshen.global.mqtt.receiver;

import cn.hutool.core.lang.Dict;
import com.fuyuanshen.common.core.constant.GlobalConstants;
import com.fuyuanshen.common.core.utils.ImageToCArrayConverter;
import com.fuyuanshen.common.core.utils.StringUtils;
import com.fuyuanshen.common.json.utils.JsonUtils;
import com.fuyuanshen.common.redis.utils.RedisUtils;
import com.fuyuanshen.global.mqtt.base.MqttRuleContext;
import com.fuyuanshen.global.mqtt.base.MqttRuleEngine;
import com.fuyuanshen.global.mqtt.constants.DeviceRedisKeyConstants;
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;

@Service
@Slf4j
public class ReceiverMessageHandler implements MessageHandler {

    @Autowired
    private MqttRuleEngine ruleEngine;

    @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();
        String receivedQos = Objects.requireNonNull(headers.get("mqtt_receivedQos")).toString();
        String timestamp = Objects.requireNonNull(headers.get("timestamp")).toString();
        
        log.info("MQTT payload= {} \n receivedTopic = {} \n receivedQos = {} \n timestamp = {}",
                payload, receivedTopic, receivedQos, timestamp);
                
        Dict payloadDict = JsonUtils.parseMap(payload.toString());
        if (receivedTopic == null || payloadDict == null) {
            return;
        }
        String[] subStr = receivedTopic.split("/");
        String deviceImei = subStr[1];
        if(StringUtils.isNotBlank(deviceImei)){
            //在线状态
            String deviceOnlineStatusRedisKey = GlobalConstants.GLOBAL_REDIS_KEY+ DeviceRedisKeyConstants.DEVICE_ONLINE_STATUS_KEY_PREFIX + deviceImei;
            RedisUtils.setCacheObject(deviceOnlineStatusRedisKey, "1", Duration.ofSeconds(60*15));
        }

        String state = payloadDict.getStr("state");
        Object[] convertArr = ImageToCArrayConverter.convertByteStringToMixedObjectArray(state);
        
        if (convertArr.length > 0) {
            Byte val1 = (Byte) convertArr[0];
            MqttRuleContext context = new MqttRuleContext();
            context.setCommandType(val1);
            context.setConvertArr(convertArr);
            context.setDeviceImei(deviceImei);
            context.setPayloadDict(payloadDict);

            boolean ruleExecuted = ruleEngine.executeRule(context);
            
            if (!ruleExecuted) {
                log.warn("未找到匹配的规则来处理命令类型: {}", val1);
            }
        }
    }
}
