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

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.PcOutlet;
import cn.cecep.talroad.domain.SMainDynamicControlFactory;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.mapper.*;
import cn.cecep.talroad.service.IAmProblemFiService;
import cn.cecep.talroad.util.NumberUtils;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
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.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author hehongyu
 * @description: 污染源管控任务
 * @date 2023/6/28 22:28
 * 逻辑描述：1.查询 s_main_dynamic_control_factory 企业传输率  判断 实测是否 > 标准
 *          大于则产生预警信息
 */
@Slf4j
@Service
public class PollutionSourceControlService {


    @Autowired
    private SMainDynamicControlFactoryMapper dynamicControlFactoryMapper;
    @Autowired
    private PcOutletMapper pcOutletMapper;
    @Autowired
    private IAmProblemFiService amProblemFiService;

    protected static final int PAGE_SIZE = 1000;

    public void invoke(){
        //分页处理查询企业传输率
        Page<SMainDynamicControlFactory> page = new Page<>(1, PAGE_SIZE);
        do {
            page = dynamicControlFactoryMapper.selectPage(page, new QueryWrapper<>());
            List<SMainDynamicControlFactory> records = page.getRecords();
            if (CollectionUtil.isEmpty(records)){
                break;
            }
            //排口名称
            List<String> outletIds = records.stream().map(SMainDynamicControlFactory::getOutletId).collect(Collectors.toList());
            List<PcOutlet> pcOutlets = pcOutletMapper.selectList(new QueryWrapper<PcOutlet>().lambda().in(PcOutlet::getId, outletIds));
            Map<String, String> outletNameMap = pcOutlets.stream().collect(Collectors.toMap(PcOutlet::getId, PcOutlet::getOutletName));
            List<AmProblemFi> amProblemFis = new ArrayList<>();
            for (SMainDynamicControlFactory record : records) {
                //实测值
                BigDecimal measuredValue = NumberUtils.getBigDecimalDefaultNull(record.getMeasuredValue());
                //验收标准值
                BigDecimal standardValue = NumberUtils.getBigDecimalDefaultNull(record.getStandardValue());
                if (measuredValue == null || standardValue == null){
                    continue;
                }
                if (measuredValue.compareTo(standardValue) > 0){
                    //添加预警信息
                    String msg = buildMsg(record.getArgumentsName(),record.getMeasuredValue(),record.getStandardValue());
                    AmProblemFi amProblemFi = doProcessAlaram(record.getFactoryId(), record.getOutletId(), outletNameMap.get(record.getOutletId()), msg, record.getArgumentsName());
                    amProblemFis.add(amProblemFi);
                }
            }
            amProblemFiService.saveBatch(amProblemFis);
        }while (page.getPages() < page.getCurrent());
    }

    /**
     * 设备名称（监控参数名称）当前为（当前的监控数值），超过标准值（备案具体数值），请及时核对
     */
    private String buildMsg(String paramName,String measuredValue,String standardValue){
        return "设备名称（"+paramName+"）当前为（"+measuredValue+"），超过标准值（"+standardValue+"），请及时核对";
    }
    /**
     * 构建报警信息实体
     */
    private AmProblemFi doProcessAlaram(String factoryId, String stationId, String stationName, String msg, String param) {
        AmProblemFi problemFi = new AmProblemFi();
        problemFi.setId(IdUtil.simpleUUID());
        problemFi.setProblemSources("3");
        problemFi.setFactoryId(factoryId);
        problemFi.setProblemDetails(msg);
        problemFi.setType(1);
        problemFi.setProblemType(ProblemTypeEnum.POLLUTION_CONTROL_EXCEEDED.getCode());
        problemFi.setProblemTreatmentState("1");
        problemFi.setAnalyseTime(new Date());
        problemFi.setAnalyseTimeEnd(new Date());
        problemFi.setStationId(stationId);
        problemFi.setStationName(stationName);
        problemFi.setCreateTime(new Date());
        problemFi.setParamName(param);
        problemFi.setInputStartTime(DateUtils.dateTime());
        problemFi.setInputEndTime(DateUtils.dateTime());
        return problemFi;
    }

}
