package cn.cecep.talroad.service.strategy.support.jh;

import cn.cecep.talroad.common.core.utils.DateUtils;
import cn.cecep.talroad.common.core.utils.StringUtils;
import cn.cecep.talroad.common.redis.service.RedisService;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.BasDeviceSalAnalysis;
import cn.cecep.talroad.domain.MonDevJhReal;
import cn.cecep.talroad.domain.analysis.SRaRealTimeAnalysisCo;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.enums.ReleaseStatusEnum;
import cn.cecep.talroad.service.IBasDeviceParamService;
import cn.cecep.talroad.service.IBasDeviceService;
import cn.cecep.talroad.service.IMonDevJhRealService;
import cn.cecep.talroad.service.IOdsAirRegionHourIService;
import cn.cecep.talroad.service.strategy.StatusStrategyAdapter;
import cn.cecep.talroad.vo.BasDeviceParamVo;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: cjh
 * @Date: 2023-03-25 16:29
 * @Class: JlmqAdapter
 * @Deseription:
 * @Version V1.0
 */
@Slf4j
@Service("JHMQGW")
public class JhMqgwAdapter extends StatusStrategyAdapter {

    @Autowired
    private IOdsAirRegionHourIService odsAirRegionHourIService;
    @Autowired
    private IBasDeviceService basDeviceService;
    @Autowired
    private IMonDevJhRealService monDevJhRealService;
    @Autowired
    private RedisService redisService;
    private final static String JHMQ_START = "JH_MQGW_START_";
    private final static String JHMQ_END = "JH_MQGW_END_";

    @Override
    protected void doProcessStatus(String industry, String deviceType,Date curr) {
        List<BasDeviceSalAnalysis> deviceStatusList = new ArrayList<>();
        List<SRaRealTimeAnalysisCo> coList = new ArrayList<>();
        List<AmProblemFi> alarmList = new ArrayList<>();
        Map<String,BasDeviceSalAnalysis> salAnalysisMap = new HashMap<>();

        Date lastDate = DateUtils.addMinutes(curr,-10);
        // 查询该设备最新监测数据
        List<MonDevJhReal> realList = monDevJhRealService.selectLatestByParams(industry,deviceType,lastDate,curr);
        if(realList!=null&&realList.size()>0){
            realList.forEach(real->{
                AtomicInteger n = new AtomicInteger();
                AtomicInteger t = new AtomicInteger();
                // 根据设备ID，查询企业名称、设备名称等信息
                FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(real.getDeviceId());
                if (StringUtils.isNotEmpty(real.getJs202())) {
                    // 放散流速
                    if (Double.valueOf(real.getJs202()).compareTo(3.0) >= 0) {
                        n.getAndIncrement();
                    }
                }
                if (StringUtils.isNotEmpty(real.getJs201())) {
                    // 放散温度
                    t.getAndIncrement();
                }

                if (StringUtils.isEmpty(real.getJs201()) && StringUtils.isEmpty(real.getJs202())) {
                    StringBuffer sb = new StringBuffer();
                    sb.append("数据缺失，无法判断");
                    AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(), vo.getDeviceId(), vo.getDeviceName(), lastDate, curr, ProblemTypeEnum.SJQS, sb.toString(),"放散温度,放散流速","js201,js202");
                    alarmList.add(problemFi);
                } else {
                    // 满足一个条件为放散
                    if (n.get() > 0) {
                        // 放散
                        if (t.get() > 0) {
                            String lastDateTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(curr,-2));
                            BigDecimal avgTemp = odsAirRegionHourIService.selectAvgTemp(lastDateTime);
                            if(BigDecimal.valueOf(Double.valueOf(real.getJs201())).subtract(avgTemp).compareTo(new BigDecimal(10))>0) {
                                BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(), vo.getDeviceId(), "", ReleaseStatusEnum.NORMAL.getName());
                                deviceStatusList.add(basStatus);
                                SRaRealTimeAnalysisCo co = super.doProcessAnalysisCoData(vo, real.getDataTime(), real.getDataTime(), ReleaseStatusEnum.NORMAL);
                                BigDecimal emission = BigDecimal.valueOf(Double.valueOf(real.getG979())).divide(BigDecimal.valueOf(60),2, RoundingMode.HALF_UP);
                                co.setCoalEmissions(emission);
                                coList.add(co);
                                // 煤气管网
                                String ycBegin = JHMQ_START+vo.getDeviceId();
                                String ycEnd = JHMQ_END+vo.getDeviceId();
                                // 异常放散开始日期
                                String stDate = redisService.getCacheObject(ycBegin);
                                // 异常放散结束日期
                                String stEnd = redisService.getCacheObject(ycEnd);
                                if(StringUtils.isNotEmpty(stDate)) {
                                    stEnd = StringUtils.isEmpty(stEnd)?stDate:stEnd;
                                    StringBuffer sb = new StringBuffer();
                                    sb.append(vo.getDeviceName()).append("于").append(stDate).append("-")
                                        .append(stEnd).append("存在CO异常放散情况。");
                                    if(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",stDate).compareTo(DateUtils.dateTime("yyyy-MM-dd HH:mm:ss",stEnd))<=0) {
                                        AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(), vo.getDeviceId(), vo.getDeviceName(), DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", stDate),
                                            DateUtils.dateTime("yyyy-MM-dd HH:mm:ss", stEnd), ProblemTypeEnum.RELEASE,
                                            sb.toString(), "放散温度,放散流速", "js201,js202");
                                        alarmList.add(problemFi);
                                    }
                                    redisService.deleteObject(ycBegin);
                                    redisService.deleteObject(ycEnd);
                                }
                            } else {
                                BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(),vo.getDeviceId(), "",ReleaseStatusEnum.ERROR.getName());
                                deviceStatusList.add(basStatus);
                                SRaRealTimeAnalysisCo co = super.doProcessAnalysisCoData(vo, real.getDataTime(),real.getDataTime(),ReleaseStatusEnum.ERROR);
                                BigDecimal emission = BigDecimal.valueOf(Double.valueOf(real.getG979())).divide(BigDecimal.valueOf(60),2, RoundingMode.HALF_UP);
                                co.setCoalEmissions(emission);
                                coList.add(co);
                                // 煤气管网
                                String ycBegin = JHMQ_START+vo.getDeviceId();
                                String ycEnd = JHMQ_END+vo.getDeviceId();
                                // 异常放散开始日期
                                String stDate = redisService.getCacheObject(ycBegin);
                                if(StringUtils.isEmpty(stDate)){
                                    //设置缓存
                                    redisService.setCacheObject(ycBegin,DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",real.getDataTime()));
                                    redisService.setCacheObject(ycEnd,DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",real.getDataTime()));
                                }else {
                                    redisService.setCacheObject(ycEnd,DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",real.getDataTime()));
                                }
                            }
                        } else {
                            BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(),vo.getDeviceId(), "",ReleaseStatusEnum.YC.getName());
                            deviceStatusList.add(basStatus);
                            SRaRealTimeAnalysisCo co = super.doProcessAnalysisCoData(vo, real.getDataTime(),real.getDataTime(),ReleaseStatusEnum.YC);
                            coList.add(co);
                        }
                    } else {
                        SRaRealTimeAnalysisCo co = super.doProcessAnalysisCoData(vo, real.getDataTime(), real.getDataTime(), ReleaseStatusEnum.UNREAL);
                        coList.add(co);
                        BasDeviceSalAnalysis oldSal = salAnalysisMap.get(vo.getDeviceId());
                        if(oldSal==null) {
                            BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(),vo.getDeviceId(), "", ReleaseStatusEnum.UNREAL.getName());
                            salAnalysisMap.put(vo.getDeviceId(),basStatus);
                            deviceStatusList.add(basStatus);
                        }
                    }
                }
            });
            // 批量处理
            super.doSaveBatchSRaRealTimeAnalysisCo(coList);
            super.doSaveOrUpdateBatchDeviceStatus(deviceStatusList);
            super.doSaveBatchAlarm(alarmList);
        }
    }

}
