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

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.BasControlValue;
import cn.cecep.talroad.domain.BasDeviceSalAnalysis;
import cn.cecep.talroad.domain.MonDevReal;
import cn.cecep.talroad.domain.analysis.SRaRealTimeAnalysisCo;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.enums.ReleaseStatusEnum;
import cn.cecep.talroad.service.IBasControlValueService;
import cn.cecep.talroad.service.IBasDeviceService;
import cn.cecep.talroad.service.IOdsAirRegionHourIService;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
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:10
 * @Class: GtGlmqAdapter
 * @Deseription:
 * @Version V1.0
 */
@Slf4j
@Service("GTGLMQ")
public class GtGlmqAdapter extends GtStatusStrategyAdapter {

    @Autowired
    private IOdsAirRegionHourIService odsAirRegionHourIService;
    @Autowired
    private IBasControlValueService basControlValueService;
    @Autowired
    private IBasDeviceService basDeviceService;
    @Autowired
    private RedisService redisService;

    private final static String GLMQ_START = "GT_GLMQ_START_";
    private final static String GLMQ_END = "GT_GLMQ_END_";

    @Override
    protected void doProcessGTStatus(String industry, String deviceType, List<MonDevReal> list,Date lastDate,Date tempDate) {

        List<BasDeviceSalAnalysis> deviceStatusList = new ArrayList<>();
        List<SRaRealTimeAnalysisCo> coList = new ArrayList<>();
        Map<String,BasDeviceSalAnalysis> salAnalysisMap = new HashMap<>();
        List<AmProblemFi> alarmList = new ArrayList<>();
        // 监测数据不为空
        if (list != null && list.size() > 0) {
            list.forEach(real -> {
                AtomicInteger m = new AtomicInteger();
                AtomicInteger n = new AtomicInteger();
                AtomicInteger t = new AtomicInteger();
                // 根据设备ID，查询企业名称、设备名称等信息
                FactoryDeviceVo vo = basDeviceService .selectFactoryDeviceVoByDeviceId(real.getDeviceId());
                if (StringUtils.isNotEmpty(real.getMq1())) {
                    m.getAndIncrement();
                    BasControlValue basControlValue = basControlValueService.selectByFactoryId(real.getFactoryId(),industry,deviceType);
                    if(basControlValue!=null){
                        if("2".equals(basControlValue.getNormalValue())) {
                            // 放散调节阀状态,开关量
                            if (Double.valueOf(real.getMq1()).compareTo(1.0)==0) {
                                n.getAndIncrement();
                            }
                        }else{
                            // 放散调节阀状态,开度
                            if (Double.valueOf(real.getMq1()).compareTo(5.0)==1) {
                                n.getAndIncrement();
                            }
                        }
                    }
                }
                if (StringUtils.isNotEmpty(real.getMq5())) {
                    // 温度
                    t.getAndIncrement();
                }
                if (StringUtils.isNotEmpty(real.getMq6())) {
                    m.getAndIncrement();
                    // 放散管流速
                    if (Double.valueOf(real.getMq6()).compareTo(3.0) >= 0) {
                        n.getAndIncrement();
                    }
                }
                if (m.get() == 0) {
                    //数据缺失，无法判断
                    StringBuffer sb = new StringBuffer();
                    sb.append("数据缺失，无法判断");
                    AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(), vo.getDeviceId(), vo.getDeviceName(), lastDate, real.getDataTime(), ProblemTypeEnum.SJQS, sb.toString(),"放散调节阀状态,放散温度,放散管流速","mq1,mq5,mq6");
                    alarmList.add(problemFi);
                } else {
                    // 处理放散状态
                    //满足两个条件就是放散，否则为未放散
                    if (n.get() > 0) {
                        if (t.get() > 0) {
                            String lastHour = DateUtils.parseDateToStr("yyyy-MM-dd HH:00:00",DateUtils.addHours(tempDate,-2));
                            BigDecimal avgTemp = odsAirRegionHourIService.selectAvgTemp(lastHour);
                            if(avgTemp!=null) {
                                if (BigDecimal.valueOf(Double.valueOf(real.getMq5())).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.getMq3())).divide(BigDecimal.valueOf(60),2, RoundingMode.HALF_UP);
                                    co.setCoalEmissions(emission);
                                    coList.add(co);

                                    String ycBegin = GLMQ_START+vo.getDeviceId();
                                    String ycEnd = GLMQ_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(), "放散调节阀状态,放散温度,放散管流速", "mq1,mq5,mq6");
                                            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.getMq3())).divide(BigDecimal.valueOf(60),2, RoundingMode.HALF_UP);
                                    co.setCoalEmissions(emission);
                                    coList.add(co);
                                    // 煤气管网
                                    String ycBegin = GLMQ_START+vo.getDeviceId();
                                    String ycEnd = GLMQ_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);
        }
    }
}
