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

import cn.cecep.talroad.domain.BStatTableZxbgWrzlAbnormalities;
import cn.cecep.talroad.domain.BStatTableZxbgWrzlTotal;
import cn.cecep.talroad.domain.analysis.SRaActionReportsAuditResult;
import cn.cecep.talroad.mapper.BStatTableZxbgWrzlAbnormalitiesMapper;
import cn.cecep.talroad.mapper.BStatTableZxbgWrzlTotalMapper;
import cn.cecep.talroad.mapper.analysis.SRaActionReportsAuditResultMapper;
import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
@Slf4j
public class PollutionPreventionAndControlFacilitiesServiceImpl implements PollutionPreventionAndControlFacilitiesService {

    private final BStatTableZxbgWrzlTotalMapper bStatTableZxbgWrzlTotalMapper;

    private final SRaActionReportsAuditResultMapper sRaActionReportsAuditResultMapper;

    private final BStatTableZxbgWrzlAbnormalitiesMapper bStatTableZxbgWrzlAbnormalitiesMapper;

    private final Integer pageSize = 10;

    private List<BStatTableZxbgWrzlTotal> queryTotalData(String pollutant, String period, String type, List<String> factoryIds) {
        List<BStatTableZxbgWrzlTotal> sRaActionReportsAuditResultList = bStatTableZxbgWrzlTotalMapper.selectByPeriodAndTypeAndRecords(pollutant, period, type, factoryIds);
        log.info("查询出污染治理设施正常情况汇总基本信息表数据:{}", sRaActionReportsAuditResultList);
        return sRaActionReportsAuditResultList;
    }

    private List<BStatTableZxbgWrzlAbnormalities> queryAbnormalitiesData(String period, String type, List<String> factoryIdList) {
        List<BStatTableZxbgWrzlAbnormalities> bStatTableZxbgWrzlAbnormalities = bStatTableZxbgWrzlAbnormalitiesMapper.queryAbnormalitiesData(period, type, factoryIdList);
        log.info("查询出污染防治设施异常情况汇总表数据:{}", bStatTableZxbgWrzlAbnormalities);
        return bStatTableZxbgWrzlAbnormalities;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void normalSewageProcess() {

        String period = LocalDate.now().toString().substring(0, 4);
        List<SRaActionReportsAuditResult> actionReportsAuditResults = Lists.newArrayList();

        SRaActionReportsAuditResult queryResult = new SRaActionReportsAuditResult();
        queryResult.setReportTime(period);
        List<SRaActionReportsAuditResult> queryActionReportsAuditResults = sRaActionReportsAuditResultMapper.selectSRaActionReportsAuditResultList(queryResult);
        List<String> factoryIdList = queryActionReportsAuditResults.stream().map(SRaActionReportsAuditResult::getFactoryId).collect(Collectors.toList());
        List<BStatTableZxbgWrzlTotal> dataList = queryTotalData("废水", period, "2", factoryIdList);
        //插入对应的提示
        for (SRaActionReportsAuditResult queryActionReportsAuditResult : queryActionReportsAuditResults) {
            updateActionReportsAuditResultByTotal(dataList, actionReportsAuditResults, queryActionReportsAuditResult);
        }
        if (CollUtil.isNotEmpty(actionReportsAuditResults)) {
            List<List<SRaActionReportsAuditResult>> partition = ListUtils.partition(actionReportsAuditResults, 10);
            for (List<SRaActionReportsAuditResult> sRaActionReportsAuditResultList : partition) {
                sRaActionReportsAuditResultMapper.batchUpdate(sRaActionReportsAuditResultList);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void abnormalCircumstanceProcess() {
        String period = LocalDate.now().toString().substring(0, 4);
        List<SRaActionReportsAuditResult> actionReportsAuditResults = Lists.newArrayList();
        SRaActionReportsAuditResult queryResult = new SRaActionReportsAuditResult();
        queryResult.setReportTime(period);
        List<SRaActionReportsAuditResult> queryActionReportsAuditResults = sRaActionReportsAuditResultMapper.selectSRaActionReportsAuditResultList(queryResult);
        List<String> factoryIdList = queryActionReportsAuditResults.stream().map(SRaActionReportsAuditResult::getFactoryId).collect(Collectors.toList());

        List<BStatTableZxbgWrzlAbnormalities> abnormalities = queryAbnormalitiesData(period, "2", factoryIdList);
        //插入对应的提示
        for (SRaActionReportsAuditResult queryActionReportsAuditResult : queryActionReportsAuditResults) {
            updateActionReportsAuditResultByAbnormalities(abnormalities, actionReportsAuditResults, queryActionReportsAuditResult);
        }
        if (CollUtil.isNotEmpty(actionReportsAuditResults)) {
            List<List<SRaActionReportsAuditResult>> partition = ListUtils.partition(actionReportsAuditResults, 10);
            for (List<SRaActionReportsAuditResult> sRaActionReportsAuditResultList : partition) {
                sRaActionReportsAuditResultMapper.batchUpdate(sRaActionReportsAuditResultList);
            }
        }
    }

    private void updateActionReportsAuditResultByAbnormalities(List<BStatTableZxbgWrzlAbnormalities> abnormalities, List<SRaActionReportsAuditResult> actionReportsAuditResults, SRaActionReportsAuditResult queryActionReportsAuditResult) {
        //todo 添加对应字段判断 shareReportGovernInfo表中的summary中包括关键词“不存在”“未发现”“未”“没有”“均正常”“无”“无异常”“全年停产”之一
        String factoryId = queryActionReportsAuditResult.getFactoryId();
        List<BStatTableZxbgWrzlAbnormalities> filteredList = abnormalities.stream()
                .filter(item -> item.getFactoryId().equals(factoryId))
                .collect(Collectors.toList());
        //企业对应的运行设施的数据
        if (CollUtil.isEmpty(filteredList)) {
            SRaActionReportsAuditResult sRaActionReportsAuditResult = new SRaActionReportsAuditResult();
            sRaActionReportsAuditResult.setId(queryActionReportsAuditResult.getId());
            sRaActionReportsAuditResult.setAbnormalSituation("未填报污染防治设施异常情况汇总表");
            actionReportsAuditResults.add(sRaActionReportsAuditResult);
        }
    }

    private void updateActionReportsAuditResultByTotal(List<BStatTableZxbgWrzlTotal> list, List<SRaActionReportsAuditResult> actionReportsAuditResults, SRaActionReportsAuditResult queryActionReportsAuditResult) {
        StringBuilder allMessage = new StringBuilder();
        String factoryId = queryActionReportsAuditResult.getFactoryId();
        List<BStatTableZxbgWrzlTotal> filteredList = list.stream()
                .filter(item -> item.getFactoryId().equals(factoryId))
                .collect(Collectors.toList());
        //企业对应的运行设施的数据
        if (CollUtil.isNotEmpty(filteredList)) {
            Map<String, List<BStatTableZxbgWrzlTotal>> factoryMap = filteredList.stream()
                    .collect(Collectors.groupingBy(BStatTableZxbgWrzlTotal::getPollutionControlFacilityCode));
            //循环每个运行设施
            for (Map.Entry<String, List<BStatTableZxbgWrzlTotal>> entry : factoryMap.entrySet()) {
                List<BStatTableZxbgWrzlTotal> value = entry.getValue();
                if (CollUtil.isNotEmpty(value)) {
                    BStatTableZxbgWrzlTotal bStatTableZxbgWrzlTotal = value.get(0);
                    StringBuilder message = new StringBuilder();
                    //当前设备其中一个备注包含停产跳过
                    String pollutionControlFacilityCode = bStatTableZxbgWrzlTotal.getPollutionControlFacilityCode();
                    String pollutionControlFacilityName = bStatTableZxbgWrzlTotal.getPollutionControlFacilityName();
                    if (value.stream().anyMatch(item -> item.getRemark() != null && item.getRemark().contains("停产"))) {
                        continue;
                    }
                    String contentIsNotFilled = this.isContentIsNotFilled(value);
                    if (StringUtils.isNotEmpty(contentIsNotFilled)) {
                        log.info("企业ID:{},提示语句:{}", factoryId, "废水污染治理设施正常运转情况表存在问题。");
                        message.append("污染治理设施编号：" + pollutionControlFacilityCode + "污染治理设施名称：" + pollutionControlFacilityName + "," + contentIsNotFilled);
                        allMessage.append(message);
                        allMessage.append(";");
                        continue;
                    }
                    if (theTimingIsIrregular(value)) {
                        log.info("企业ID:{},提示语句:{}", factoryId, "运行时间超过8760小时不规范。");
                        message.append("污染治理设施编号" + pollutionControlFacilityCode + "污染治理设施名称" + pollutionControlFacilityName + ",运行时间超过8760小时不规范");
                        allMessage.append(message);
                        allMessage.append(";");
                        continue;
                    }
                    if (efficiencyIsNotStandardized(value)) {
                        log.info("企业ID:{},提示语句:{}", factoryId, "污染物处理效率高于100%。");
                        message.append("污染治理设施编号" + pollutionControlFacilityCode + "污染治理设施名称" + pollutionControlFacilityName + ",污染物处理效率高于100%");
                        allMessage.append(message);
                        allMessage.append(";");
                        continue;
                    }
                }
            }

        } else {
            allMessage.append("未填报废水污染治理设施正常运转情况表。");
        }
        SRaActionReportsAuditResult sRaActionReportsAuditResult = new SRaActionReportsAuditResult();
        sRaActionReportsAuditResult.setId(queryActionReportsAuditResult.getId());
        sRaActionReportsAuditResult.setWaterPreventionFacilities(allMessage.toString());
        actionReportsAuditResults.add(sRaActionReportsAuditResult);
    }

    private boolean efficiencyIsNotStandardized(List<BStatTableZxbgWrzlTotal> value) {
        for (BStatTableZxbgWrzlTotal bStatTableZxbgWrzlTotal : value) {
            if (bStatTableZxbgWrzlTotal.getProcessParameter().contains("处理效率")) {
                if (Integer.parseInt(bStatTableZxbgWrzlTotal.getAmount()) > 100) {
                    return true;
                }
            }
        }
        return false;
    }

    private boolean theTimingIsIrregular(List<BStatTableZxbgWrzlTotal> value) {
        for (BStatTableZxbgWrzlTotal bStatTableZxbgWrzlTotal : value) {
            if (bStatTableZxbgWrzlTotal.getProcessParameter().contains("运行时间")) {
                if (Integer.parseInt(bStatTableZxbgWrzlTotal.getAmount()) > 8760) {
                    return true;
                }
            }
        }
        return false;
    }


    private String isContentIsNotFilled(List<BStatTableZxbgWrzlTotal> value) {
        //todo 运行参数 可能需要修改
        for (BStatTableZxbgWrzlTotal bStatTableZxbgWrzlTotal : value) {
            String processParameter = bStatTableZxbgWrzlTotal.getProcessParameter();
            String amount = bStatTableZxbgWrzlTotal.getAmount();
            if (processParameter.contains("运行时间")
                    || processParameter.contains("污水处理量")
                    || processParameter.contains("药剂使用量")) {
                if (StringUtils.isEmpty(amount) || amount.equals("/")) {
                    return processParameter + "内容未填报";
                }
            }
        }
        return null;
    }
}
