package com.njcn.serviceimpl.weeklyreport;

import com.njcn.mapper.advanced.RelevanceMapper;
import com.njcn.mapper.user.UserMapper;
import com.njcn.mapper.weeklyreport.GetAreaPointInfoDataMapper;
import com.njcn.mapper.weeklyreport.GetSagReasonDataMapper;
import com.njcn.mapper.weeklyreport.GetVoltageInfoDataMapper;
import com.njcn.pojo.advanced.SagEvent;
import com.njcn.pojo.advanced.SagEventsQueryCondition;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.configuration.DicData;
import com.njcn.pojo.weeklyreport.AreaPointInfoData;
import com.njcn.pojo.weeklyreport.ResultReasonData;
import com.njcn.pojo.weeklyreport.SagRateData;
import com.njcn.service.weeklyreport.WeeklyReportDataService;
import com.njcn.serviceimpl.commons.WaveServiceImpl;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.PubUtils;
import com.njcn.utils.ReadExcel;
import com.njcn.utils.UserUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class WeeklyReportDataServiceImpl implements WeeklyReportDataService {
    private static final Logger logger = LoggerFactory.getLogger(WeeklyReportDataServiceImpl.class);
    @Autowired
    private GetAreaPointInfoDataMapper getAreaPointInfoMapper;
    @Autowired
    private UserUtil userUtil;
    @Autowired
    private GetVoltageInfoDataMapper getVoltageInfoMapper;
    @Autowired
    private RelevanceMapper relevanceMapper;
    @Autowired
    private WaveServiceImpl waveServiceImpl;
    @Autowired
    private GetSagReasonDataMapper getSagReasonMapper;
    @Autowired
    private UserMapper userMapper;

    public static class Info {
        private String name;
        private Integer id;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }
    }

    @Override
    public List<AreaPointInfoData> getPointData(String userIndex, Date start, Date end) {
        List<AreaPointInfoData> listPointInfo = new ArrayList<>();
        String userId = (userMapper.getAppBaseUser(userIndex) == null ? userIndex : userMapper.getAppBaseUser(userIndex).getUserIndex());
        String area = userUtil.getDeptsIndex(userId);
        List<AreaGeneralData> deptdLists = userUtil.getAreaDataByInfo(area);

        for (AreaGeneralData areaGeneralData : deptdLists) {
            AreaPointInfoData areaPointInfo = new AreaPointInfoData();
            areaPointInfo.setName(areaGeneralData.getName());
            List<Integer> listLineIndex = areaGeneralData.getLineIndexs(); // 获取监测点ID

            if (listLineIndex.size() > 0) {
                Integer onLineCount = getAreaPointInfoMapper.getOnline(listLineIndex); // 获取监测点在线个数
                areaPointInfo.setOnLine(onLineCount == null ? 0 : onLineCount.intValue());

                if (listLineIndex.size() > 0) {
                    Integer eventCount = getAreaPointInfoMapper.getEventCount(listLineIndex, start, end);
                    areaPointInfo.setOffLine(listLineIndex.size() - areaPointInfo.getOnLine());
                    areaPointInfo.setEventCount(eventCount == null ? 0 : eventCount.intValue());
                } else {
                    areaPointInfo.setOffLine(0);
                    areaPointInfo.setEventCount(0);
                }
            } else {
                areaPointInfo.setEventCount(0);
                areaPointInfo.setOffLine(0);
                areaPointInfo.setOnLine(0);
            }

            listPointInfo.add(areaPointInfo);
        }

        return listPointInfo;
    }

    @Override
    public List<AreaPointInfoData> getVoltageData(String userIndex, Date start, Date end) {
        List<AreaPointInfoData> list = new ArrayList<>();
        String userId = (userMapper.getAppBaseUser(userIndex) == null ? userIndex : userMapper.getAppBaseUser(userIndex).getUserIndex());
        String area = userUtil.getDeptsIndex(userId);
        List<AreaGeneralData> deptdLists = userUtil.getAreaDataByInfo(area);
        List<Integer> listLineIndex = new ArrayList<>();

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

        List<DicData> list1 = getVoltageInfoMapper.getVoltageData();

        for (DicData dicData : list1) {
            AreaPointInfoData areaPointInfo = new AreaPointInfoData();
            areaPointInfo.setName(dicData.getDicName());
            List<Integer> list2 = getVoltageInfoMapper.getLineIndex(dicData.getDicIndex(), listLineIndex);

            if (list2.size() > 0) {
                Integer onLineCount = getVoltageInfoMapper.getOnLine(list2);// 获取监测点在线个数
                areaPointInfo.setOnLine(onLineCount == null ? 0 : onLineCount.intValue());
                Integer eventCount = getAreaPointInfoMapper.getEventCount(list2, start, end);
                areaPointInfo.setOffLine(list2.size() - areaPointInfo.getOnLine());
                areaPointInfo.setEventCount(eventCount == null ? 0 : eventCount.intValue());
            } else {
                areaPointInfo.setOnLine(0);
                areaPointInfo.setOffLine(0);
                areaPointInfo.setEventCount(0);
            }

            list.add(areaPointInfo);
        }

        return list;
    }

    public List<SagEvent> getSagEvent(String userIndex, Date start, Date end) {
        List<AreaGeneralData> areaGeneral = userUtil.getAppAreaGeneral(userIndex);
        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);

        for (Integer integer : hashSet) {
            SagEventsQueryCondition sagEventsQueryCondition = new SagEventsQueryCondition(start, end, integer);
            list.addAll(relevanceMapper.querySagEvents(sagEventsQueryCondition));
        }

        for (SagEvent sagEvent : list) {
            try {
                sagEvent.setStrTime(PubUtils.date2String(sagEvent.getSagTime(), "yyyy-MM-dd HH:mm:ss") + "."
                        + PubUtils.getMs(sagEvent.getMsec()));
                sagEvent.setStrEventValue(String.format("%.2f", sagEvent.getEventValue() * 100));
            } catch (Exception e) {
                logger.error(e.getMessage());
            }
        }

        return list;
    }

    @Override
    public List<SagEvent> getSagData(String userIndex, Date start, Date end) {
        List<SagEvent> list;
        list = getSagEvent(userIndex, start, end);
        Iterator iterator = list.iterator();

        for (; iterator.hasNext(); ) { //只考虑暂降事件
            SagEvent sagEvent = (SagEvent) iterator.next();

            if (sagEvent.getWaveType().intValue() != 1) {
                iterator.remove();
            }
        }

        // 根据暂降严重度重新排序，保留前五条数据，这里的记录数需不需要做配置?
        for (SagEvent sagEvent : list) {
            if (sagEvent.getSeverity() == null) {
                String value = waveServiceImpl.getYzd(sagEvent.getPersistTime(), sagEvent.getEventValue());
                sagEvent.setSeverity(Float.parseFloat(value));
            }

            sagEvent.setSortType(1); // 设置排序规则
        }

        // 排序，根据暂降严重度排序
        Collections.sort(list);

        if (list.size() > 20) {
            return list.subList(0, 20);
        }

        return list;
    }

    @Override
    public List<SagRateData> getSagReasonData(String userIndex, Date start, Date end) {
        List<ResultReasonData> list = getSagReasonMapper.getReasonName();
        List<SagRateData> listResult = new ArrayList<>();
        List<Integer> listLineId = new ArrayList<>();
        String userId = (userMapper.getAppBaseUser(userIndex) == null ? userIndex : userMapper.getAppBaseUser(userIndex).getUserIndex());
        String area = userUtil.getDeptsIndex(userId);
        List<AreaGeneralData> deptdLists = userUtil.getAreaDataByInfo(area);

        for (AreaGeneralData areaGeneralData : deptdLists) {
            if (!areaGeneralData.getLineIndexs().isEmpty()) {
                listLineId.addAll(areaGeneralData.getLineIndexs());
            }
        }

        if (listLineId.isEmpty()) {
            return null;
        }

        // 获取事件类型总数
        List<ResultReasonData> listTotal = getSagReasonMapper.getTotal(start, end, listLineId);

        int total = listTotal.size() > 0 ? 0 : 1;

        for (ResultReasonData resultReason : listTotal) {
            total += resultReason.getTotal().intValue();
        }

        for (ResultReasonData resultReason : list) {
            SagRateData sagRate = new SagRateData();
            sagRate.setName(resultReason.getName());
            sagRate.setCount(new Integer(0));

            for (ResultReasonData resultReason1 : listTotal) {
                if (resultReason.getDicindex().equals(resultReason1.getEventreason())) {
                    sagRate.setCount(resultReason1.getTotal());
                    break;
                }
            }

            sagRate.setRate(new Float((float) sagRate.getCount().intValue() / total * 100));
            listResult.add(sagRate);
        }

        return listResult;
    }

    @Override
    public List<SagEvent> getSagEvents(String userIndex, Date start, Date end) {
        List<SagEvent> list = getSagEvent(userIndex, start, end);

        for (SagEvent sagEvent : list) {
            if (sagEvent.getWaveType() != 1) {
                sagEvent.setSagReason("/");
            }

            sagEvent.setTime(sagEvent.getSagTime().getTime() + sagEvent.getMsec());
            sagEvent.setSortType(2); // 设置排序规则
        }

        // 排序，根据暂降发生时间排序
        Collections.sort(list);

        return list;
    }
}
