/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2021/12/16
 */
package org.ts.ddcs.dataStream.processor.sw;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.ts.ddcs.common.constant.SwDatagramConstant;
import org.ts.ddcs.common.dict.RunSettingFlag;
import org.ts.ddcs.enums.SwElementCodeEnum;
import org.ts.ddcs.common.metadata.DatagramMetadataEnum;
import org.ts.ddcs.enums.SwDatagramTypeCodeEnum;
import org.ts.ddcs.common.metadata.ElementDataMetadataEnum;
import org.ts.ddcs.common.util.BytesHelp;
import org.ts.ddcs.common.util.StringUtil;
import org.ts.ddcs.common.util.Sw2014DatagramTemplateHelp;
import org.ts.ddcs.common.util.ValueLen;
import org.ts.ddcs.dataStream.*;
import org.ts.ddcs.datatemplate.TestState;
import org.ts.ddcs.itemdatatemplate.DataItemTemplate;
import org.ts.ddcs.metadata.DataStreamCacheMetadata;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

/***
 * Date:2021/12/16
 * Title:数据处理器模块
 * Description：读取运行参数回报 0x43
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public class DataStreamSwReadRunSettingDatagramProcessor extends DataStreamProcessor {

    private DataStreamCache dataStreamCache;
    private Map<String, List<Map<String, Object>>> keyStore = new HashMap<>();

    @Override
    public void init(DataStreamLineManager context) {
        this.context = context;
        this.dataStreamCache = context.getCache();
    }

    @Override
    public void process(DataStreamAdapter dataStreamAdapter) throws UnsupportedEncodingException {
        this.dataStreamCache.setState(TestState.MATHCE);
        this.dataStreamCache.setMatchProcessor(this);
        String datagramCode = this.dataStreamCache.getDatagramCode();
        if (SwDatagramTypeCodeEnum.DATAGRAM_CODE_43.getName().equals(datagramCode)) {
            this.keyStore.clear();
            String agreement = dataStreamAdapter.getAgreement();
            Map<String, DataItemTemplate> itemTemplateMap = this.context.getItemTemplate(agreement);
            //解析报文
            byte[] dataArea = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_DATA_AREA.getName());
            int count = 0;
            //流水号
            byte[] serialNo = BytesHelp.subBytes(dataArea, count, 2);
            dataStreamCache.putValue(DataStreamCacheMetadata.METADATA_SERIAL_NO.getName(), serialNo);
            count += 2;
            //String serialNo = Sw2014DatagramTemplateHelp.toSerialNo(dataArea, count);
            // dataStreamCache.putValue(DatagramConstant.serialNo, serialNo);
            // 发报时间
            byte[] sendPacketTime = BytesHelp.subBytes(dataArea, count, 6);
            dataStreamCache.putValue(DataStreamCacheMetadata.METADATA_UP_TIME_BYTE.getName(), sendPacketTime);
            count += 6;
            //String sendPacketTime = Sw2014DatagramTemplateHelp.toSendPacketTime(dataArea, count);
            // dataStreamCache.putValue(DatagramConstant.sendPacketTime, sendPacketTime);
            //遥测站地址
            DataItemTemplate itemTemplateSt = itemTemplateMap.get(SwElementCodeEnum.CODE_ST.getCode());
            //itemTemplateSt.clear();
            int readSize = itemTemplateSt.stream(dataArea, count);
            if (itemTemplateSt.isMacth()) {
                itemTemplateSt.saveValue(this.keyStore);
            }
            count += readSize;
            while (count < dataArea.length) {

                byte[] f = BytesHelp.subBytes(dataArea, count, 1);
                count += 1;
                String flagCode = BytesHelp.byte2HexStr(f);
                ValueLen valueLen = Sw2014DatagramTemplateHelp.getValueLen(dataArea, count);
                int dataTotalLen = valueLen.getByteLen();
                int decimalLen = valueLen.getDecimalLen();
                count += 1;
                byte[] value = BytesHelp.subBytes(dataArea, count, dataTotalLen);
                count += dataTotalLen;
                if (flagCode.equals(RunSettingFlag.intervalTime.getId())) {
                    //定时报时间间隔
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "intervalTime");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), BytesHelp.byte2HexStr(value));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.intervalTime.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("intervalTime", list);
                } else if (flagCode.equals(RunSettingFlag.addIntervalTime.getId())) {
                    //加报时间间隔
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "addIntervalTime");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), StringUtil.getPrettyNumber(BytesHelp.byte2HexStr(value)));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.addIntervalTime.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("addIntervalTime", list);
                } else if (flagCode.equals(RunSettingFlag.rainTime.getId())) {
                    //降水量日起始时间
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "rainTime");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), StringUtil.getPrettyNumber(BytesHelp.byte2HexStr(value)));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.rainTime.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("rainTime", list);
                } else if (flagCode.equals(RunSettingFlag.collectInterval.getId())) {
                    //采样间隔
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "collectInterval");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), StringUtil.getPrettyNumber(BytesHelp.byte2HexStr(value)));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.collectInterval.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("collectInterval", list);
                } else if (flagCode.equals(RunSettingFlag.dataSaveInterval.getId())) {
                    //水位数据存储间隔
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "dataSaveInterval");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), StringUtil.getPrettyNumber(BytesHelp.byte2HexStr(value)));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.dataSaveInterval.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("dataSaveInterval", list);
                } else if (flagCode.equals(RunSettingFlag.rainAddValue.getId())) {
                    //雨量加报阈值
                    Map<String, Object> data = new HashMap<>();
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "rainAddValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), StringUtil.getPrettyNumber(BytesHelp.byte2HexStr(value)));
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.rainAddValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("rainAddValue", list);
                } else if (flagCode.equals(RunSettingFlag.waterLevelBase.getId())) {
                    //水位基值1
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "waterLevelBase");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.waterLevelBase.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("waterLevelBase", list);
                } else if (flagCode.equals(RunSettingFlag.waterLevelCorrectValue.getId())) {
                    //水位修正基值1
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "waterLevelCorrectValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.waterLevelCorrectValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("waterLevelCorrectValue", list);
                } else if (flagCode.equals(RunSettingFlag.addWaterLevel.getId())) {
                    //加报水位1
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "addWaterLevel");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.addWaterLevel.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("addWaterLevel", list);
                } else if (flagCode.equals(RunSettingFlag.addWaterUpValue.getId())) {
                    //加报水位以上加报阈值
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "addWaterUpValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.addWaterUpValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("addWaterUpValue", list);
                } else if (flagCode.equals(RunSettingFlag.addWaterDownValue.getId())) {
                    //加报水位以下加报阈值
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "addWaterDownValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.addWaterDownValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("addWaterDownValue", list);
                } else if (flagCode.equals(RunSettingFlag.flowValue.getId())) {
                    //流量加报阈值
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "flowValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.flowValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("flowValue", list);
                } else if (flagCode.equals(RunSettingFlag.flowSpeetValue.getId())) {
                    //流速加报阈值
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "flowSpeetValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.flowSpeetValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("flowSpeetValue", list);
                } else if (flagCode.equals(RunSettingFlag.waterGateValue.getId())) {
                    //闸位加报阀值
                    Map<String, Object> data = new HashMap<>();
                    BigDecimal dec = BytesHelp.toDecimal(BytesHelp.byte2HexStr(value), decimalLen);
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), "waterGateValue");
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_VALUE.getName(), dec.toPlainString());
                    data.put(ElementDataMetadataEnum.ELEMENT_METADATA_CODE.getName(), RunSettingFlag.waterGateValue.getId());
                    List<Map<String, Object>> list = new ArrayList<>();
                    list.add(data);
                    this.keyStore.put("waterGateValue", list);
                }
            }
            this.next(false);
        } else {
            this.next(true);
        }
    }

    @Override
    public void close(DataStreamAdapter dataStreamAdapter) {

    }

    @Override
    public void batchComplete(DataStreamAdapter dataStreamAdapter) {

        log.info("接收到43读取运行参数,回复报文");
        //帧起始符
        byte[] respPacket = new byte[2];
        respPacket[0] = 0x7e;
        respPacket[1] = 0x7e;
        //遥测站地址
        byte[] rtuCodeByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_RTU_CODE.getName());
        respPacket = BytesHelp.arrayApend(respPacket, rtuCodeByte);
        //中心站地址
        byte[] centerStationByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_CENTER_STATION_CODE.getName());
        respPacket = BytesHelp.arrayApend(respPacket, centerStationByte);
        //密码
        byte[] rtuPwByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_SW_PW.getName());
        respPacket = BytesHelp.arrayApend(respPacket, rtuPwByte);
        //功能码
        byte[] funcCodeByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_SW_AFN.getName());
        respPacket = BytesHelp.arrayApend(respPacket, funcCodeByte);
        //报文下行标识及长度
        respPacket = BytesHelp.arrayApend(respPacket, BytesHelp.hexStr2Bytes("8008"));
        //报文起始符
        byte[] dataAreaStartFlagByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_DATA_AREA_START_FLAG.getName());
        respPacket = BytesHelp.arrayApend(respPacket, dataAreaStartFlagByte);
        //流水号
        byte[] serialNoByte = this.dataStreamCache.getBytesValue(DataStreamCacheMetadata.METADATA_SERIAL_NO.getName());
        respPacket = BytesHelp.arrayApend(respPacket, serialNoByte);
        //发报时间
        respPacket = BytesHelp.arrayApend(respPacket, Sw2014DatagramTemplateHelp.getFBTm());
        //RTU2014年报文正文结束符
        respPacket = BytesHelp.arrayApend(respPacket, SwDatagramConstant.PACKET_CONTROL_FLAG_ESC);
        //CRC16
        byte[] crc16 = Sw2014DatagramTemplateHelp.crcFun2014(respPacket);
        respPacket = BytesHelp.arrayApend(respPacket, crc16);
        dataStreamAdapter.output(respPacket);

    }

    @Override
    public List<Map<String, Object>> sink(DataStreamAdapter dataStreamAdapter) {
        try {
            List<Map<String, Object>> elementDataList = new LinkedList<>();
            Set<String> keys = this.keyStore.keySet();
            for (String key : keys) {
                Map<String, Object> data = new HashMap<>();
//                data.put(JsonPackMetadataEnum.PACK_METADATA_DATAGRAM.getName(), BytesHelp.byte2HexStr(this.dataStreamCache.getDatagramBuff()));
//                data.put(JsonPackMetadataEnum.PACK_METADATA_FROM_TIME.getName(), this.dataStreamCache.getPickPacketTime());
                // data.put(SinkJsonPackMetadataEnum.PACK_METADATA_FROM_TIME.getName(), this.dataStreamCache.getValue(DatagramConstant.pickPacketTime));
//                data.put(JsonPackMetadataEnum.PACK_METADATA_RTU_CODE.getName(), this.dataStreamCache.getRtuCode());
//
//                String collectTime = this.dataStreamCache.getStringValue(DatagramConstant.collectTime);
//                if (null != collectTime) {
//                    data.put(JsonPackMetadataEnum.PACK_METADATA_COLLECT_TIME.getName(), collectTime);
//                } else {
//                    data.put(JsonPackMetadataEnum.PACK_METADATA_COLLECT_TIME.getName(), DatagramHelp.getCollectTime(this.keyStore));
//                }
                //  data.put(SinkJsonPackMetadataEnum.PACK_METADATA_COLLECT_TIME.getName(), this.dataStreamCache.getStringValue(DatagramConstant.collectTime));
                // data.put(JsonPackMetadataEnum.PACK_METADATA_UP_TIME.getName(), this.dataStreamCache.getStringValue(DatagramConstant.sendPacketTime));
                data.put(DatagramMetadataEnum.CACHE_METADATA_ELEMENT_CODE.getName(), key);
                List<Map<String,Object>> elements = this.keyStore.get(key);
                for (Map<String,Object> jsonObject : elements) {
                    log.info("element {}", JSONObject.toJSONString(jsonObject));
                }
                if (null != elements) {
                    data.put(DatagramMetadataEnum.CACHE_METADATA_DATA.getName(), elements);
                }
                elementDataList.add(data);
            }
            return elementDataList;
        } catch (Exception e) {
            return null;
        }
    }

}
