package cn.cecep.talroad.service.impl;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.analysis.SRaFactoryTransferRateAnalysis;
import cn.cecep.talroad.domain.dto.BMainPollMonDTO;
import cn.cecep.talroad.enums.PollutantTypeEnum;
import cn.cecep.talroad.mapper.AmProblemFiMapper;
import cn.cecep.talroad.mapper.BMainPollDisGasMoutMapper;
import cn.cecep.talroad.mapper.BMainPollDisSelfMonMapper;
import cn.cecep.talroad.mapper.BMainPollDisWaterMoutMapper;
import cn.cecep.talroad.mapper.analysis.SRaFactoryTransferRateAnalysisMapper;
import cn.cecep.talroad.service.TradeMonitorService;
import cn.cecep.talroad.vo.analysis.OutletPollutantVO;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


/**
 * 排污单位在线监测缺少污染物排放因子
 * @author szhpt
 * @date 2023-01-10
 */
@Service
public class TradeMonitorServiceImpl  implements TradeMonitorService {
    @Autowired
    private BMainPollDisSelfMonMapper mainPollDisSelfMonMapper;
    @Autowired
    private AmProblemFiMapper amProblemFiMapper;
    @Autowired
    private SRaFactoryTransferRateAnalysisMapper sRaFactoryTransferRateAnalysisMapper;
    @Autowired
    private BMainPollDisGasMoutMapper bMainPollDisGasMoutMapper;
    @Autowired
    private BMainPollDisWaterMoutMapper bMainPollDisWaterMoutMapper;

    @Override
    public void doUnitPollutantGasWarn() {
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        DateTime endTime = DateUtil.endOfMonth(lastMonth);
        DateTime startTime = DateUtil.beginOfMonth(lastMonth);
        List<BMainPollMonDTO> list = mainPollDisSelfMonMapper.selectBMainPollDisMonList(startTime,endTime, PollutantTypeEnum.GAS.getName());
        List<AmProblemFi> batchInsertLists = new ArrayList<>();
//        Map<String, String> outletNames = getOutletNameMap(list);
        //判断是否在线，不在线直接报警，在线查询排口速率小于50
        List<BMainPollMonDTO> listNotOnline = list.stream().filter(e->null==e.getIsOnline()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(listNotOnline)){
            List<String> outletCodes =listNotOnline.stream().map(e->e.getOutletCode()).collect(Collectors.toList());
            List<String> factoryIds =listNotOnline.stream().map(e->e.getFactoryId()).collect(Collectors.toList());
            List<OutletPollutantVO> pollutantVOS = bMainPollDisGasMoutMapper.selectGasOnlineOutletPollutant(factoryIds,outletCodes);
            if(CollectionUtils.isNotEmpty(pollutantVOS)){
                this.batchInsertList(pollutantVOS,endTime, startTime,batchInsertLists,PollutantTypeEnum.GAS.getCode());
            }
        }
        List<BMainPollMonDTO> listOnline = list.stream().filter(e->e.getIsOnline()!=null && 1==e.getIsOnline()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(listOnline)) {
            List<String> outletCodes = listOnline.stream().map(e -> e.getOutletCode()).collect(Collectors.toList());
            List<String> factoryIds = listOnline.stream().map(e -> e.getFactoryId()).collect(Collectors.toList());
            List<SRaFactoryTransferRateAnalysis> analysisLists = sRaFactoryTransferRateAnalysisMapper.selectDayRateOutletLt50List(factoryIds, outletCodes, startTime, endTime);
            if (CollectionUtils.isNotEmpty(analysisLists)) {
                List<String> lt50OutletCodes = analysisLists.stream().map(e -> e.getOutletCode()).collect(Collectors.toList());
                List<String> lt50FactoryIds = analysisLists.stream().map(e -> e.getFactoryId()).collect(Collectors.toList());
                List<OutletPollutantVO> pollutantVOS = bMainPollDisGasMoutMapper.selectGasOnlineOutletPollutant(lt50FactoryIds, lt50OutletCodes);
                if (CollectionUtils.isNotEmpty(pollutantVOS)) {
                    this.batchInsertList(pollutantVOS,endTime, startTime,batchInsertLists,PollutantTypeEnum.GAS.getCode());
                }
            }
        }
        if(CollectionUtils.isNotEmpty(batchInsertLists)){
            amProblemFiMapper.insertAmProblemFis(batchInsertLists);
        }
    }

    @Override
    public void doUnitPollutantWaterWarn() {
        Date lastMonth = DateUtils.addDateMonths(new Date(),-1);
        DateTime endTime = DateUtil.endOfMonth(lastMonth);
        DateTime startTime = DateUtil.beginOfMonth(lastMonth);
        List<BMainPollMonDTO> list = mainPollDisSelfMonMapper.selectBMainPollDisMonList(startTime,endTime, PollutantTypeEnum.WASTEWATER.getName());
        List<AmProblemFi> batchInsertLists = new ArrayList<>();
//        Map<String, String> outletNames = getOutletNameMap(list);
        //判断是否在线，不在线直接报警，在线查询排口速率小于50
        List<BMainPollMonDTO> listNotOnline = list.stream().filter(e->null==e.getIsOnline()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(listNotOnline)){
            List<String> outletCodes =listNotOnline.stream().map(e->e.getOutletCode()).collect(Collectors.toList());
            List<String> factoryIds =listNotOnline.stream().map(e->e.getFactoryId()).collect(Collectors.toList());
            List<OutletPollutantVO> pollutantVOS = bMainPollDisWaterMoutMapper.selectWaterOnlineOutletPollutant(factoryIds,outletCodes);
            if(CollectionUtils.isNotEmpty(pollutantVOS)) {
                this.batchInsertList(pollutantVOS,endTime, startTime,batchInsertLists,PollutantTypeEnum.WASTEWATER.getCode());
            }
        }
        List<BMainPollMonDTO> listOnline = list.stream().filter(e->e.getIsOnline()!=null && 1==e.getIsOnline()).collect(Collectors.toList());
        if(CollectionUtils.isNotEmpty(listOnline)) {
            List<String> outletCodes = listOnline.stream().map(e -> e.getOutletCode()).collect(Collectors.toList());
            List<String> factoryIds = listOnline.stream().map(e -> e.getFactoryId()).collect(Collectors.toList());
            List<SRaFactoryTransferRateAnalysis> analysisLists = sRaFactoryTransferRateAnalysisMapper.selectDayRateOutletLt50List(factoryIds, outletCodes, startTime, endTime);
            if (CollectionUtils.isNotEmpty(analysisLists)) {
                List<String> lt50OutletCodes = analysisLists.stream().map(e -> e.getOutletCode()).collect(Collectors.toList());
                List<String> lt50FactoryIds = analysisLists.stream().map(e -> e.getFactoryId()).collect(Collectors.toList());
                List<OutletPollutantVO> pollutantVOS = bMainPollDisWaterMoutMapper.selectWaterOnlineOutletPollutant(lt50FactoryIds, lt50OutletCodes);
                if (CollectionUtils.isNotEmpty(pollutantVOS)) {
                    this.batchInsertList(pollutantVOS,endTime, startTime,batchInsertLists,PollutantTypeEnum.WASTEWATER.getCode());
                }
            }
        }
        if(CollectionUtils.isNotEmpty(batchInsertLists)){
            amProblemFiMapper.insertAmProblemFis(batchInsertLists);
        }
    }

    //排口名称
    private  Map<String, String> getOutletNameMap(List<BMainPollMonDTO> lists){
        return  lists.stream().collect(Collectors.toMap(k->k.getOutletCode(),v->v.getOutletName()));
    }

    private Map<String,List<OutletPollutantVO>> factoryListToMapPollutant(List<OutletPollutantVO> lists){
        Map<String,List<OutletPollutantVO>> map = new HashMap<>();
        for (OutletPollutantVO e:  lists) {
            if(map.containsKey(e.getFactoryId())){
                List<OutletPollutantVO> l =  map.get(e.getFactoryId());
                l.add(e);
                map.put(e.getFactoryId(),l);
            }else{
                List<OutletPollutantVO> l = new ArrayList<>();
                l.add(e);
                map.put(e.getFactoryId(),l);
            }
        }
        return map;
    }

    private Map<String,List<OutletPollutantVO>> outletListToMapPollutant(List<OutletPollutantVO> pollutantVOS){
        Map<String,List<OutletPollutantVO>> map = new HashMap<>();
        for (OutletPollutantVO e:  pollutantVOS) {
            if(map.containsKey(e.getOutletCode())){
                List<OutletPollutantVO> l =  map.get(e.getOutletCode());
                l.add(e);
                map.put(e.getOutletCode(),l);
            }else{
                List<OutletPollutantVO> l = new ArrayList<>();
                l.add(e);
                map.put(e.getOutletCode(),l);
            }
        }
        return map;
    }

    private List<AmProblemFi> batchInsertList(List<OutletPollutantVO> pollutantVOS,DateTime endTime,DateTime startTime,List<AmProblemFi> batchInsertLists,String code){
        //企业ID转换成map
        Map<String, List<OutletPollutantVO>> map = factoryListToMapPollutant(pollutantVOS);
        map.forEach((k, v) -> {
            AmProblemFi amProblemFi = getAmProblemFi(v, code);
            amProblemFi.setProblemStartTime(startTime.toDateStr());
            amProblemFi.setProblemEndTime(endTime.toDateStr());
            amProblemFi.setAnalyseTime(startTime.toJdkDate());
            amProblemFi.setAnalyseTimeEnd(endTime.toJdkDate());
            batchInsertLists.add(amProblemFi);
        });
        return batchInsertLists;
    }

    /**
     * 合并污染因子报警信息
     * type 1废气、2废水
     */
    private AmProblemFi getAmProblemFi(List<OutletPollutantVO> pollutantVOS,String type){
        AmProblemFi fi = new AmProblemFi();
        fi.setFactoryId(pollutantVOS.get(0).getFactoryId());
        fi.setProblemSources("1");
        fi.setProblemType("003003");
        fi.setType(1);
        fi.setCreateTime(DateUtils.getNowDate());
        fi.setPollutantSourceAi(type);
        StringBuilder result = new StringBuilder(pollutantVOS.get(0).getFactoryName()).append("-");
        Map<String,List<OutletPollutantVO>> map=outletListToMapPollutant(pollutantVOS);
        map.forEach((k,v)->{
            result.append(v.get(0).getOutletName()).append("-在线监测缺少");
            v.stream().forEach(e->{
                result.append(e.getPollutantsType()).append(",");
            });
        });
        result.append("监测因子");
        fi.setProblemDetails(result.toString());
        return fi;
    }

}
