package org.ts.ddcs.DataItemTemplate;


import org.ts.ddcs.Entity.RsvrEntity;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.Tool.BytesHelp;
import org.ts.ddcs.Tool.StringUtil;

import java.math.BigDecimal;

/**
 * 0x3B
 * 库（闸、站）上水位
 */
@SuppressWarnings("all")
public class DataItemTemplateZU extends DataItemTemplate {
    @Override
    public byte[] Stream(byte[] data) {
        byte[] remain = data;
        try {

            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;
                this.valueBuff = BytesHelp.subBytes(remain, count, dataTotalLen);
                count += dataTotalLen;
                boolean dataError = true;
                for (int i = 0; i < dataTotalLen; i++) {
                    if (this.valueBuff[i] != (byte) 0xFF) {
                        dataError = false;
                        break;
                    }
                }

                if (!dataError) {
                    String hexStr = BytesHelp.byte2HexStr(this.valueBuff);
                    StringBuffer dataStr = new StringBuffer(hexStr);
                    if (decimalLen != 0) {
                        dataStr.insert(dataStr.length() - decimalLen, ".");
                    }
                    String value = StringUtil.getPrettyNumber(dataStr.toString());
                    this.bigDecimalValue = new BigDecimal(value);
                }
                if (remain.length - count > 0) {
                    remain = BytesHelp.subBytes(remain, count, remain.length - count);
                } else {
                    remain = new byte[0];
                }

                this.macth = true;
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return remain;
    }

    @Override
    public void SetEntity(Object entity) {
        RsvrEntity rsvrEntity = (RsvrEntity) entity;
        rsvrEntity.setRZ(this.bigDecimalValue);
    }

    @Override
    public boolean OutlierData() {
        if (null != this.valueBuff && this.valueBuff.length > 0) {
            boolean dataError = true;
            for (int i = 0; i < this.valueBuff.length; i++) {
                if (this.valueBuff[i] != (byte) 0xFF) {
                    dataError = false;
                    break;
                }
            }
            return dataError;
        }
        return false;
    }
}
