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

import cn.cecep.talroad.domain.BMainEmissionPollutionAir;
import cn.cecep.talroad.domain.PcLabel;
import cn.cecep.talroad.domain.PcLabelFactory;
import cn.cecep.talroad.enums.LabelFactoryEnum;
import cn.cecep.talroad.enums.LabelValueEnum;
import cn.cecep.talroad.mapper.BMainEmissionPollutionAirMapper;
import cn.cecep.talroad.mapper.PcLabelFactoryMapper;
import cn.cecep.talroad.mapper.PcLabelMapper;
import cn.cecep.talroad.util.NumberUtils;
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.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author hehongyu
 * @description: 废气排放 超总量 标签任务
 * @date 2023/6/28 23:58
 * 逻辑描述：1.获取 b_main_emission_pollution_air的数据 判断
 *            SO2 、NOx  、颗粒物（烟尘）、VOC 四个类型的污染物 是否实际大于许可
 *            有一个大于 则 判断该企业 超标
 *          2. 将 企业id 和标签id 查询 删除原有关系 维护新关系
 */
@Slf4j
@Service
public class GasExceededTotalLabelTaskService {
    @Autowired
    private BMainEmissionPollutionAirMapper mapper;

    @Autowired
    private PcLabelFactoryMapper labelFactoryMapper;

    @Autowired
    private PcLabelMapper labelMapper;

    public void invoke() {
        Calendar instance = Calendar.getInstance();
        int year = instance.get(Calendar.YEAR);
        LambdaQueryWrapper<BMainEmissionPollutionAir> wrapper = new QueryWrapper<BMainEmissionPollutionAir>().lambda()
                .eq(BMainEmissionPollutionAir::getPollYear, String.valueOf(year - 1));
        List<BMainEmissionPollutionAir> bMainEmissionPollutionAirs = mapper.selectList(wrapper);
        PcLabel label = labelMapper.selectOne(
                new QueryWrapper<PcLabel>().lambda().eq(PcLabel::getLabelCode, LabelFactoryEnum.PF019.getEnumId())
        );
        List<PcLabelFactory> pcLabelFactoryList = new ArrayList<>();
        for (BMainEmissionPollutionAir entity : bMainEmissionPollutionAirs) {
            ArrayList<LabelValueEnum> labelValueEnums = new ArrayList<>();
            //sj = 实际  ， xk = 许可 , cb = 超标
            //SO₂
            BigDecimal sjSo2 = NumberUtils.getBigDecimalDefaultZero(entity.getActuallyEmittingSo2());
            BigDecimal xkSo2 = NumberUtils.getBigDecimalDefaultZero(entity.getAllowableEmissionSo2());
            BigDecimal cbSo2 = entity.getExceedingRateSo2();
            labelValueEnums.add(judgementCb(sjSo2, xkSo2, cbSo2));
            //NOx
            BigDecimal sjNox = NumberUtils.getBigDecimalDefaultZero(entity.getActuallyEmittingNox());
            BigDecimal xkNox = NumberUtils.getBigDecimalDefaultZero(entity.getAllowableEmissionNox());
            BigDecimal cbNox = entity.getExceedingRateNox();
            labelValueEnums.add(judgementCb(sjNox, xkNox, cbNox));
            //颗粒物
            BigDecimal sjPm = NumberUtils.getBigDecimalDefaultZero(entity.getActuallyEmittingPm());
            BigDecimal xkPm = NumberUtils.getBigDecimalDefaultZero(entity.getAllowableEmissionPm());
            BigDecimal cbPm = entity.getExceedingRatePm();
            labelValueEnums.add(judgementCb(sjPm, xkPm, cbPm));
            //Vocs
            BigDecimal sjVocs = NumberUtils.getBigDecimalDefaultZero(entity.getActuallyEmittingVocs());
            BigDecimal xkVocs = NumberUtils.getBigDecimalDefaultZero(entity.getAllowableEmissionVocs());
            BigDecimal cbVocs = entity.getExceedingRateVocs();
            labelValueEnums.add(judgementCb(sjVocs, xkVocs, cbVocs));
            //判断四个污染物的超标 枚举
            PcLabelFactory pcLabelFactory = null;
            if (labelValueEnums.contains(LabelValueEnum.CODE_1048)){
                //包含超标 即为超标
                pcLabelFactory = buildPcLabelFactory(entity.getFactoryId(), label.getId(), LabelValueEnum.CODE_1048);
            }else{
                pcLabelFactory = buildPcLabelFactory(entity.getFactoryId(), label.getId(), LabelValueEnum.CODE_1049);
            }
            //构建标签信息
            pcLabelFactoryList.add(pcLabelFactory);
            break;
        }
        if (CollectionUtil.isEmpty(pcLabelFactoryList)){
            return;
        }
        //查询对应企业 和 标签 是否存在 存在修改 不存在新增
        LambdaQueryWrapper<PcLabelFactory> labelWrapper = Wrappers.<PcLabelFactory>lambdaQuery()
                .in(PcLabelFactory::getFactoryId, pcLabelFactoryList.stream().map(PcLabelFactory::getFactoryId).collect(Collectors.toList()))
                .eq(PcLabelFactory::getLabelId, label.getId());
        //删除原本的对应标签 和 企业的 关联关系
        labelFactoryMapper.delete(labelWrapper);
        //重新添加新的企业 标签 关联关系
        if (CollectionUtil.isNotEmpty(pcLabelFactoryList)){
            labelFactoryMapper.batchSave(pcLabelFactoryList);
        }

    }


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

    public LabelValueEnum judgementCb(BigDecimal sj, BigDecimal xk,BigDecimal cb){
        BigDecimal cbValue = getExceedValue(xk, cb);
        return judgingTheIndexOfExcess(cbValue, sj);
    }
    /**
     * 获取超标值
     */
    public BigDecimal getExceedValue(BigDecimal xk, BigDecimal cb){
        //(许可值 * 超标百分比 ) + 许可值  即为超标临界值
        return xk.multiply(cb).add(xk);
    }

    /**
     * 判断是否超总量
     */
    public static LabelValueEnum judgingTheIndexOfExcess(BigDecimal cb, BigDecimal sj){
        //超标值 - 实际值 > 0 代表不超总量
        if (cb.subtract(sj).compareTo(BigDecimal.ZERO) > 0){
            return LabelValueEnum.CODE_1049;
        }
        return LabelValueEnum.CODE_1048;
    }
}