package com.njcn.serviceimpl.advanced;

import com.njcn.mapper.advanced.WaveformMapper;
import com.njcn.pojo.advanced.EventAssObj;
import com.njcn.pojo.advanced.EventsQueryCondition;
import com.njcn.pojo.advanced.MessageObj;
import com.njcn.pojo.advanced.SagEvent;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.service.advanced.WaveformService;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import com.njcn.utils.WebSocketUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

@Service
public class WaveformServiceImpl implements WaveformService {
    @Autowired
    private WaveformMapper waveformMapper;
    @Autowired
    private UserUtil userUtil;

    private WebSocketUtil webSocketUtil = new WebSocketUtil();

    @Override
    public List<SagEvent> queryEventsByGUID(String queryCondition) throws Exception {
        EventsQueryCondition eventsQueryCondition = new EventsQueryCondition(null, null, null, null);

        JSONArray jsonArray = JSONArray.fromObject(queryCondition);

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

            if (jsonArray.getJSONObject(0).containsKey("strGuid")) {
                eventsQueryCondition.setStrGuid((String) jsonArray.getJSONObject(0).get("strGuid"));
            }

            if (jsonArray.getJSONObject(0).containsKey("arrGuid")) {
                JSONArray stringArr = (JSONArray) jsonArray.getJSONObject(0).get("arrGuid");
                List<String> list = new ArrayList<String>();

                for (int i = 0; i < stringArr.size(); i++) {
                    list.add((String) stringArr.getJSONObject(i).get("indexEventDetail"));
                }

                eventsQueryCondition.setListIndex(list);
            }
        }

        String area = userUtil.getDeptsIndex(TokenManager.getToken().getUserIndex());
        List<AreaGeneralData> deptdLists = userUtil.getAreaDataByInfo(area);
        List<Integer> list1 = new ArrayList<>();

        for (AreaGeneralData areaGeneralData : deptdLists) {
            list1.addAll(areaGeneralData.getLineIndexs());
        }

        if (list1.isEmpty()) {
            return new ArrayList<>();
        }

        List<SagEvent> list = waveformMapper.queryEventsByGUID(eventsQueryCondition, list1);


        for (SagEvent sagEvent : list) {
            sagEvent.setStrTime(
                    PubUtils.date2String(sagEvent.getSagTime(), "yyyy-MM-dd HH:mm:ss") + "." + sagEvent.getMsec());
            sagEvent.setStrEventValue(String.format("%.2f", sagEvent.getEventValue() * 100));
            sagEvent.setStrPersist(String.valueOf(sagEvent.getPersistTime()));
            sagEvent.setSortType(3);
            if(!"短路故障".equals(sagEvent.getSagReason())){
                sagEvent.setSagType("/");
            }
        }

        Collections.sort(list);

        return list;
    }

    @Override
    @Transactional
    public void addNormalization(String condition) throws Exception {
        List<SagEvent> list = new ArrayList<SagEvent>();
        JSONArray jsonArray = JSONArray.fromObject(condition);

        if (jsonArray.size() > 0) {
            JSONArray stringArr = (JSONArray) jsonArray.getJSONObject(0).get("arrGuid");
            String[] strArr = new String[stringArr.size()];
            SagEvent sagEvent = null;

            for (int i = 0; i < stringArr.size(); i++) {
                sagEvent = new SagEvent();
                sagEvent.setIndexEventDetail((String) stringArr.getJSONObject(i).get("indexEventDetail"));
                sagEvent.setIndexEventAss((String) jsonArray.getJSONObject(0).get("strGuid"));
                strArr[i] = (String) stringArr.getJSONObject(i).get("indexEventAss");
                list.add(sagEvent);
            }

            waveformMapper.addNormalization(list);
            String[] arrStr = array_unique(strArr);

            /**
             * 数据处理完成后需要更新事件描述
             */
            List<EventAssObj> list2 = new ArrayList<EventAssObj>();
            EventAssObj eventAssObj = null;

            for (int j = 0; j < arrStr.length; j++) {
                eventAssObj = new EventAssObj();
                List<SagEvent> list3 = waveformMapper.queryDataByGuid(arrStr[j]);

                /**
                 * 如果数据为空则删除该条记录，否则更新数据
                 */
                if (list3.size() == 0) {
                    waveformMapper.deleteDataByGuid(arrStr[j]);
                } else {
                    for (int i = 0; i < list3.size(); i++) {
                        list3.get(i).setFirstTimeMills(((Long) list3.get(i).getFirstTime().getTime()).longValue() + ((Integer) list3.get(i).getFirstMs()).intValue());
                    }

                    Collections.sort(list3);
                    String name = PubUtils.date2String(list3.get(0).getSagTime(), "yyyy-MM-dd HH:mm:ss") + "."
                            + PubUtils.getMs(list3.get(0).getMsec());
                    String describe = "事件关联分析编号" + name + "共包含" + list3.size() + "个事件";
                    eventAssObj.setDescribe(describe);
                    eventAssObj.setName(name);
                    eventAssObj.setTime(list3.get(0).getSagTime());
                    eventAssObj.setIndexEventAss(arrStr[j]);
                    eventAssObj.setIndexUser(TokenManager.getToken().getUserIndex());
                    list2.add(eventAssObj);
                }
            }

            if (list2.size() > 0) {
                waveformMapper.updateDataByGuid(list2);
            }

            MessageObj messageObj = new MessageObj();
            messageObj.setMsgId(messageObj.getRelevance() + 2);
            messageObj.setMsgBody("update");

            webSocketUtil.sendAll(messageObj);
        }
    }

    /**
     * 数组去重
     *
     * @param a
     * @return
     */
    public String[] array_unique(String[] a) {
        List<String> list = new LinkedList<String>();

        for (int i = 0; i < a.length; i++) {
            if (!list.contains(a[i])) {
                list.add(a[i]);
            }
        }

        return (String[]) list.toArray(new String[list.size()]);
    }

    @Override
    public void deleteWaveform(String condition) throws Exception {
        JSONArray jsonArray = JSONArray.fromObject(condition);
        List<String> list = new ArrayList<String>();

        if (jsonArray.size() > 0) {
            JSONArray stringArr = (JSONArray) jsonArray.getJSONObject(0).get("arrGuid");

            for (int i = 0; i < stringArr.size(); i++) {
                list.add((String) stringArr.getJSONObject(i).get("indexEventDetail"));
            }

            waveformMapper.updateWaveForm(list);

            String sqlCondition = (String) stringArr.getJSONObject(0).get("indexEventAss");
            List<EventAssObj> list2 = new ArrayList<EventAssObj>();
            EventAssObj eventAssObj = null;

            List<SagEvent> list3 = waveformMapper.queryDataByGuid(sqlCondition);

            /**
             * 如果数据为空则删除该条记录，否则更新数据
             */
            if (list3.size() == 0) {
                waveformMapper.deleteDataByGuid(sqlCondition);
            } else {
                eventAssObj = new EventAssObj();

                for (int i = 0; i < list3.size(); i++) {
                    list3.get(i).setFirstTimeMills(((Long) list3.get(i).getFirstTime().getTime()).longValue() + ((Integer) list3.get(i).getFirstMs()).intValue());
                }

                Collections.sort(list3);
                String name = PubUtils.date2String(list3.get(0).getSagTime(), "yyyy-MM-dd HH:mm:ss") + "."
                        + PubUtils.getMs(list3.get(0).getMsec());
                String describe = "事件关联分析编号" + name + "共包含" + list3.size() + "个事件";
                eventAssObj.setDescribe(describe);
                eventAssObj.setName(name);
                eventAssObj.setTime(list3.get(0).getSagTime());
                eventAssObj.setIndexEventAss(sqlCondition);
                eventAssObj.setIndexUser(TokenManager.getToken().getUserIndex());
                list2.add(eventAssObj);
            }

            if (list2.size() > 0) {
                waveformMapper.updateDataByGuid(list2);
            }

            MessageObj messageObj = new MessageObj();
            messageObj.setMsgId(messageObj.getRelevance() + 2);
            messageObj.setMsgBody("update");

            webSocketUtil.sendAll(messageObj);
        }
    }
}
