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

import cn.cecep.talroad.domain.*;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditRecord;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditResult;
import cn.cecep.talroad.enums.EmlTypeEnums;
import cn.cecep.talroad.mapper.*;
import cn.cecep.talroad.mapper.analysis.SRaActionReportsAuditRecordMapper;
import cn.cecep.talroad.mapper.analysis.SRaActionReportsAuditResultMapper;
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.function.Function;
import java.util.stream.Collectors;

/**
 * @author hehongyu
 * @description: 非正常工况/特殊时段有组织废气污染物监测数据统计表
 * @date 2023/8/12 17:16
 * 1.污染防治设施正常情况汇总表-废气污染防治设施表填报了数据，但是非正常工况有组织废气污染物监测数据统计表无数据。
 * 2.企业上传了非正常工况证明材料附件，但是非正常工况有组织废气污染物监测数据统计表无数据。
 * 3.在线监测系统中废气监测点位有非正常工况标记信息，但是非正常工况有组织废气污染物监测数据统计表无数据。
 */
@Slf4j
@Service
public class NotNormalOrgGasPollutantsService {

    @Autowired
    private BStatTableZxbgWrzlTotalMapper zxbgWrzlTotalMapper;

    @Autowired
    private BStatTableZxbgWrzlAbnormalitiesMapper zxbgWrzlAbnormalitiesMapper;

    @Autowired
    private SEnvGasMonHourMapper gasMonHourMapper;

    @Autowired  //TODO 特殊时段废气排放量  没看到任务逻辑里面有涉及到这张表的
    private BStatTableZxbgPflAirSpecialMapper statTableZxbgPflAirSpecialMapper;

    @Autowired
    private OdsPermissionSharereportattachmentAMapper sharereportattachmentAMapper;

    @Autowired
    private BMainActionReportsMapper actionReportsMapper;

    @Autowired
    private SRaActionReportsAuditRecordMapper recordMapper;

    @Autowired
    private SRaActionReportsAuditResultMapper auditResultMapper;

    public void execute(List<String> reportIds){

        LambdaQueryWrapper<BMainActionReports> reportQueryWrapper = new QueryWrapper<BMainActionReports>().lambda()
                .in(BMainActionReports::getId, reportIds);
        List<BMainActionReports> bMainActionReports = actionReportsMapper.selectList(reportQueryWrapper);
        //附件查询
        LambdaQueryWrapper<OdsPermissionSharereportattachmentA> fileQueryWrapper = new QueryWrapper<OdsPermissionSharereportattachmentA>()
                .lambda().in(OdsPermissionSharereportattachmentA::getReportid, reportIds)
                //TODO 暂时只能根据名称模糊搜索
                .like(OdsPermissionSharereportattachmentA::getFilename,"非正常工况证明材料");
        List<OdsPermissionSharereportattachmentA> fileList = sharereportattachmentAMapper.selectList(fileQueryWrapper);
        List<Long> fileReportIds = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(fileList)){
            fileReportIds = fileList.stream().map(OdsPermissionSharereportattachmentA::getReportid).collect(Collectors.toList());
        }
        List<String> updateReportIds = new ArrayList<>();
        for (BMainActionReports report : bMainActionReports){
            //条件是 报告周期 报告类型 企业id 只能单条了
            LambdaQueryWrapper<BStatTableZxbgWrzlAbnormalities> wrzlAbnormalitiesLambdaQueryWrapper = new QueryWrapper<BStatTableZxbgWrzlAbnormalities>().lambda()
                    .eq(BStatTableZxbgWrzlAbnormalities::getFactoryId, report.getFactoryId())
                    .eq(BStatTableZxbgWrzlAbnormalities::getZxbgPeriod, report.getReportsTime())
                    .eq(BStatTableZxbgWrzlAbnormalities::getZxbgType, report.getReportsType());
            Integer count = zxbgWrzlAbnormalitiesMapper.selectCount(wrzlAbnormalitiesLambdaQueryWrapper);
            boolean isEmptyData = false;
            if (count == null || count == 0){
                log.warn("非正常工况有组织废气污染物监测数据统计表无数据! report:{}", JSON.toJSONString(report));
                isEmptyData = true;
            }
            //1.污染防治设施正常情况汇总表-废气污染防治设施表填报了数据，但是非正常工况有组织废气污染物监测数据统计表无数据。 //条件是 报告周期 报告类型 企业id 只能单条了
            LambdaQueryWrapper<BStatTableZxbgWrzlTotal> tableZxbgWrzlTotalLambdaQueryWrapper = new QueryWrapper<BStatTableZxbgWrzlTotal>().lambda()
                    .eq(BStatTableZxbgWrzlTotal::getFactoryId, report.getFactoryId())
                    .eq(BStatTableZxbgWrzlTotal::getZxbgPeriod, report.getReportsTime())
                    .eq(BStatTableZxbgWrzlTotal::getZxbgType, report.getReportsType());
            Integer totalCount = zxbgWrzlTotalMapper.selectCount(tableZxbgWrzlTotalLambdaQueryWrapper);
            if (totalCount != null && totalCount != 0 && isEmptyData){
                //需要修改该条报告所对应的审核结果了
                updateReportIds.add(report.getId());
                continue;
            }
            //2.企业上传了非正常工况证明材料附件，但是非正常工况有组织废气污染物监测数据统计表无数据。
            if (fileReportIds.contains(report.getId()) && isEmptyData){
                //需要修改该条报告所对应的审核结果了
                updateReportIds.add(report.getId());
                continue;
            }
            //3.在线监测系统中废气监测点位有非正常工况标记信息，但是非正常工况有组织废气污染物监测数据统计表无数据。
            LambdaQueryWrapper<SEnvGasMonHour> gasMonHourLambdaQueryWrapper = new QueryWrapper<SEnvGasMonHour>().lambda()
                    .eq(SEnvGasMonHour::getFactoryId, report.getFactoryId())
                    // data_flag字段为GFBJ，非正常工况标记
                    .in(SEnvGasMonHour::getDataFlag, Arrays.asList("G","F","B","J","GFBJ"));
            gasMonHourLambdaQueryWrapper = getQueryWrapperBetweenDate(report.getReportsType(),gasMonHourLambdaQueryWrapper);
            Integer notNormalDataCount = gasMonHourMapper.selectCount(gasMonHourLambdaQueryWrapper);
            if (notNormalDataCount != null && notNormalDataCount != 0 && isEmptyData){
                //需要修改该条报告所对应的审核结果了
                updateReportIds.add(report.getId());
                continue;
            }
        }
        if (CollectionUtil.isEmpty(updateReportIds)){
            return;
        }
        Map<String, SRaActionReportsAuditResult> reportRecordMap = getReportRecordMap(updateReportIds);
        if (CollectionUtil.isEmpty(reportRecordMap.values())){
            log.warn("执行报告审核记录不存在！");
            return;
        }
        reportRecordMap.values().forEach(data -> data.setAbnormalOrganizedGasMonitoringData("非正常工况有组织废气污染物监测数据统计表无数据!"));
        //更新数据
        auditResultMapper.batchUpdate(new ArrayList<>(reportRecordMap.values()));
    }

    public LambdaQueryWrapper<SEnvGasMonHour> getQueryWrapperBetweenDate(String reportsType,LambdaQueryWrapper<SEnvGasMonHour> queryWrapper){
        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();
        queryWrapper.between(SEnvGasMonHour::getMonitoringTime,startTime,endTime);
        return queryWrapper;
    }

    public Map<String, SRaActionReportsAuditResult> getReportRecordMap(List<String> reportIds){
        LambdaQueryWrapper<SRaActionReportsAuditRecord> recordQueryWrapper = new QueryWrapper<SRaActionReportsAuditRecord>()
                .lambda()
                .select(SRaActionReportsAuditRecord::getId,SRaActionReportsAuditRecord::getReportId)
                .in(SRaActionReportsAuditRecord::getReportId, reportIds);
        List<SRaActionReportsAuditRecord> sRaActionReportsAuditRecords = recordMapper.selectList(recordQueryWrapper);
        if (CollectionUtil.isEmpty(sRaActionReportsAuditRecords)){
            log.warn("执行报告审核记录不存在！");
            return null;
        }
        List<String> recordIds = sRaActionReportsAuditRecords.stream().map(SRaActionReportsAuditRecord::getId).collect(Collectors.toList());
        Map<String, String> recordReportIdMap = sRaActionReportsAuditRecords.stream().collect(Collectors.toMap(SRaActionReportsAuditRecord::getId, SRaActionReportsAuditRecord::getReportId));
        LambdaQueryWrapper<SRaActionReportsAuditResult> queryWrapper = new QueryWrapper<SRaActionReportsAuditResult>().lambda().in(SRaActionReportsAuditResult::getRecordId, recordIds);
        List<SRaActionReportsAuditResult> sRaActionReportsAuditResults = auditResultMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(sRaActionReportsAuditResults)){
            log.warn("执行报告规范性审核结果记录不存在！");
            return null;
        }
        return sRaActionReportsAuditResults.stream().collect(Collectors.toMap(data -> recordReportIdMap.get(data.getRecordId()), Function.identity()));
    }

}
