package cn.cecep.talroad.data.analyse.task.label;

import cn.cecep.talroad.domain.BMainActionReports;
import cn.cecep.talroad.domain.PcLabel;
import cn.cecep.talroad.domain.PcLabelFactory;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditRecord;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditResult;
import cn.cecep.talroad.enums.LabelFactoryEnum;
import cn.cecep.talroad.enums.LabelValueEnum;
import cn.cecep.talroad.mapper.BMainActionReportsMapper;
import cn.cecep.talroad.mapper.PcLabelFactoryMapper;
import cn.cecep.talroad.mapper.PcLabelMapper;
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 cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hehongyu
 * @description: 是否存在执行报告未提交情况
 * @date 2023/7/17 22:28
 */
@Slf4j
@Service
public class ExecuteReportTaskService {

    @Autowired
    private SRaActionReportsAuditRecordMapper reportsAuditRecordMapper;

    @Autowired
    private PcLabelMapper labelMapper;

    @Autowired
    private PcLabelFactoryMapper labelFactoryMapper;

    @Autowired
    private BMainActionReportsMapper reportsMapper;

    @Autowired
    private SRaActionReportsAuditResultMapper reportsAuditResultMapper;


    /**
     * 是否已经提交 执行报告 检测
     */
    public void isSubmitTask(){
        //查询审核通过的 时间范围内的 所有报告提交情况
        LambdaQueryWrapper<SRaActionReportsAuditRecord> queryWrapper = new QueryWrapper<SRaActionReportsAuditRecord>().lambda()
                //上月
                .between(SRaActionReportsAuditRecord::getAuditTime, DateUtil.getDayOfMonth(-1), DateUtil.getDayOfMonth(0))
                //审核通过
                .eq(SRaActionReportsAuditRecord::getAuditStatus, 9);
        List<SRaActionReportsAuditRecord> dataList = reportsAuditRecordMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(dataList)){
            log.info("根据关联分析系统的判断结果得出-执行报告规范审核定时任务 无分析内容");
            return;
        }
        List<String> reportIds = dataList.stream().map(SRaActionReportsAuditRecord::getReportId).distinct().collect(Collectors.toList());
        List<BMainActionReports> bMainActionReports = reportsMapper.selectList(new QueryWrapper<BMainActionReports>().lambda().in(BMainActionReports::getId, reportIds));
        if (CollectionUtil.isEmpty(bMainActionReports)){
            log.info("bMainActionReports is null; 根据关联分析系统的判断结果得出-执行报告规范审核定时任务 无分析内容");
            return;
        }
        //所有企业id
        Map<String, String> factoryMap = bMainActionReports.stream()
                .collect(Collectors.toMap(BMainActionReports::getId, BMainActionReports::getFactoryId));
        //企业id 与 标签code 映射map
        Map<String, String> factoryIdLabelMap = new HashMap<>();
        //判断 是否已经提交全部  应提交 > 已提交
        List<String> notSubmitReportIds = dataList.stream().filter(record -> record.getTotalEnterprises() > record.getSubmittedEnterprises())
                .map(SRaActionReportsAuditRecord::getReportId).collect(Collectors.toList());

        for (Map.Entry<String, String> entry : factoryMap.entrySet()) {
            String key = entry.getKey();
            if (notSubmitReportIds.contains(key)){
                //未提交
                factoryIdLabelMap.put(entry.getValue(),LabelValueEnum.CODE_JG004_1001.getArgumentsCode());
            }else{
                factoryIdLabelMap.put(entry.getValue(),LabelValueEnum.CODE_JG004_1002.getArgumentsCode());
            }
        }
        batchCreateLabelFactory(factoryIdLabelMap,LabelFactoryEnum.JG004.getEnumId());
    }

    /**
     * 是否规范提交
     */
    public void isSpecification(){
        //查询 时间范围内的 所有报告审核情况
        LambdaQueryWrapper<SRaActionReportsAuditResult> queryWrapper = new QueryWrapper<SRaActionReportsAuditResult>().lambda()
                //上月
                .between(SRaActionReportsAuditResult::getAuditTime, DateUtil.getDayOfMonth(-1), DateUtil.getDayOfMonth(0));
        List<SRaActionReportsAuditResult> dataList = reportsAuditResultMapper.selectList(queryWrapper);
        if (CollectionUtil.isEmpty(dataList)){
            log.info("根据关联分析系统的判断结果得出-执行报告规范审核定时任务 无分析内容");
            return;
        }
        List<String> factoryIds = dataList.stream().map(SRaActionReportsAuditResult::getFactoryId).collect(Collectors.toList());
        //审核不规范判断 TODO 暂时只用这三个 有调整后续加
        List<String> notSpecificationFactoryIds = dataList.stream()
                //污染防治设施异常情况汇总表 != null
                .filter(result -> StringUtils.isNotBlank(result.getPreventionFacilities()))
                //污染防治设施-异常情况汇总表 != null
                .filter(result -> StringUtils.isNotBlank(result.getAbnormalSituation()))
                //超标排放信息 ！= null
                .filter(result -> StringUtils.isNotBlank(result.getExcessiveEmissions()))
                .map(SRaActionReportsAuditResult::getFactoryId).collect(Collectors.toList());
        //企业id 与 标签code 映射map
        Map<String, String> factoryIdLabelMap = new HashMap<>();
        for (String factoryId : factoryIds) {
            String value = null;
            if (notSpecificationFactoryIds.contains(factoryId)){
                //不规范
                value = LabelValueEnum.CODE_JG005_1002.getArgumentsCode();
            }else{
                value = LabelValueEnum.CODE_JG005_1001.getArgumentsCode();
            }
            factoryIdLabelMap.put(factoryId,value);
        }
        batchCreateLabelFactory(factoryIdLabelMap,LabelFactoryEnum.JG005.getEnumId());
    }

    @Transactional(rollbackFor = Exception.class)
    public void batchCreateLabelFactory(Map<String, String> factoryIdLabelMap,String labelCode){
        PcLabel label = labelMapper.selectOne(
                new QueryWrapper<PcLabel>().lambda().eq(PcLabel::getLabelCode, labelCode)
        );
        ArrayList<PcLabelFactory> pcLabelFactories = new ArrayList<>();
        for (Map.Entry<String, String> entry : factoryIdLabelMap.entrySet()) {
            PcLabelFactory pcLabelFactory = buildPcLabelFactory(entry.getKey(), label.getId(), entry.getValue());
            pcLabelFactories.add(pcLabelFactory);
        }
        //查询对应企业 和 标签 是否存在 存在修改 不存在新增
        LambdaQueryWrapper<PcLabelFactory> wrapper = Wrappers.<PcLabelFactory>lambdaQuery()
                .in(PcLabelFactory::getFactoryId, pcLabelFactories.stream().map(PcLabelFactory::getFactoryId).collect(Collectors.toList()))
                .eq(PcLabelFactory::getLabelId, label.getId());
        //删除原本的对应标签 和 企业的 关联关系
        labelFactoryMapper.delete(wrapper);
        //重新添加新的企业 标签 关联关系
        if (CollectionUtil.isNotEmpty(pcLabelFactories)){
            labelFactoryMapper.batchSave(pcLabelFactories);
        }
    }

    /**
     * 构建企业标签关联关系实体
     */
    private PcLabelFactory buildPcLabelFactory(String factoryId, String labelId, String labelValue){
        PcLabelFactory pcLabelFactory = new PcLabelFactory();
        pcLabelFactory.setId(UUID.randomUUID().toString());
        pcLabelFactory.setFactoryId(factoryId);
        pcLabelFactory.setLabelId(labelId);
        pcLabelFactory.setLabelValue(labelValue);
        pcLabelFactory.setLableUseing("0");
        return pcLabelFactory;
    }

}
