package org.ts.ddcs.DataItemTemplate;


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

import java.util.*;


/**
 * 0xFF10
 * 扩展闸门开度 ,长度包括2个字节闸门编号和高度，闸门编号N（3），高度数据组 N(5,2)
 */
@SuppressWarnings("all")
public class DataItemTemplateEXT_FF10 extends DataItemTemplate {

    @Override
    public byte[] Stream(byte[] data) {
        byte[] remain = data;
        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;
            if (dataTotalLen == 5 && remain.length >= count + 5) {
                //闸门编号
                byte[] buff = BytesHelp.subBytes(remain, count, 2);
                String hexStr = BytesHelp.byte2HexStr(buff);
                StringBuffer dataStr = new StringBuffer(hexStr);
                String gateCode = StringUtil.getPrettyNumber(dataStr.toString());
                count += 2;
                //闸门开度
                buff = BytesHelp.subBytes(remain, count, 3);
                hexStr = BytesHelp.byte2HexStr(buff);
                if (hexStr.equals("FFFFFF")) {
                    this.datas.put("" + gateCode, hexStr);
                } else {
                    dataStr = new StringBuffer(hexStr);
                    dataStr.insert(dataStr.length() - 2, ".");
                    String value = StringUtil.getPrettyNumber(dataStr.toString());
                    this.datas.put("" + gateCode, value);
                }
                count += 3;
            }
            remain = BytesHelp.subBytes(remain, count, remain.length - count);
            this.macth = true;
        }
        return remain;
    }

    @Override
    public String toString() {
        if (null != datas && datas.size() > 0) {
            String text = "";
            List<Integer> textList = new LinkedList<>();
            Set<String> keys = this.datas.keySet();
            for (String key : keys) {
                textList.add(Integer.parseInt(key));
            }
            textList.sort(new Comparator<Integer>() {
                @Override
                public int compare(Integer o1, Integer o2) {
                    if (o1 > o2) {
                        return 1;
                    } else if (o1 < o2) {
                        return -1;
                    }
                    return 0;
                }
            });

            for (Integer i : textList) {
                text += "" + i + "号闸门：" + this.datas.get("" + i) + "（米） ";
            }
            return text;
        }
        if (null != bigDecimalValue) {
            return bigDecimalValue.toPlainString();
        }
        if (null != varcharValue) {
            return varcharValue;
        }
        return "";
    }
}
