/**
 * 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.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：测站状态扩展报 0xF5
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@Slf4j
public class DataStreamSwStatusDatagramProcessor 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_EX_F5.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);
            int readSize = 0;
            //解析观测要素
            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);
                        //  itemTemplate.clear();
                        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();
                    }
                    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("接收到f5状态报");

    }

    @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());

                //  data.put(JsonPackMetadataEnum.PACK_METADATA_COLLECT_TIME.getName(), this.dataStreamCache.getStringValue(DatagramConstant.sendPacketTime));

                //  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;
//    }

}
