package org.ts.ddcs.DataItemTemplate;


import org.ts.ddcs.Entity.RtuStatusEntity;
import org.ts.ddcs.Tool.BytesHelp;

import java.math.BigDecimal;

/**
 * funcode 0xff56
 * 异常值
 */
@SuppressWarnings("all")
public class DataItemTemplateFF56 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, 2);
        count += 2;
        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);
            String hexStr = BytesHelp.byte2HexStr(buff);
            StringBuffer dataStr = new StringBuffer(hexStr);
            if (decimalLen != 0) {
                dataStr.insert(dataStr.length() - decimalLen, ".");
            }
            count += dataTotalLen;
            byte[] varbuff = BytesHelp.hexStr2Bytes(dataStr.toString());
            this.varcharValue = String.format("%d", varbuff[0]);
            remain = BytesHelp.subBytes(remain, count, remain.length - count);
            this.macth = true;
        }
        return remain;
    }

    @Override
    public BigDecimal GetDecimal() {
        return new BigDecimal(Double.parseDouble(this.varcharValue));
    }

    @Override
    public void SetEntity(Object entity) {
        RtuStatusEntity statusEntity = (RtuStatusEntity) entity;
        statusEntity.setError(Integer.parseInt(this.varcharValue));
    }

    @Override
    public String toString() {
        if (varcharValue.equals("0")) {
            return "设备正常";
        } else {
            return "设备异常 代码：" + this.varcharValue;
        }
    }
}
