/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/2/23
 */
package org.ts.ddcs.DataItemTemplate.tool;

import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.StringUtil;

import java.math.BigDecimal;

/***
 * Date:2022/2/23
 * Title: 数据项模板
 * Description：解析数据帮助，公共方法
 * @author dylan
 *
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
public class DataItemTemplateHelp {
    private static final String SYMBOL_FLAG="FF";

    /**
     * 解析数值字节长度及小数位长度
     *
     * @param buff
     * @return
     */
    public static ValueLen getValueLen(byte buff) {
        int dataTotalLen = buff >> 3;
        int decimalLen = buff & 7;
        ValueLen valueLen = new ValueLen();
        valueLen.setByteLen(dataTotalLen);
        valueLen.setDecimalLen(decimalLen);
        return valueLen;
    }

    public static BigDecimal getDecimalValue(byte[] buff, int pos){
        return null;
    }

    /**
     * 解析数字类型数值
     *
     * @param buff
     * @param index
     * @param byteLen
     * @param decimalLen
     * @return
     */
    public static BigDecimal toDecimal(byte[] buff, int index, int byteLen, int decimalLen) {
        String decimalValue = DataItemTemplateHelp.toDecimalString(buff, index, byteLen, decimalLen);
        if (null != decimalValue) {
            return new BigDecimal(decimalValue);
        }
        return null;
    }

    /**
     * 解析数字类型数值并转成字符串
     * @param buff
     * @param index
     * @param byteLen
     * @param decimalLen
     * @return
     */
    public static String toDecimalString(byte[] buff, int index, int byteLen, int decimalLen) {
        if (buff.length == 0 || (buff.length - index) < byteLen) {
            return null;
        }
        byte[] valueBuff = BytesHelp.subBytes(buff, index, byteLen);
        if (null == valueBuff || valueBuff.length <= 0) {
            return null;
        }
        String hexStr = BytesHelp.byte2HexStr(valueBuff);
        StringBuffer tmpString = new StringBuffer(hexStr);
        String symbol = "";
        if (SYMBOL_FLAG.equals(hexStr.substring(0,2))) {
            tmpString = new StringBuffer(hexStr.substring(2));
            symbol = "-";
        }
        if (decimalLen != 0) {
            tmpString.insert(tmpString.length() - decimalLen, ".");
        }
        String decimalValue = StringUtil.getPrettyNumber(tmpString.toString());
        decimalValue = symbol + decimalValue;
        return decimalValue;
    }
}
