package cn.cecep.talroad.data.analyse.task.execute.report.specifications.audit;

import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.BMainActionReports;
import cn.cecep.talroad.domain.PcOutlet;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditRecord;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditResult;
import cn.cecep.talroad.domain.analysis.SRaSelfMonitoringData;
import cn.cecep.talroad.enums.EmlTypeEnums;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.mapper.AmProblemFiMapper;
import cn.cecep.talroad.mapper.BMainActionReportsMapper;
import cn.cecep.talroad.mapper.PcOutletMapper;
import cn.cecep.talroad.mapper.analysis.SRaActionReportsAuditRecordMapper;
import cn.cecep.talroad.mapper.analysis.SRaActionReportsAuditResultMapper;
import cn.cecep.talroad.mapper.analysis.SRaSelfMonitoringDataMapper;
import cn.cecep.talroad.util.DateUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author hehongyu
 * @description: 超标排放信息
 * @date 2023/8/12 17:17
 */
@Slf4j
@Service
public class ExcessiveEmissionsService {

    @Autowired
    private SRaActionReportsAuditResultMapper mapper;

    @Autowired
    private BMainActionReportsMapper actionReportsMapper;

    @Autowired
    private SRaSelfMonitoringDataMapper monitoringDataMapper;

    @Autowired
    private AmProblemFiMapper problemFiMapper;

    @Autowired
    private SRaActionReportsAuditRecordMapper recordMapper;

    @Autowired
    private PcOutletMapper outletMapper;

    public void execute(List<String> reportIds){
        //复杂 无法批量  直接遍历报告id 进行审核
        LambdaQueryWrapper<BMainActionReports> queryWrapper = new QueryWrapper<BMainActionReports>().lambda()
                .in(BMainActionReports::getId, reportIds);
        List<BMainActionReports> bMainActionReports = actionReportsMapper.selectList(queryWrapper);
        for (BMainActionReports bMainActionReport : bMainActionReports) {
            String factoryId = bMainActionReport.getFactoryId();
            String reportsType = bMainActionReport.getReportsType();//EmlTypeEnums
            //根据 企业id 加 报告周期 查询到对应报警信息表 是否有超标信息
            //按照报表审核类型的时间 为 查询数据开始的时间
            Calendar startCalendar = Calendar.getInstance();
            Calendar endCalendar = Calendar.getInstance();
            if (EmlTypeEnums.YEAR.getCode().equals(reportsType)) {
                //去年 开始的数据 到今年的数据
                startCalendar.setTime(DateUtil.parseTime(startCalendar.get(Calendar.YEAR) - 1 + "-01-01 00:00:00"));
                endCalendar.setTime(DateUtil.parseTime(endCalendar.get(Calendar.YEAR) + "-01-01 00:00:00"));
            }else if (EmlTypeEnums.QUARTER.getCode().equals(reportsType)) {
                //获取上季度的数据 此处获取到当前季度开始的日期 手动去-3月 上季度结束日期 就是本季度开始
                startCalendar.setTime(DateUtil.getQuarterStart(new Date()));
                startCalendar.set(Calendar.MONTH,startCalendar.get(Calendar.MONTH) - 3);
                endCalendar.setTime(DateUtil.getQuarterStart(new Date()));
            }else if (EmlTypeEnums.MONTH.getCode().equals(reportsType)) {
                //上月开始 到 这月结束的数据
                startCalendar.set(Calendar.DAY_OF_MONTH,0);
                DateUtil.setTimeZero(startCalendar);
                endCalendar.set(Calendar.DAY_OF_MONTH,1);
                DateUtil.setTimeZero(endCalendar);
                startCalendar.set(Calendar.MONTH,startCalendar.get(Calendar.MONTH) - 1);
            }
            Date endTime = endCalendar.getTime();
            Date startTime = startCalendar.getTime();
            //直接查询企业下 所有超标的站点和 污染物 然后去 执行报告进行匹配
            LambdaQueryWrapper<AmProblemFi> problemFiLambdaQueryWrapper = new QueryWrapper<AmProblemFi>().lambda()
                    .eq(AmProblemFi::getFactoryId, factoryId)
                    .eq(AmProblemFi::getProblemType, ProblemTypeEnum.CONCENTRATION_EXCEEDED_TYPE.getCode())
                    .between(AmProblemFi::getAnalyseTime, startTime, endTime);
            List<AmProblemFi> mAmProblemFis = problemFiMapper.selectList(problemFiLambdaQueryWrapper);
            if (CollectionUtil.isEmpty(mAmProblemFis)){
                log.warn("超标排放信息 无报警信息！bMainActionReport:{}", JSON.toJSONString(bMainActionReport));
                continue;
            }
            for (AmProblemFi mAmProblemFi : mAmProblemFis) {
                LambdaQueryWrapper<SRaSelfMonitoringData> dataLambdaQueryWrapper = new QueryWrapper<SRaSelfMonitoringData>().lambda()
                        .eq(SRaSelfMonitoringData::getFactoryId, mAmProblemFi.getFactoryId())
                        .eq(SRaSelfMonitoringData::getMonitorId, mAmProblemFi.getStationId())
                        //现有的报警内容中有污染物名称 直接根据污染物名称进行查询
                        .eq(SRaSelfMonitoringData::getPollutantsName, mAmProblemFi.getParamName())
                        .between(SRaSelfMonitoringData::getMonitorTime, startTime, endTime);
                List<SRaSelfMonitoringData> sRaSelfMonitoringData = monitoringDataMapper.selectList(dataLambdaQueryWrapper);
                //如果有该企业有报警信息 但是根据报警信息中的站点和污染物没有查询到实际数据 则认为是不规范
                if (CollectionUtil.isEmpty(sRaSelfMonitoringData)){
                    //转换一下排口id 和 code 将 排口编号 输出到提示内容里面
                    PcOutlet pcOutlet = outletMapper.selectOne(new QueryWrapper<PcOutlet>().lambda().select(PcOutlet::getOutletCode).eq(PcOutlet::getId, mAmProblemFi.getStationId()));
                    //报告id  排口编号 污染物名称
                    updateReportAuditData(bMainActionReport.getId(),pcOutlet.getOutletCode(),mAmProblemFi.getParamName());
                }
            }
        }
    }

    public void updateReportAuditData(String problemReportId,String outletCode, String pollutantsName){
        LambdaQueryWrapper<SRaActionReportsAuditRecord> recordQueryWrapper = new QueryWrapper<SRaActionReportsAuditRecord>()
                .lambda()
                .select(SRaActionReportsAuditRecord::getId,SRaActionReportsAuditRecord::getReportId)
                .eq(SRaActionReportsAuditRecord::getReportId, problemReportId);
        List<SRaActionReportsAuditRecord> sRaActionReportsAuditRecords = recordMapper.selectList(recordQueryWrapper);
        if (CollectionUtil.isEmpty(sRaActionReportsAuditRecords)){
            log.warn("执行报告审核记录不存在！");
            return;
        }
        List<String> recordIds = sRaActionReportsAuditRecords.stream().map(SRaActionReportsAuditRecord::getId).collect(Collectors.toList());
        LambdaQueryWrapper<SRaActionReportsAuditResult> queryWrapper = new QueryWrapper<SRaActionReportsAuditResult>().lambda().in(SRaActionReportsAuditResult::getRecordId, recordIds);
        List<SRaActionReportsAuditResult> sRaActionReportsAuditResults = mapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(sRaActionReportsAuditResults)){
            log.warn("执行报告规范性审核结果记录不存在！");
            return;
        }
        sRaActionReportsAuditResults.forEach(data -> data.setExcessiveEmissions("“"+outletCode+"”“"+pollutantsName+"”在执行周期内有超标排放信息，但是此表未填报。"));
        mapper.batchUpdate(sRaActionReportsAuditResults);
    }
}
