package org.ts.ddcs.DataItemTemplate;


import org.ts.ddcs.Entity.RiverEntity;
import org.ts.ddcs.Log.LogHelper;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.StringUtil;

import java.math.BigDecimal;

/**
 * 0x39
 * 瞬时河道水位、潮位
 */
@SuppressWarnings("all")
public class DataItemTemplateZ extends DataItemTemplate {
    @Override
    public byte[] Stream(byte[] data) {
        byte[] remain = data;
        if (this.macth) {
            return remain;
        }
        int count = 0;
        String flag = BytesHelp.byte2HexStr(remain, count, 1);
        count += 1;
        if (flag.equals(this.feture)) {
            byte[] len = BytesHelp.subBytes(remain, count, 1);
            count += 1;
            int dataTotalLen = len[0] >> 3;
            int decimalLen = len[0] & 7;
            byte[] buff = BytesHelp.subBytes(remain, count, dataTotalLen);
            count += dataTotalLen;
            boolean dataError = true;
            for (int i = 0; i < buff.length; i++) {
                if (buff[i] != (byte) 0xFF) {
                    dataError = false;
                    break;
                }
            }
            String hexStr = BytesHelp.byte2HexStr(buff);
            if (!dataError) {
                if (hexStr.startsWith("FF")) {
                    StringBuffer dataStr = new StringBuffer(hexStr.substring(2));
                    if (decimalLen != 0) {
                        dataStr.insert(dataStr.length() - decimalLen, ".");
                    }
                    String value = "-" + StringUtil.getPrettyNumber(dataStr.toString());
                    this.bigDecimalValue = new BigDecimal(value);
                } else {
                    StringBuffer dataStr = new StringBuffer(hexStr);
                    if (decimalLen != 0) {
                        dataStr.insert(dataStr.length() - decimalLen, ".");
                    }
                    String value = StringUtil.getPrettyNumber(dataStr.toString());
                    this.bigDecimalValue = new BigDecimal(value);
                }

            } else {
                LogHelper.info(this.desc + ":" + this.feture + ":" + "数据异常 " + hexStr);
                this.outlierData=true;
            }
            remain = BytesHelp.subBytes(remain, count, remain.length - count);
            this.macth = true;
        }
        return remain;
    }


    @Override
    public void SetEntity(Object entity) {
        RiverEntity riverEntity = (RiverEntity) entity;
        riverEntity.setZ(this.bigDecimalValue);
    }
}
