package com.njcn.serviceimpl.advanced;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.njcn.mapper.advanced.RelevanceMapper;
import com.njcn.pojo.advanced.*;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.RedisDB;
import com.njcn.service.advanced.RelevanceService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.*;
import com.njcn.utils.redis.JedisManager;
import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class RelevanceServiceImpl implements RelevanceService {
    private static final Logger logger = LoggerFactory.getLogger(RelevanceServiceImpl.class);

    // 内部枚举类：高级算法处理事件的标识描述
    enum EnumFlag {
        PROCESSED(1, "计算成功"), UNTREATED(0, "未计算"), EXIST(1, "存在"), ABSENCE(0, "不存在"), NODATA(2, "无结果"), PROCESSFAIL(3, "计算失败");

        private Integer code;
        private String description;

        EnumFlag(Integer code, String description) {
            this.code = code;
            this.description = description;
        }

        public Integer getCode() {
            return code;
        }

        public String getDescription() {
            return description;
        }
    }

    @Autowired
    private RelevanceMapper relevanceMapper;

    @Autowired
    private UserUtil userUtil;

    @Autowired
    private JedisManager jedisManager;

    @Autowired
    private TransformerOperationServiceImpl transformerOperationServiceImpl;

    private WebSocketUtil webSocketUtil = new WebSocketUtil();

    private InstantiateUtil<List<EventAssObj>> instantiateUtil;
    private InstantiateUtil<String> stringInstantiateUtil;

    public RelevanceServiceImpl() {
        instantiateUtil = new InstantiateUtil<>();
        stringInstantiateUtil = new InstantiateUtil<>();
    }

    @Override
    public EntityRelevance querySagEvents(String queryCondition,String startTime, String endTime) throws Exception {

        //增加用户判断部门信息并获取详细事件信息
        List<AreaGeneralData> areaGeneral = userUtil.getAreaGeneralRun();
        List<SagEvent> list = new ArrayList<>();
        List<Integer> ll = new ArrayList<>();

        for (AreaGeneralData depts : areaGeneral) {
            List<Integer> listLineIndex = depts.getLineIndexs(); // 获取监测点ID
            ll.addAll(listLineIndex);
        }

        HashSet<Integer> hashSet = new HashSet<>(ll);

        SimpleDateFormat format = new SimpleDateFormat(DatePattern.NORM_DATE_PATTERN);
        for (Integer integer : hashSet) {
            SagEventsQueryCondition sagEventsQueryCondition = new SagEventsQueryCondition(DateUtil.beginOfDay(format.parse(startTime)), DateUtil.endOfDay(format.parse(endTime)), integer);
            list.addAll(relevanceMapper.querySagEvents(sagEventsQueryCondition));
        }

        // 拼接暂降事件发生时间并格式化处理
        for (SagEvent sagEvent : list) {

            sagEvent.setStrTime(PubUtils.date2String(sagEvent.getSagTime(), "yyyy-MM-dd HH:mm:ss") + "."
                    + PubUtils.getMs(sagEvent.getMsec()));
            sagEvent.setStrEventValue(String.format("%.2f", sagEvent.getEventValue() * 100));
            sagEvent.setStrPersist(String.valueOf(sagEvent.getPersistTime()));
            sagEvent.setTime(sagEvent.getSagTime().getTime() + sagEvent.getMsec());

            switch (sagEvent.getDealFlag().intValue()) {
                case 0:
                    sagEvent.setDealFlagDescription(EnumFlag.UNTREATED.getDescription());
                    break;
                case 1:
                    sagEvent.setDealFlagDescription(EnumFlag.PROCESSED.getDescription());
                    break;
                case 2:
                    sagEvent.setDealFlagDescription(EnumFlag.NODATA.getDescription());
                    break;
                case 3:
                    sagEvent.setDealFlagDescription(EnumFlag.PROCESSFAIL.getDescription());
                    break;
            }

            sagEvent.setFileFlagDescription(0 == Utils.getIntValue(sagEvent.getFileFlag().toString(), new Integer(0))
                    ? EnumFlag.ABSENCE.getDescription() : EnumFlag.EXIST.getDescription());
        }

        int dealCount = 0;
        int fileCount = 0;

        if (hashSet != null || hashSet.size() > 0) {
            List<Integer> list1 = new ArrayList<>(hashSet);
            dealCount = relevanceMapper.queryDealTotal(list1).intValue();
            fileCount = relevanceMapper.queryFileTotal(list1).intValue();
        }

        EntityRelevance entityRelevance = new EntityRelevance(dealCount, fileCount, list);

        return entityRelevance;
    }

    public EntityRelevance querySagEventss(String queryCondition) throws Exception {
        SagEventsQueryCondition sagEventsQueryCondition = new SagEventsQueryCondition(null, null, null);

        JSONArray jsonArray = JSONArray.fromObject(queryCondition);

        if (jsonArray.size() > 0) {
            if (jsonArray.getJSONObject(0).containsKey("startTime")
                    && jsonArray.getJSONObject(0).containsKey("endTime")) {
                sagEventsQueryCondition.setStartTime(PubUtils
                        .string2Date((String) jsonArray.getJSONObject(0).get("startTime"), "yyyy-MM-dd HH:mm:ss"));
                sagEventsQueryCondition.setEndTime(PubUtils
                        .string2Date((String) jsonArray.getJSONObject(0).get("endTime"), "yyyy-MM-dd HH:mm:ss"));
            }

            if (jsonArray.getJSONObject(0).containsKey("lineId")) {
                sagEventsQueryCondition.setLineId(Integer.parseInt(jsonArray.getJSONObject(0).get("lineId").toString()));
            }
        }

        //增加用户判断部门信息并获取详细事件信息
        List<SagEvent> list = new ArrayList<>();
        list.addAll(relevanceMapper.querySagEvents(sagEventsQueryCondition));

        // 拼接暂降事件发生时间并格式化处理
        for (SagEvent sagEvent : list) {
            sagEvent.setStrTime(PubUtils.date2String(sagEvent.getSagTime(), "yyyy-MM-dd HH:mm:ss") + "."
                    + PubUtils.getMs(sagEvent.getMsec()));
            sagEvent.setStrEventValue(String.format("%.2f", sagEvent.getEventValue() * 100));
            sagEvent.setStrPersist(String.valueOf(sagEvent.getPersistTime()));
            sagEvent.setTime(sagEvent.getSagTime().getTime() + sagEvent.getMsec());

            switch (sagEvent.getDealFlag().intValue()) {
                case 0:
                    sagEvent.setDealFlagDescription(EnumFlag.UNTREATED.getDescription());
                    break;
                case 1:
                    sagEvent.setDealFlagDescription(EnumFlag.PROCESSED.getDescription());
                    break;
                case 2:
                    sagEvent.setDealFlagDescription(EnumFlag.NODATA.getDescription());
                    break;
                case 3:
                    sagEvent.setDealFlagDescription(EnumFlag.PROCESSFAIL.getDescription());
                    break;
            }

            sagEvent.setFileFlagDescription(0 == Utils.getIntValue(sagEvent.getFileFlag().toString(), new Integer(0))
                    ? EnumFlag.ABSENCE.getDescription() : EnumFlag.EXIST.getDescription());
        }

        //int dealCount = relevanceMapper.queryDealTotal().intValue();
        //int fileCount = relevanceMapper.queryFileTotal().intValue();
        EntityRelevance entityRelevance = new EntityRelevance(0, 0, list);

        return entityRelevance;
    }

    @Override
    public String querySagEventByID(String indexEventdetail) throws Exception {
        MessageObj messageObj = new MessageObj();
        messageObj.setMsgId(messageObj.getRelevance() + 1);
        messageObj.setMsgBody("insert");

        webSocketUtil.sendAll(messageObj);

        return "";
    }

    @Override
    @Transactional
    public void processEvents(String arrayList) throws Exception {
        JSONArray jsonArray = JSONArray.fromObject(arrayList);
        normalization(jsonArray);

        // 关联分析处理成功后，推送数据到前台
        MessageObj messageObj = new MessageObj();
        messageObj.setMsgId(messageObj.getRelevance());
        messageObj.setMsgBody("update");

        webSocketUtil.sendAll(messageObj);

        /*
         * 测试 点对点推送 for (Map<String, Session> map : WebSocketObj.getList()) {
         * for (String strKey : map.keySet()) { if ("sunw".equals(strKey)) {
         * webSocketUtil.sendMsgObj(map.get(strKey), messageObj); } } }
         */
    }

    // 从redis查归一化处理的数据
    @SuppressWarnings("unchecked")
    public List<EventAssObj> queryNormalizeData() {
        String userIndex = TokenManager.getUserId();
        byte[] bytes = stringInstantiateUtil.instantiate(userIndex);

        return instantiateUtil.deInstantiate(
                jedisManager.hget(RedisDB.NORMALIZ, bytes, stringInstantiateUtil.instantiate(RedisDB.EVENTASSOBJECT)));
    }

    /***********************************************************
     * 提供接口，外部处理变压器矩阵信息缓存进redis
     ***********************************************************/
    public void setNodeInRedis() {
        HandleEvent handleEvent = new HandleEvent();
        getNodeInfo(handleEvent);
    }

    /*****************************************************************
     * 事件归一化处理
     ******************************************************************/
    @Transactional
    public void normalization(JSONArray jsonArray) {
        HandleEvent handleEvent = new HandleEvent();
        Date date = new Date();
        String userIndex = TokenManager.getUserId();
        byte[] bytes = stringInstantiateUtil.instantiate(userIndex);

        try {
            jedisManager.hdel(RedisDB.NORMALIZ, bytes, stringInstantiateUtil.instantiate(RedisDB.EVENTASSOBJECT));
        } catch (Exception e1) {

        }

        // 分析的事件进行处理
        EntityGroupEvtData[] entityGroupEvtDatas = handleEvent.getData(relevanceMapper, jsonArray);
        List<EntityGroupEvtData> list3 = new ArrayList<EntityGroupEvtData>();

        for (EntityGroupEvtData entityGroupEvtData : Arrays.asList(entityGroupEvtDatas)) {
            list3.add(entityGroupEvtData);
        }

        // 传入的处理事件根据物理隔绝进行分组
        Set<Map.Entry<String, Map<Integer, Integer>>> nodeSort = getNodeSort(); //变压器策略id,母线id，排序
        Set<Map.Entry<String, JSONObject>> setMtrans = getMtrans();
        List<SagEvent> listSagEvent = new ArrayList<SagEvent>();
        List<EventAssObj> listEventAssObj = new ArrayList<EventAssObj>();

        for (Map.Entry<String, Map<Integer, Integer>> m : nodeSort) {
            List<EntityGroupEvtData> list = new ArrayList<EntityGroupEvtData>();
            Set<Map.Entry<Integer, Integer>> mapValue = m.getValue().entrySet();
            FinalData.NODE_NUM = m.getValue().size();

            for (Map.Entry<Integer, Integer> mm : mapValue) {
                for (int i = 0; i < entityGroupEvtDatas.length; i++) {
                    if (entityGroupEvtDatas[i].getNodePhysics() == mm.getKey().intValue() && "短路故障".equals(entityGroupEvtDatas[i].getSagReason())) {
                        entityGroupEvtDatas[i].setNode(mm.getValue());
                        list.add(entityGroupEvtDatas[i]);
                    }
                }

                // 筛选不在矩阵中的事件id
                Iterator<EntityGroupEvtData> iterator = list3.iterator();
                while (iterator.hasNext()) {
                    EntityGroupEvtData entityGroupEvtData = iterator.next();

                    if (entityGroupEvtData.getNodePhysics() == mm.getKey().intValue() && "短路故障".equals(entityGroupEvtData.getSagReason())) {
                        iterator.remove();
                    }
                }
            }

            EntityGroupEvtData[] entityGroupEvtData = new EntityGroupEvtData[list.size()];
            Collections.sort(list);
            list.toArray(entityGroupEvtData);

            for (Map.Entry<String, JSONObject> mEntry : setMtrans) {
                if (mEntry.getKey().equals(m.getKey())) {
                    /********************************************************************
                     * 算法最多处理1000条数据，超过限制需分批处理 先将数据根据某种方式进行升序/降序排序，然后分段处理 加入循环处理
                     *********************************************************************/
                    int circulation = entityGroupEvtData.length % FinalData.MAX_EVT_NUM == 0
                            ? entityGroupEvtData.length / FinalData.MAX_EVT_NUM
                            : entityGroupEvtData.length / FinalData.MAX_EVT_NUM + 1;

                    for (int i = 0; i < circulation; i++) {
                        int to = 0;

                        if (i == circulation - 1) {
                            to = entityGroupEvtData.length % FinalData.MAX_EVT_NUM > 0
                                    ? entityGroupEvtData.length
                                    : (i + 1) * FinalData.MAX_EVT_NUM - 1;
                        } else {
                            to = (i + 1) * FinalData.MAX_EVT_NUM - 1;
                        }

                        EntityGroupEvtData[] arrayObj = Arrays.copyOfRange(entityGroupEvtData,
                                i * FinalData.MAX_EVT_NUM, to);
                        JSONObject entityMtrans = mEntry.getValue();
                        EntityGroupData entityGroupData = handleEvent.translate(arrayObj, (EntityMtrans) JSONObject.toBean(entityMtrans, EntityMtrans.class));
                        // 处理分析结果
                        handleEvent.show_group_info(entityGroupData, listSagEvent, listEventAssObj, date);
                    }
                }
            }
        }

        /******************************************************************************
         * 事件ID不在矩阵中，结果集为基础以时标为标准进行归集处理 注意：三相与(单相/两相)互斥
         *****************************************************************************/
        disposeNonStandardData(handleEvent, list3, listEventAssObj, listSagEvent, date);

        List<EventAssObj> list = new ArrayList<>();

        for (int i = 0; i < listEventAssObj.size(); i++) {
            list.add(listEventAssObj.get(i));

            if ((i + 1) % 1000 == 0) {
                relevanceMapper.insertEventAssData(list);
                list.clear();
            } else if (i == listEventAssObj.size() - 1) {
                relevanceMapper.insertEventAssData(list);
            }
        }

        List<SagEvent> list1 = new ArrayList<>();
        for (int i = 0; i < listSagEvent.size(); i++) {
            list1.add(listSagEvent.get(i));

            if ((i + 1) % 1000 == 0) {
                relevanceMapper.updateSagEventData(list1);
                list1.clear();
            } else if (i == listSagEvent.size() - 1) {
                relevanceMapper.updateSagEventData(list1);
            }
        }

        //relevanceMapper.insertEventAssData(listEventAssObj);
        //relevanceMapper.updateSagEventData(listSagEvent);

        // 增加策略记录
        String describe = "用户" + TokenManager.getToken().getLoginName() + "进行了关联分析";
        EntityPqsRelevance entityPqsRelevance = new EntityPqsRelevance(date, describe, 1,
                TokenManager.getToken().getUserIndex(), date);
        relevanceMapper.insertRelevance(entityPqsRelevance);

        // 将归一化处理的数据放入redis缓存中 数据缓存到redis前先清空redis数据
        for (EventAssObj eventAssObj : listEventAssObj) {
            try {
                eventAssObj.setStrTime(PubUtils.date2String(eventAssObj.getTime(), "yyyy-MM-dd HH:mm:ss"));
            } catch (Exception e) {

            }
        }

        try {
            jedisManager.hset(RedisDB.NORMALIZ, bytes, stringInstantiateUtil.instantiate(RedisDB.EVENTASSOBJECT),
                    instantiateUtil.instantiate(listEventAssObj), -1);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    public List<EntityPqsRelevance> queryEvents() throws Exception {
        List<EntityPqsRelevance> list = relevanceMapper.queryEvents();

        for (EntityPqsRelevance entityPqsRelevance : list) {
            entityPqsRelevance.setStrTime(PubUtils.date2String(entityPqsRelevance.getTimeId(), "yyyy-MM-dd HH:mm:ss"));
        }

        return list;
    }

    @Transactional
    public void deleteEvent(String date) throws Exception {
        relevanceMapper.deleteEvent(PubUtils.string2Date(date, "yyyy-MM-dd HH:mm:ss"));
        relevanceMapper.updateEvent(PubUtils.string2Date(date, "yyyy-MM-dd HH:mm:ss"));
        relevanceMapper.updateFlag(PubUtils.string2Date(date, "yyyy-MM-dd HH:mm:ss"));

        // 推送消息
        MessageObj messageObj = new MessageObj();
        messageObj.setMsgId(messageObj.getRelevance() + 2);
        messageObj.setMsgBody("update");
        webSocketUtil.sendAll(messageObj);
    }

    /**********************************************************************
     * 归集结果与非矩阵事件进行比对
     **********************************************************************/
    public void disposeNonStandardData(HandleEvent handleEvent, List<EntityGroupEvtData> list3, List<EventAssObj> list, List<SagEvent> list2, Date date) {
      /*下面内容注释运行无误可删除*/
       /* Iterator<EntityGroupEvtData> iterator = list3.iterator();

        while (iterator.hasNext()) {
            EntityGroupEvtData entityGroupEvtData = iterator.next();

            for (EventAssObj eventAssObj : list) {
                if (Math.abs(eventAssObj.getTime().getTime() - entityGroupEvtData.getSagEvent().getSagTime().getTime()) < 10000) {
                    int b = 0;
                    int a = 0;

                    for (SagEvent sagEvent : eventAssObj.getList()) {
                        if (sagEvent.getCata() == 9) {
                            b++;
                        } else if (sagEvent.getCata() != 10) {
                            a++;
                        }
                    }

                    if (b > 0) {
                        if (entityGroupEvtData.getCata() < 9) {
                            break;
                        }
                    } else if (a > 0) {
                        if (entityGroupEvtData.getCata() == 9) {
                            break;
                        }
                    }

                    iterator.remove();
                    entityGroupEvtData.getSagEvent().setIndexEventAss(eventAssObj.getIndexEventAss());
                    entityGroupEvtData.getSagEvent().setDealTime(date);
                    eventAssObj.getList().add(entityGroupEvtData.getSagEvent());
                    String describe = "事件关联分析编号" + eventAssObj.getName() + "共包含" + eventAssObj.getList().size() + "个事件";
                    eventAssObj.setDescribe(describe);
                    list2.add(entityGroupEvtData.getSagEvent());

                    break;
                }
            }
        }*/

        // 如果还有未归集的数据则单独拎为单一事件处理
        for (EntityGroupEvtData entityGroupEvtData : list3) {
            String strUUID = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            entityGroupEvtData.getSagEvent().setIndexEventAss(strUUID);
            entityGroupEvtData.getSagEvent().setDealTime(date);
            List<SagEvent> l = new ArrayList<SagEvent>();
            l.add(entityGroupEvtData.getSagEvent());
            handleEvent.processing(l, list, date);
            list2.add(entityGroupEvtData.getSagEvent());
        }
    }

    /******************************************************************************
     * 获取物理隔绝后节点信息
     ******************************************************************************/
    public Set<Map.Entry<String, Map<Integer, Integer>>> getNodeSort() {
        Set<Map.Entry<String, Map<Integer, Integer>>> setNodeSort = null;

        // 从redis中获取排序的节点信息
        try {
            @SuppressWarnings("unchecked")
            Map<String, Map<Integer, Integer>> mapSort = (Map<String, Map<Integer, Integer>>) SerializeUtil.deserialize(
                    jedisManager.getValueByKey(RedisDB.NORMALIZ, SerializeUtil.serialize(RedisDB.NODESORT)));

            setNodeSort = mapSort.entrySet();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }

        return setNodeSort;
    }

    /************************************************************************************
     * 获取变压器矩阵信息key.变压器guid value:
     ************************************************************************************/
    public Set<Map.Entry<String, JSONObject>> getMtrans() {
        Set<Map.Entry<String, JSONObject>> set = null;

        try {
            // @SuppressWarnings("unchecked")
            /*
             * Map<String, EntityMtrans> map = (Map<String, EntityMtrans>)
             * SerializeUtil
             * .deserialize(jedisManager.getValueByKey(RedisDB.NORMALIZ,
             * SerializeUtil.serialize(RedisDB.MTRANS)));
             */
            String string = jedisManager.getValueByKey(RedisDB.NORMALIZ, RedisDB.MTRANS);
            JSONObject jsonObject = JSONObject.fromObject(string);
            @SuppressWarnings("unchecked")
            Map<String, JSONObject> map = (Map<String, JSONObject>) jsonObject;
            set = map.entrySet();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return null;
        }

        return set;
    }

    /*************************************************************************************
     * 获取变压器信息并生成矩阵
     *************************************************************************************/
    public void getNodeInfo(HandleEvent handleEvent) {
        List<EntityLogic> list = transformerOperationServiceImpl.getLogic();

        if (list.size() > 0) {
            Map<String, List<Integer>> map = transformerOperationServiceImpl.getLogicInfo(list);
            Map<String, EntityMtrans> mapRedis = new HashMap<String, EntityMtrans>();

            nodeSort(map);

            Set<Map.Entry<String, Map<Integer, Integer>>> setNodeSort = getNodeSort();

            for (Map.Entry<String, Map<Integer, Integer>> m : setNodeSort) {
                FinalData.NODE_NUM = m.getValue().size();
                List<EntityLogic> listNew = new ArrayList<EntityLogic>();

                for (EntityLogic entityLogic : list) {
                    if (entityLogic.gettPIndex().equals(m.getKey())) {
                        entityLogic.setNode_h(m.getValue().get(entityLogic.getNodeBefore()));
                        entityLogic.setNode_l(m.getValue().get(entityLogic.getNodeNext()));
                        listNew.add(entityLogic);
                    }
                }

                EntityMtrans entityMtrans = new EntityMtrans();
                handleEvent.create_matrixcata(listNew, entityMtrans);
                mapRedis.put(m.getKey(), entityMtrans);
            }

            // 将结果写入redis缓存
            try {
                jedisManager.deleteByKey(RedisDB.NORMALIZ, RedisDB.MTRANS);
                JSONObject jsonObject = JSONObject.fromObject(mapRedis);
                String str = jsonObject.toString();
                jedisManager.saveValueByKey(RedisDB.NORMALIZ, RedisDB.MTRANS, str, -1);
                /*
                 * jedisManager.saveValueByKey(RedisDB.NORMALIZ,
                 * SerializeUtil.serialize(RedisDB.MTRANS),
                 * SerializeUtil.serialize(mapRedis), -1);
                 */
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }
    }

    /*******************************************
     * 增加排序功能并缓存进redis
     *******************************************/
    public void nodeSort(Map<String, List<Integer>> mapList) {
        Set<Map.Entry<String, List<Integer>>> sets = mapList.entrySet();
        Map<String, Map<Integer, Integer>> map = new HashMap<String, Map<Integer, Integer>>();

        for (Map.Entry<String, List<Integer>> m : sets) {
            int index = 1;
            Map<Integer, Integer> map2 = new HashMap<Integer, Integer>();

            for (Integer integer : m.getValue()) {
                map2.put(integer, index++);
            }

            map.put(m.getKey(), map2);
        }

        // 缓存进redis
        try {
            jedisManager.deleteByKey(RedisDB.NORMALIZ, RedisDB.NODESORT);
            jedisManager.saveValueByKey(RedisDB.NORMALIZ, SerializeUtil.serialize(RedisDB.NODESORT),
                    SerializeUtil.serialize(map), -1);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }
}

class HandleEvent {
    public EntityGroupData translate(EntityGroupEvtData entityGroupEvtData[], EntityMtrans entityMtrans) {
        // 获取测试数据的数组长度
        int test_log_num = entityGroupEvtData.length;

        // 实例化EntityGroupData，给其中的数组分配空间
        EntityGroupData group_buf = new EntityGroupData();

        // 填入日志
        setMatrixcata(group_buf, entityMtrans);
        create_evt_buf(entityGroupEvtData, group_buf, test_log_num);

        UtilNormalization.sort_Tstart(group_buf); // 根据时标进行划分
        // 根据暂降类型进行划分
        for (int i = 0; i < group_buf.getGrp_all_num(); i++)
            UtilNormalization.sort_cata(group_buf, i);

        return group_buf;
    }

    public EntityGroupEvtData[] getData(RelevanceMapper relevanceMapper, JSONArray jsonArray) {
        EntityGroupEvtData test_log[] = new EntityGroupEvtData[jsonArray.size()];

        for (int i = 0; i < jsonArray.size(); i++) { // 获取监测点线路序号
            int nodePhysics = relevanceMapper
                    .queryLineIdbyPointId((Integer) jsonArray.getJSONObject(i).get("indexPoint")).intValue();

            // 根据暂降类型获取高级算法对应的编号
            int cata = 0;
            long ll = 0L;
            int start_time = 0;

            if (jsonArray.getJSONObject(i).get("firstType") == JSONNull.getInstance()) {
                cata = relevanceMapper.queryCodebyGuid((String) jsonArray.getJSONObject(i).get("sagType")); // 获取类型
                ll = ((Long) jsonArray.getJSONObject(i).get("sagTime")).longValue()
                        + ((Integer) jsonArray.getJSONObject(i).get("msec")).intValue();
                start_time = (int) (ll / 1000);
            } else {
                cata = relevanceMapper.queryCodebyGuid((String) jsonArray.getJSONObject(i).get("firstType")); // 获取类型
                ll = ((Long) jsonArray.getJSONObject(i).get("firstTime")).longValue()
                        + ((Integer) jsonArray.getJSONObject(i).get("firstMs")).intValue();
                start_time = (int) (ll / 1000);
            }

            // 填充SagEvent对象数据
            SagEvent sagEvent = new SagEvent();
            PlantInfo plantInfo = new PlantInfo();

            sagEvent.setFirstTime(PubUtils.ms2Date(ll));// 必须增加，否则序列化出错
            sagEvent.setStrTime((String) jsonArray.getJSONObject(i).get("strTime"));
            sagEvent.setTime((Long) jsonArray.getJSONObject(i).get("time"));
            sagEvent.setFirstTimeMills(ll);
            sagEvent.setMsec((Integer) jsonArray.getJSONObject(i).get("msec"));
            sagEvent.setSagTime(PubUtils.ms2Date((Long) jsonArray.getJSONObject(i).get("sagTime")));
            plantInfo.setNameBD((String) jsonArray.getJSONObject(i).get("nameBD"));
            plantInfo.setNameGD((String) jsonArray.getJSONObject(i).get("nameGD"));
            plantInfo.setNamePoint((String) jsonArray.getJSONObject(i).get("namePoint"));
            sagEvent.setPlantInfo(plantInfo);
            sagEvent.setIndexPoint((Integer) jsonArray.getJSONObject(i).get("indexPoint"));
            sagEvent.setCata(cata);

            EntityGroupEvtData entityGroupEvtData = new EntityGroupEvtData(nodePhysics, start_time, cata, -1, sagEvent,jsonArray.getJSONObject(i).get("sagReason").toString());
            test_log[i] = entityGroupEvtData;
        }

        return test_log;
    }

    public void create_evt_buf(EntityGroupEvtData[] arr, EntityGroupData obj, int len) {
        System.arraycopy(arr, 0, obj.getIn_buf(), 0, arr.length);
        obj.setEvt_in_num(len);
    }

    public void create_matrixcata(List<EntityLogic> list, EntityMtrans entityMtrans) {
        EntityLogic[] node_data = new EntityLogic[list.size()];

        for (int i = 0; i < list.size(); i++) {
            node_data[i] = list.get(i);
        }

        int len = node_data.length;

        UtilNormalization.matrixcata_pro(node_data, entityMtrans, len);
    }

    public void setMatrixcata(EntityGroupData obj, EntityMtrans entityMtrans) {
        int i, j;

        for (i = 0; i < (FinalData.MAX_CATA_NUM - 1); i++) {
            for (j = 0; j < FinalData.NODE_NUM; j++)
                obj.getMatrixcata()[i][j] = entityMtrans.getMatrixcata1()[i][j];
        }
    }

    public void show_group_info(EntityGroupData obj, List<SagEvent> list, List<EventAssObj> list1, Date date) {
        int i, j, k;
        for (i = 0; i < obj.getGrp_all_num(); i++) {
            String strUUID = UUID.randomUUID().toString().replace("-", "").toLowerCase();
            List<SagEvent> list2 = new ArrayList<SagEvent>();

            for (j = 0; j < FinalData.MAX_CATA_NUM + 2; j++) {
                if (obj.getGrp_cata_num()[i][j] != 0) {
                    for (k = 0; k < obj.getGrp_cata_num()[i][j]; k++) {
                        obj.getGrp_cata_buf()[i][j][k].getSagEvent().setIndexEventAss(strUUID);
                        obj.getGrp_cata_buf()[i][j][k].getSagEvent().setDealTime(date);
                        list2.add(obj.getGrp_cata_buf()[i][j][k].getSagEvent());
                        list.add(obj.getGrp_cata_buf()[i][j][k].getSagEvent());
                    }
                }
            }

            if (list2.size() > 0) {
                processing(list2, list1, date);
            }
        }
    }

    public void processing(List<SagEvent> list, List<EventAssObj> lists, Date date) {
        // 根据暂降事件发生时间进行排序
        Collections.sort(list);
        EventAssObj eventAssObj = new EventAssObj();
        String strUUID = list.get(0).getIndexEventAss();

        // 归一化处理数据填充
        eventAssObj.setIndexEventAss(strUUID);

        // 事件发生时间
        eventAssObj.setTime(PubUtils.ms2Date(list.get(0).getTime()));

        // 关联事件名称
        String name = list.get(0).getStrTime();
        eventAssObj.setName(name);

        // 获取当前用户GUID
        eventAssObj.setIndexUser(TokenManager.getToken().getUserIndex());

        // 是否进行范围分析 默认未分析
        eventAssObj.setbRange(1);

        // 更新时间
        eventAssObj.setUpdateTime(date);

        // 暂降事件描述
        String describe = "事件关联分析编号" + name + "共包含" + list.size() + "个事件";
        eventAssObj.setDescribe(describe);

        eventAssObj.setList(list);
        lists.add(eventAssObj);
    }
}
