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));
            }
            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);
            result.setElectricEnergy(Integer.parseInt(DecimalConversion.hexToDecimalExample(res3), 16) / 100.00);
            result.setCreateTime(new Date());

        } catch (Exception e) {
            logger.error("解析消息时出错", e);
        }
        return result;
    }

    public static String parseMeterNumber(String msgString) {
        String hexString = msgString.substring(6, msgString.length() - 4);
        // 转换为BigInteger并获取无符号十进制表示
       BigInteger bigInteger = new BigInteger(hexString, 16);
        return bigInteger.toString();
    }
    public static String shiftFromList(List<String> list) {
        if (list == null || list.isEmpty()) {
            return null; // 或者抛出异常，根据需求决定
        }
        return list.remove(0);
    }

    private static String getStringList(List<String> dataParts,Integer q) {
        StringBuilder res1 = new StringBuilder();
        for (int i = 0; i < q; i++) {
            res1.append(shiftFromList(dataParts));
        }
        return res1.toString();
    }
}
