/**
 * 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.enums.SwElementCodeEnum;
import org.ts.ddcs.common.metadata.DatagramMetadataEnum;
import org.ts.ddcs.enums.SwDatagramTypeCodeEnum;
import org.ts.ddcs.common.util.BytesHelp;
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.util.*;

/***
 * Date:2021/12/16
 * Title:数据处理器模块
 * Description：均匀时段降水信息报 0x31
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public class DataStreamSwTimeIntervalDatagramProcessor 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_31.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());
            int readSize = itemTemplateSt.stream(dataArea, count);
            if (itemTemplateSt.isMacth()) {
                itemTemplateSt.saveValue(this.keyStore);
            }
            count += readSize;
            //遥测站分类码
            byte[] siteKind = BytesHelp.subBytes(dataArea, count, 1);
            count += 1;
            dataStreamCache.putValue(DataStreamCacheMetadata.METADATA_SITE_KIND.getName(), BytesHelp.byte2HexStr(siteKind));
            //采集时间
            DataItemTemplate itemTemplateTt = itemTemplateMap.get(SwElementCodeEnum.CODE_TT.getCode());
            readSize = itemTemplateTt.stream(dataArea, count);
            if (itemTemplateTt.isMacth()) {
                itemTemplateTt.saveValue(this.keyStore);
            }
            count += readSize;

            int mValue = 0;
            DataItemTemplate dataItemTemplateDRxnn = itemTemplateMap.get(SwElementCodeEnum.CODE_DRxnn.getCode());
            readSize = dataItemTemplateDRxnn.stream(dataArea, count);
            if (dataItemTemplateDRxnn.isMacth()) {
                byte[] valueBuff = dataItemTemplateDRxnn.getValueBuff();
                mValue = valueBuff[2];
            }
            count += readSize;
            if (mValue == 5) {
                //只处理5分钟时段数据
                //解析观测要素
                if (dataArea.length - count > 0) {
                    byte[] content = BytesHelp.subBytes(dataArea, count, dataArea.length - count);
                    int index = 0;
                    int orgLen = content.length;
                    while (true) {
                        String func = BytesHelp.byte2HexStr(content, index, 1);
                        int funcLen = 0;
                        if ("FF".equals(func.toUpperCase())) {
                            func = BytesHelp.byte2HexStr(content, index, 2).toUpperCase();
                            funcLen = 2;
                        } else {
                            funcLen = 1;
                        }
                        if (itemTemplateMap.containsKey(func)) {
                            DataItemTemplate itemTemplate = itemTemplateMap.get(func);
                            readSize = itemTemplate.stream(content, index);
                            index += readSize;
                            if (itemTemplate.isMacth()) {
                                itemTemplate.saveValue(this.keyStore);
                            }
                        } else {
                            index += funcLen;
                            ValueLen valueLen = Sw2014DatagramTemplateHelp.getValueLen(content, index);
                            index += 1;
                            index += valueLen.getByteLen() * 12;
                        }
                        if (index >= orgLen) {
                            break;
                        }
                    }
                }
            }
            this.next(false);
        } else {
            this.next(true);
        }
    }

    @Override
    public void close(DataStreamAdapter dataStreamAdapter) {

    }

    @Override
    public void batchComplete(DataStreamAdapter dataStreamAdapter) {
        Set<String> keys = this.keyStore.keySet();
        for (String key : keys) {
            List<Map<String,Object>> list = this.keyStore.get(key);
            if (null != list) {
                for (Map<String,Object> jsonObject : list) {
                    log.info("item {} {}", key, JSONObject.toJSONString(jsonObject));
                }
            }
        }
        log.info("接收到31均匀时段水文信息报,回复报文");
        //帧起始符
        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));
                }
                data.put(DatagramMetadataEnum.CACHE_METADATA_DATA.getName(), elements);
                elementDataList.add(data);
            }
            return elementDataList;
        } catch (Exception e) {
            return null;
        }
    }

//    @Override
//    public List<JSONObject> sinkJson(DataStreamAdapter dataStreamAdapter) {
//        List<JSONObject> datas = new LinkedList<>();
//        JSONObject body = new JSONObject();
//        body.put(DatagramPostEntityConstant.BASE_KEY_DATAGRAM, BytesHelp.byte2HexStr(this.dataStreamCache.getDatagramBuff()));
//        body.put(DatagramPostEntityConstant.BASE_KEY_RTU, dataStreamAdapter.getRtuCode());
//        body.put(DatagramPostEntityConstant.BASE_KEY_AGREEMENT, DatagramPostEntityConstant.AGREEMENT_KIND_SW);
//        body.put(DatagramPostEntityConstant.BASE_KEY_DATAGRAM_PICK_TM, this.dataStreamCache.getValue(DatagramConstant.pickPacketTime));
//        datas.add(body);
//        return datas;
//    }

}
