package com.pqs9900.serviceImpl.linedata;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.njcn.mapper.configuration.DeviceMapper;
import com.njcn.mapper.configuration.LineMapper;
import com.njcn.pojo.commons.AreaGeneralData;
import com.njcn.pojo.commons.runmanage.IntergralityData;
import com.njcn.pojo.commons.runmanage.IntergralityTable;
import com.njcn.pojo.commons.runmanage.OnlineRateData;
import com.njcn.pojo.configuration.Device;
import com.njcn.pojo.configuration.Line;
import com.njcn.pojo.terminal.UpDevVO;
import com.njcn.shiro.token.TokenManager;
import com.njcn.utils.AppConfig;
import com.njcn.utils.SocketClient;
import com.njcn.utils.UserUtil;
import com.njcn.utils.Utils;
import com.pqs9900.mapper.DataInfo.AlarmInfoMapper;
import com.pqs9900.mapper.linedata.OnlineRateCldMapper;
import com.pqs9900.mapper.linedata.TopStrategyMapper;
import com.pqs9900.pojo.DataInfo.AlarmInfo;
import com.pqs9900.pojo.linedata.*;
import com.pqs9900.service.linedata.TerminalRunService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * system
 *
 * @author cdf
 * @date 2021/11/3
 */
@Service
public class TerminalRunServiceImpl implements TerminalRunService {
    private static final Logger logger = LoggerFactory.getLogger(TerminalRunServiceImpl.class);


    @Resource
    private TopStrategyMapper topStrategyMapper;

    @Autowired
    private LineMapper lineMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private SocketClient socketClient;
    @Autowired
    private AppConfig appConfig;
    @Resource
    private OnlineRateCldMapper onlineRateCldMapper;


    @Override
    public Integer addForRun(TerminalRun terminalRun) {
        //判断是否存在重复数据
        TerminalRun count = topStrategyMapper.selectByPrimaryKey(terminalRun.getDicIndex());
        if(Objects.nonNull(count)){
            return -1;
        }
        terminalRun.setUpdateTime(new Date());
        terminalRun.setUpdateUser(TokenManager.getUserId());
        return topStrategyMapper.insert(terminalRun);
    }

    @Override
    public Integer updateForRun(TerminalRun terminalRun) {
        terminalRun.setUpdateTime(new Date());
        terminalRun.setUpdateUser(TokenManager.getUserId());
        return topStrategyMapper.updateByPrimaryKey(terminalRun);
    }

    @Override
    public TerminalRun queryForRun(String dicIndex) {
        return topStrategyMapper.selectByPrimaryKey(dicIndex);
    }

    @Override
    public List<TerminalRun> queryListForRun() {
        return topStrategyMapper.getList();
    }

    @Override
    public Integer deleteForRun(String dicIndex) {
        return topStrategyMapper.deleteByPrimaryKey(dicIndex);
    }

    /**
     * 运行管理--》终端在线率
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @Override
    public List<OnlineRateData> getOnlineRate(Date startTime, Date endTime,Integer lineGrade,Integer colorFlag) {

        List<OnlineRateData> onList = getOnlineRateData(startTime, endTime,lineGrade);
        if(CollectionUtil.isNotEmpty(onList)){
            List<TerminalRun> strList = topStrategyMapper.getList();
            if(CollectionUtil.isEmpty(strList)){
                logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
                return null;
            }

            HashMap<Integer,TerminalRun> hashMap = new HashMap();
            for(TerminalRun terminalRun:strList){
                hashMap.put(terminalRun.getDicLeave(),terminalRun);
            }
            if(hashMap.size() == 0){
                logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
                return null;
            }

            for(OnlineRateData onlineRateData :onList){
                if(Objects.isNull(onlineRateData.getLineGrade())){
                    onlineRateData.setColorFlag(1);
                }else{
                        //极重要
                        if(hashMap.containsKey(onlineRateData.getLineGrade())){
                            Float on =Float.parseFloat(onlineRateData.getOnlineRate());
                            Float rate = hashMap.get(onlineRateData.getLineGrade()).getOnlineValue();
                            if(on>rate){
                                onlineRateData.setColorFlag(1);
                            }else {
                                onlineRateData.setColorFlag(0);
                            }
                        }
                }

            }

        }


        if(Objects.nonNull(colorFlag)){
            if(colorFlag == 0){
                //不达标的
                onList = onList.stream().filter(item->item.getColorFlag()==0).collect(Collectors.toList());
            }else{
                onList = onList.stream().filter(item->item.getColorFlag()==1).collect(Collectors.toList());
            }
        }
        return onList;

    }

    /**
     * 根据装置索引，查询出需要展示的数据
     */
    private List<OnlineRateData> getOnlineRateData(Date startTime, Date endTime,Integer lineGrade) {
        List<OnlineRateData> onlineRateDatas = new ArrayList<>();
        onlineRateDatas = topStrategyMapper.selectOnlineRate(startTime, endTime,lineGrade);
        return onlineRateDatas;
    }


    /**
     * 运行管理--》监测点数据完整性
     *
     * @param startTime 起始时间
     * @param endTime   截止时间
     */
    @Override
    public IntergralityData getDataIntegralityTable(Date startTime, Date endTime,Integer lineGrade,Integer colorFlag) {
        IntergralityData intergralityData = new IntergralityData();

        //全网监测点的数据完整性
        intergralityData.setAllNets(getIntegralityTable(startTime, endTime,lineGrade,colorFlag));

        return intergralityData;
    }

    /**
     * 分片处理获取监测点数据完整性所有数据
     *
     * @param startTime  起始时间
     * @param endTime    截止时间
     */
    private List<IntergralityTable> getIntegralityTable(Date startTime, Date endTime,Integer lineGrade,Integer colorFlag) {
        List<IntergralityTable> intergralityTables = topStrategyMapper.selectIntegrityData(startTime, endTime,lineGrade);
        if(CollectionUtil.isEmpty(intergralityTables)){
            //进行完整性标准判断
           return intergralityTables;
        }
        List<TerminalRun> strList = topStrategyMapper.getList();
        if(CollectionUtil.isEmpty(strList)){
            logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
            return null;
        }

        HashMap<Integer,TerminalRun> hashMap = new HashMap();
        for(TerminalRun terminalRun:strList){
            hashMap.put(terminalRun.getDicLeave(),terminalRun);
        }
        if(hashMap.size() == 0){
            logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
            return null;
        }

        for(IntergralityTable intergralityTable :intergralityTables){
            if(Objects.isNull(intergralityTable.getLineGrade())){
                intergralityTable.setColorFlag(1);
            }else{
                    //极重要
                    if(hashMap.containsKey(intergralityTable.getLineGrade())){
                        Float on =Float.parseFloat(intergralityTable.getIntegrity());
                        Integer rate = hashMap.get(intergralityTable.getLineGrade()).getIntegrityValue();
                        if(on>rate){
                            intergralityTable.setColorFlag(1);
                        }else {
                            intergralityTable.setColorFlag(0);
                        }
                    }
            }

        }
        if(Objects.nonNull(colorFlag)){
            if(colorFlag == 0){
                //不达标的
                intergralityTables = intergralityTables.stream().filter(item->item.getColorFlag()==0).collect(Collectors.toList());
            }else{
                intergralityTables = intergralityTables.stream().filter(item->item.getColorFlag()==1).collect(Collectors.toList());
            }
        }
        return intergralityTables;
    }


    /**
     * 终端运行异常页面列表初始化
     * @author cdf
     * @date 2021/11/9
     */
    @Override
    public List<TopView> getRunExceptionList(Date beginTime, Date endTime, Integer lineGrade){
        List<TopView> allTopResList = topStrategyMapper.getTopView(beginTime,endTime,lineGrade);
        return allTopResList;
    }


    @Override
    public List<TopException> getRunExceptionDetail(Date timeId,Integer lineGrade){


        List<TopException>  allTopResList = topStrategyMapper.getRunExceptionDetail(timeId,lineGrade);

/*
        if(CollectionUtil.isNotEmpty(allTopResList)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(timeId);
            calendar.set(Calendar.HOUR_OF_DAY,23);
            calendar.set(Calendar.MINUTE,59);
            calendar.set(Calendar.SECOND,59);
            calendar.set(Calendar.MILLISECOND,999);
            Date endTime = calendar.getTime();


            List<TerminalRun> strategyList = topStrategyMapper.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);
            }

            for(TopException top : allTopResList){
                if(top.getAlarmNum()>0) {
                    Integer devIndex = top.getDevIndex();
                    List<AlarmInfo> alarmList = alarmInfoMapper.getAlarmDesc(devIndex, timeId, endTime);
                    List<String> descList = new ArrayList<>();
                    for(AlarmInfo alarmInfo:alarmList){
                        String time = sdf.format(alarmInfo.getOccurredTime());
                        String tmp = time+" "+alarmInfo.getDescrpiption();
                        descList.add(tmp);
                      //  top.setAlarmDesc(descList);
                    }
                }
                if(top.getComoutNum()>0){
                    //中断时间
                    if(hashMap.containsKey(top.getLineGrade())){
                        Integer offValue = hashMap.get(top.getLineGrade()).getOfftimeValue();
                        List<TopExceptionParam> offList =topStrategyMapper.getOffTimeList(top.getDevIndex(),timeId,endTime,offValue);
                        List<String> offResList = new ArrayList<>();
                        for(TopExceptionParam topExceptionParam: offList){
                           String normal = sdf.format(topExceptionParam.getNormalTime());
                            String off = sdf.format(topExceptionParam.getOffTime());
                            offResList.add(off+" ~ "+normal);
                        }
                        top.setOffDesc(offResList);
                    }

                }
            }
        }*/


        return allTopResList;
    }

    @Override
    public TopException getRunExceptionDetailById(Date timeId,Integer devIndex){
        return topStrategyMapper.getRunExceptionDetailById(timeId,devIndex);
    }

    @Override
    public List<DataIntegralityStatis> getDataIntegralityStatis(Long lineId, String startTime, String endTime) {
        List<DataIntegralityStatis> dataIntegralityStatis = new ArrayList<>();
        try{
            dataIntegralityStatis = topStrategyMapper.getDataIntegralityStatis(lineId,startTime,endTime);
        }catch (Exception e){
            logger.error("获取单个监测点的数据完整性异常");
        }
        return dataIntegralityStatis;
    }

    @Override
    public String socketonIntegrityData(String type, Long LineId, String startTime, String endTime) {
        String jsonStr = null;
        try {
            Line line =new Line();
            line.setLineIndex(LineId);
            line = lineMapper.selectOne(line);
            Device device = new Device();
            device.setDevIndex(Long.valueOf(line.getDevIndex()));
            device = deviceMapper.selectOne(device);
            UpDevVO upDevVO = new UpDevVO();
            upDevVO.setDevIndex(LineId.toString());
            upDevVO.setDevName(device.getName());
            String host = lineMapper.getNodeIpbylineIndex(LineId);
            Integer port = Integer.valueOf(appConfig.getSocketPort());
            IntegrityDataViewRVO upParamVO = new IntegrityDataViewRVO();
            IntegrityDataView valueVO = new IntegrityDataView();
            valueVO.setType(type);
            valueVO.setLineId(LineId);
            valueVO.setStartTime(startTime.replace("-",""));
            valueVO.setEndTime(endTime.replace("-",""));
            JSONObject jsonstr = new JSONObject(valueVO);
            Integer len = jsonstr.toString().length();
            upParamVO.setLen(len.toString());
            upParamVO.setData(valueVO);
            JSONObject jsonObject = new JSONObject(upParamVO);
            String str = jsonObject.toString();
            jsonStr = socketClient.sentIntegrityData(str,host,port);
        }catch (Exception e){
            return jsonStr;
        }
        return jsonStr;
    }

    @Override
    public  List<OnlineRateCldRVO> getOnlineRateCldList(Date startTime,Date endTime,Integer lineGrade,Integer colorFlag){
        List<OnlineRateCldRVO> list = onlineRateCldMapper.getOnlineRateCldList(startTime,endTime,lineGrade);
        if(CollectionUtil.isNotEmpty(list)){
            List<TerminalRun> strList = topStrategyMapper.getList();
            if(CollectionUtil.isEmpty(strList)){
                logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
                return null;
            }
            HashMap<Integer,TerminalRun> hashMap = new HashMap();
            for(TerminalRun terminalRun:strList){
                hashMap.put(terminalRun.getDicLeave(),terminalRun);
            }
            if(hashMap.size() == 0){
                logger.error(new Date()+" 9900在线率完整性策略配置为空异常");
                return null;
            }

            for(OnlineRateCldRVO onlineRateCldRVO :list){
                if(Objects.isNull(onlineRateCldRVO.getLineGrade())){
                    onlineRateCldRVO.setColorFlag(1);
                }else{
                    //极重要
                    if(hashMap.containsKey(onlineRateCldRVO.getLineGrade())){
                        Float on =onlineRateCldRVO.getOnlineRate();
                        Integer rate = hashMap.get(onlineRateCldRVO.getLineGrade()).getIntegrityValue();
                        if(on>rate){
                            onlineRateCldRVO.setColorFlag(1);
                        }else {
                            onlineRateCldRVO.setColorFlag(0);
                        }
                    }
                }

            }
            if(Objects.nonNull(colorFlag)) {
                if (colorFlag == 0) {
                    //不达标的
                    list = list.stream().filter(item -> item.getColorFlag() == 0).collect(Collectors.toList());
                } else {
                    list = list.stream().filter(item -> item.getColorFlag() == 1).collect(Collectors.toList());
                }
            }
        }
        return list;
    }

}
