package com.zksy.infrared.utils;

import com.zksy.common.utils.DecimalConversion;
import com.zksy.infrared.domain.InfraredReadingMeter;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Slf4j
public class DataParser {
    private static Logger logger = LoggerFactory.getLogger(DataParser.class);

    public static InfraredReadingMeter parseMessage(String msgString) {
        InfraredReadingMeter result = new InfraredReadingMeter();
        try {
            List<String> dataParts = new ArrayList<>();
            for (int i = 0; i < msgString.length(); i += 2) {
                int end = Math.min(i + 2, msgString.length());
                dataParts.add(msgString.substring(i, end));
            }

            // 检查数据部分是否足够
            if (dataParts.size() < 1 + 1 + 1 + 4) { // address(1) + function(1) + 跳过(1) + energy(4)
                logger.error("数据长度不足，无法解析: {}", msgString);
                return result;
            }

            String res1 = getStringList(dataParts, 1);
            result.setAddressCode(String.valueOf(Integer.parseInt(res1, 16)));

            String res2 = getStringList(dataParts, 1);
            result.setFunctionCode(String.valueOf(Integer.parseInt(res2, 16)));

            // 跳过一个部分
            getStringList(dataParts, 1);

            String res3 = getStringList(dataParts, 4);
            // 检查是否有null值
            if (res3.contains("null")) {
                logger.error("解析得到的电能数据包含无效值: {}", res3);
                return result;
            }

            BigInteger energyValue = new BigInteger(res3, 16);
            result.setElectricEnergy(energyValue.divide(BigInteger.valueOf(100)).doubleValue());
            result.setCreateTime(new Date());

        } catch (NumberFormatException e) {
            logger.error("解析数字时出错，输入字符串无效", e);
        } catch (Exception e) {
            logger.error("解析消息时出错", e);
        }
        return result;
    }

    public static String parseMeterNumber(String msgString) {
        try {
            // 检查字符串长度是否足够
            if (msgString.length() < 10) { // 6 + 4，确保有足够的长度
                logger.error("消息字符串太短，无法解析仪表编号: {}", msgString);
                return null;
            }

            String hexString = msgString.substring(6, msgString.length() - 4);
            // 转换为BigInteger并获取无符号十进制表示
            BigInteger bigInteger = new BigInteger(hexString, 16);
            return bigInteger.toString();
        } catch (Exception e) {
            logger.error("解析仪表编号时出错", e);
            return null;
        }
    }

    public static String shiftFromList(List<String> list) {
        if (list == null || list.isEmpty()) {
            logger.warn("尝试从空列表中获取元素");
            return null;
        }
        return list.remove(0);
    }

    private static String getStringList(List<String> dataParts, Integer q) {
        if (dataParts == null || dataParts.size() < q) {
            logger.warn("数据部分不足，需要{}个，实际只有{}个", q, dataParts == null ? 0 : dataParts.size());
            // 返回空字符串或处理不足的情况
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < q; i++) {
                sb.append(shiftFromList(dataParts));
            }
            return sb.toString();
        }

        StringBuilder res = new StringBuilder();
        for (int i = 0; i < q; i++) {
            String part = shiftFromList(dataParts);
            if (part == null) {
                logger.warn("获取第{}个元素时为null", i);
            }
            res.append(part);
        }
        return res.toString();
    }
}
