/*
 * 文 件 名:  MessageHandler
 * 版    权:  浩鲸云计算科技股份有限公司
 * 描    述:  <描述>
 * 修 改 人:  lvwenbin
 * 修改时间:  2024/4/30
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.ruoyi.ems.handle;

import com.ruoyi.ems.core.MqttMessageHandler;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;

/**
 * 消息处理handle
 * <功能详细描述>
 *
 * @author lvwenbin
 * @version [版本号, 2024/4/30]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Service
public class RootMsgHandler implements MqttMessageHandler {
    private static final Logger log = LoggerFactory.getLogger(RootMsgHandler.class);

    @Autowired
    private GeekOpenCbHandler geekOpenCbHandler;

    @Autowired
    private Keka86BsHandler keka86BsHandler;

    @Override
    public void handle(String topic, byte[] message) {
        try {
            if (StringUtils.startsWith(topic, "/server/dlq/")) {
                String payload = convertToString(message);
                log.info("[Receive] Topic:{}, message:{}", topic, payload);

                String deviceCode = StringUtils.substringAfter(topic, "/server/dlq/");
                geekOpenCbHandler.msgHandle(deviceCode, payload);
            }
            else if (StringUtils.startsWith(topic, "/sc/dtu/rep/")) {
                String payload = convertToHexString(message);
                log.info("[Receive] Topic:{}, message:{}", topic, payload);
                String deviceCode = StringUtils.substringAfter(topic, "/sc/dtu/rep/");
                keka86BsHandler.msgHandle(deviceCode, payload);
            }
        }
        catch (Exception e) {
            log.error("[Handle]Topic:{}, message:{}", topic, message, e);
        }
    }

    /**
     * 将payload转换为字符串 (用于文本类消息)
     */
    private String convertToString(byte[] message) {
        return new String(message, StandardCharsets.UTF_8);
    }

    /**
     * 将payload转换为十六进制字符串 (用于Modbus二进制消息)
     */
    private String convertToHexString(byte[] message) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < message.length; i++) {
            if (i > 0)
                sb.append(" ");
            sb.append(String.format("%02X", message[i] & 0xFF));
        }
        return sb.toString();
    }
}