package com.shining.cloud.serviceImpl.information;

import cn.hutool.core.collection.CollectionUtil;
import com.github.pagehelper.PageHelper;
import com.njcn.pojo.commons.DatePojo;
import com.njcn.pojo.data.ComInformation;
import com.njcn.utils.PubUtils;
import com.njcn.utils.UserUtil;
import com.shining.cloud.mapper.information.DevDetailMapper;
import com.shining.cloud.mapper.information.DevMsgAssMapper;
import com.shining.cloud.mapper.information.DevMsgMapper;
import com.shining.cloud.mapper.information.MonFlowMapper;
import com.shining.cloud.pojo.information.*;
import com.shining.cloud.service.information.DevMsgAssService;
import org.apache.kafka.common.protocol.types.Field;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description: 终端消息详情ServiceImpl
 * @author: denghuajun
 * @time: 2019-10-17 14:12:01
 **/
@Service
public class DevMsgAssServiceImpl implements DevMsgAssService {
    @Resource
    private DevMsgAssMapper devMsgAssMapper;
    @Resource
    private DevDetailMapper devDetailMapper;
    @Resource
    private MonFlowMapper monFlowMapper;
    @Resource
    private DevMsgMapper devMsgMapper;
    @Autowired
    private UserUtil userUtil;

    @Override
    public List<DevMsgDetailInfo> deviceList(String devMsgIndex, int page, int num) {
        List<DevMsgDetailInfo> devMsgDetailInfos = new ArrayList<>();
        try {
            PageHelper.offsetPage((page - 1) * num, num);
            devMsgDetailInfos = devMsgAssMapper.deviceList(devMsgIndex);
            devMsgMapper.updateDevMsgState(devMsgIndex);
        } catch (Exception e) {
        }
        return devMsgDetailInfos;
    }

    @Override
    public int state(String userIndex) {
        return devMsgAssMapper.state(userIndex);
    }


    /**
     * @param devIndex 装置索引
     * @param timeID   年月日
     */
    @Override
    public DevMsgAssInfo devMsgInfo(int devIndex, Date timeID) {
        //时间的转换 1.只取年月日
        Calendar cal = Calendar.getInstance();
        cal.setTime(timeID);
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;
        int day = cal.get(Calendar.DATE);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String firstday, lastday;
        // 获取当前月的第一天
        cal.add(Calendar.MONTH, 0);
        cal.set(Calendar.DAY_OF_MONTH, 1);
        firstday = format.format(cal.getTime());
        //时间的组合 2.yyyy-mm-dd 00:00:00 yyyy-mm-dd 23:59:59
        DatePojo datePojo = new DatePojo();
        String mon = null, days = null;
        if (month < 10) {
            mon = "0" + month;
        } else {
            mon = String.valueOf(month);
        }
        if (day < 10) {
            days = "0" + day;
        } else {
            days = String.valueOf(day);
        }
        SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        String startTime = firstday + " 00:00:00";
        String startT = year + "-" + mon + "-" + days + " 00:00:00";
        String endTime = year + "-" + mon + "-" + days + " 23:59:59";
        datePojo = PubUtils.validateDate(startT, endTime, "devMsgInfo");
        List<ComInformation> comInformations = devMsgAssMapper.devMsgInfo(devIndex, datePojo.getStartTime(), datePojo.getEndTime());
        DevDetail devDetail = devDetailMapper.getDevDatail(devIndex);
        List<String> alarm = new ArrayList<String>();
        DevMsgAssInfo devMsgDetailInfos = new DevMsgAssInfo();
        if (devDetail != null) {
            List<TerminalRun> strategyList = devMsgMapper.getList();
            if (CollectionUtil.isEmpty(strategyList)) {
                //logger.error(new Date() + "终端运行异常判断策略标准为空,请先配置! 方法名TopExceptionTask");
               return null;
            }
            HashMap<Integer, TerminalRun> hashMap = new HashMap();
            for (TerminalRun terminalRun : strategyList) {
                hashMap.put(terminalRun.getDicLeave(), terminalRun);
            }

            Integer time = 3600000;
            if(devDetail.getLineGrade() == null){

            }else{
                if(hashMap.containsKey(devDetail.getLineGrade())){
                    TerminalRun terminalRun=hashMap.get(devDetail.getLineGrade());
                    time = terminalRun.getOfftimeValue()*60*1000;
                }
            }

            //时间的组合 3.yyyy-mm
            TopException monFlow = monFlowMapper.getMonFlowByTop(devIndex, datePojo.getStartTime());
            devMsgDetailInfos.setDevIndex(devDetail.getDevIndex());
            devMsgDetailInfos.setDevName(devDetail.getDevName());
            devMsgDetailInfos.setGdName(devDetail.getGdName());
            devMsgDetailInfos.setBdzName(devDetail.getBdzName());
            devMsgDetailInfos.setIp(devDetail.getIp());
            devMsgDetailInfos.setTimeID(devDetail.getTimeID());
            List<String> dt = new ArrayList<String>();
            int comOutNum = 0;
            SimpleDateFormat sDateFormatY = new SimpleDateFormat("yyyy-MM-dd");
            if (!comInformations.isEmpty()) {

                for (int i = 0; i < comInformations.size(); i++) {
                    String start = "";
                    Date startTmp =null;
                    String end = "";
                    //记录中断时间
                    if (comInformations.get(i).getType() == 0) {
                        startTmp = comInformations.get(i).getUpdateTime();
                        start = sDateFormat.format(startTmp);
                        if (comInformations.size() > 1) {
                            if (i < (comInformations.size() - 1)) {
                                if (comInformations.get(i + 1).getType() == 1) {
                                    Date endDate = comInformations.get(i + 1).getUpdateTime();
                                    end = sDateFormat.format(endDate);

                                    if(endDate.getTime()-startTmp.getTime()>=time){
                                        dt.add(start + "至" + end);
                                    }

                                } else {

                                   /* String endTimes = sDateFormatY.format(comInformations.get(i).getUpdateTime()) + " 23:59:59";
                                    Date endDate =null;
                                    try {
                                        endDate = sDateFormat.parse(endTimes);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    if(endDate.getTime()-startTmp.getTime()>=time){
                                        dt.add(start + "至" + endTimes);
                                    }
                                    dt.add(start + "至" + endTimes);*/
                                }
                            } else {

                                String endTimes = sDateFormatY.format(comInformations.get(i).getUpdateTime()) + " 23:59:59";
                                Date endDate =null;
                                try {
                                    endDate = sDateFormat.parse(endTimes);
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                if(endDate.getTime()-startTmp.getTime()>=time){
                                    dt.add(start + "至" + endTimes);
                                }
                            }
                        } else {

                            String endTimes = sDateFormatY.format(comInformations.get(i).getUpdateTime()) + " 23:59:59";
                            Date endDate =null;
                            try {
                                endDate = sDateFormat.parse(endTimes);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            if(endDate.getTime()-startTmp.getTime()>=time){
                                dt.add(start + "至" + endTimes);
                            }


                        }
                    }
                }
                devMsgDetailInfos.setComOutNum(dt.size());
                devMsgDetailInfos.setDevMsgDescribe(dt);
            } else {
                devMsgDetailInfos.setComOutNum(0);
                devMsgDetailInfos.setDevMsgDescribe(null);
            }
            if (monFlow != null) {
                if (monFlow.getFlowNum() > 95) {
                    devMsgDetailInfos.setFlowInfo(devDetail.getDevName() + "的总流量于" + sDateFormat.format(datePojo.getEndTime()) + "超过总流量" + monFlow.getFlowNum() + "%，目前已关闭除心跳外所有采集数据通道");
                } else {
                    devMsgDetailInfos.setFlowInfo(devDetail.getDevName() + "的总流量于" + sDateFormat.format(datePojo.getEndTime()) + "占总流量的" + monFlow.getFlowNum() + "%");
                }
            } else {
                devMsgDetailInfos.setFlowInfo(devDetail.getDevName() + "暂无流量套餐");
            }

            //告警
            List<AlarmInfo> alarmList = monFlowMapper.getAlarmByDev(devIndex,datePojo.getStartTime(),datePojo.getEndTime());
            if(CollectionUtil.isNotEmpty(alarmList)){
                for(AlarmInfo alarmInfo:alarmList){
                    String occTime = sDateFormat.format(alarmInfo.getOccurredTime());
                    alarm.add(occTime+" "+alarmInfo.getDescrpiption());
                }
            }else{
                alarm.add("暂无告警信息");
            }

            devMsgDetailInfos.setAlarmInfo(alarm);
        } else {
            devMsgDetailInfos = null;
        }
        return devMsgDetailInfos;
    }

    @Override
    public List<DevComInfo> getDevComInfo(String userId) {
        List<DevComInfo> result = new ArrayList<>();

        List<Integer> indexs = userUtil.ApplistLine(userId);
        if (!indexs.isEmpty()) {
            result = devMsgAssMapper.getDevComInfo(indexs);
        } else {
            result = null;
        }
        return result;
    }

    @Override
    public DevComTJ getDevComTJ(String userId) {
        DevComTJ result = new DevComTJ();

        List<Integer> indexs = userUtil.ApplistLine(userId);

        if (!indexs.isEmpty()) {
            result = devMsgAssMapper.getDevComTJ(indexs);
        } else {
            result = null;
        }
        return result;
    }
}
