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


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.ts.ddcs.common.metadata.JsonPackMetadataEnum;
import org.ts.ddcs.enums.SzyDatagramTypeCodeEnum;
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.DataStreamAdapter;
import org.ts.ddcs.dataStream.DataStreamCache;
import org.ts.ddcs.dataStream.DataStreamLineManager;
import org.ts.ddcs.dataStream.DataStreamProcessor;
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 DataStreamSzyExtStatusDatagramProcessor 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 (SzyDatagramTypeCodeEnum.DATAGRAM_CODE_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[] sendPacketTime = BytesHelp.subBytes(dataArea, count, 6);
            byte tmp = sendPacketTime[5];
            sendPacketTime[5] = sendPacketTime[0];
            sendPacketTime[0] = tmp;
            tmp = sendPacketTime[4];
            sendPacketTime[4] = sendPacketTime[1];
            sendPacketTime[1] = tmp;
            tmp = sendPacketTime[3];
            sendPacketTime[3] = sendPacketTime[2];
            sendPacketTime[2] = tmp;
            dataStreamCache.putValue(DataStreamCacheMetadata.METADATA_UP_TIME_BYTE.getName(), sendPacketTime);
            count += 6;
            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 (index < orgLen) {
                    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();
                    }
                }
            }
            this.next(false);
        } else {
            this.next(true);
        }
    }

    @Override
    public void close(DataStreamAdapter dataStreamAdapter) {

    }

    @Override
    public void batchComplete(DataStreamAdapter dataStreamAdapter) {
        log.info("接收到接收到水资源 F5 状态报");
        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> m : list) {
                    log.info("item {} {}", key, JSONObject.toJSONString(m));
                }
            }
        }
    }

    @Override
    public List<Map<String, Object>> sink(DataStreamAdapter dataStreamAdapter) {
        List<Map<String, Object>> datas = new ArrayList<>();
        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.getStringValue(DataStreamCacheMetadata.METADATA_PICK_TIME.getName()));
        data.put(JsonPackMetadataEnum.PACK_METADATA_RTU_CODE.getName(), this.dataStreamCache.getRtuCode());
        datas.add(data);
        return datas;
    }
}
