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.core.utils.bean.BeanUtils;
import cn.cecep.talroad.common.core.web.domain.AjaxResult;
import cn.cecep.talroad.domain.AmProblemFi;
import cn.cecep.talroad.domain.BasDevice;
import cn.cecep.talroad.domain.BasDeviceParam;
import cn.cecep.talroad.domain.BasDeviceSalAnalysis;
import cn.cecep.talroad.domain.BasParam;
import cn.cecep.talroad.domain.MonDevReal;
import cn.cecep.talroad.domain.PcFactory;
import cn.cecep.talroad.domain.SRaRealTimeAnalysisRunOne;
import cn.cecep.talroad.domain.analysis.SRaRealTimeAnalysisRun;
import cn.cecep.talroad.enums.DeviceStatusEnum;
import cn.cecep.talroad.enums.JudgeEnum;
import cn.cecep.talroad.enums.ProblemTypeEnum;
import cn.cecep.talroad.service.IBasDeviceParamService;
import cn.cecep.talroad.service.IBasDeviceService;
import cn.cecep.talroad.service.IBasParamService;
import cn.cecep.talroad.service.IMonDevRealService;
import cn.cecep.talroad.service.strategy.AbstractStrategyAdapter;
import cn.cecep.talroad.util.MathUtils;
import cn.cecep.talroad.vo.BasDeviceParamVo;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
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:04
 * @Class: GtSlAdapter
 * @Deseription:
 * @Version V1.0
 */
@Slf4j
@Service("GTSL")
public class GtSlAdapter extends GtStatusStrategyAdapter {

    @Autowired
    private IBasDeviceParamService basDeviceParamService;
    @Autowired
    private IBasDeviceService basDeviceService;

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

        List<BasDeviceSalAnalysis> deviceStatusList = new ArrayList<>();
        List<SRaRealTimeAnalysisRun> runList = new ArrayList<>();
        List<SRaRealTimeAnalysisRunOne> runOneList = new ArrayList<>();
        List<AmProblemFi> alarmList = new ArrayList<>();
        // 监测数据不为空
        if (list != null && list.size() > 0) {
            list.forEach(real -> {
                AtomicInteger m = new AtomicInteger();
                AtomicInteger n = new AtomicInteger();
                // 查询设备参数
                List<BasDeviceParamVo> paramsList = basDeviceParamService.selectBasDeviceParamByCondition(real.getDeviceId(),Arrays.asList("p1", "p2", "g604","g921", "o2Out"));
                // 设备参数不为空
                if (paramsList != null && paramsList.size() > 0) {
                    if (StringUtils.isNotEmpty(real.getP3())) {
                        // 摆头皮带运行信号
                        m.getAndIncrement();
                        if (Double.valueOf(real.getP3()).compareTo(0.0)==0) {
                            n.getAndIncrement();
                        }
                    }
                    if (StringUtils.isNotEmpty(real.getO2Out())) {
                        // 含氧量(出口)
                        m.getAndIncrement();
                        if (Double.valueOf(real.getO2Out()).compareTo(0.0)==0
                            || Double.valueOf(real.getO2Out()).compareTo(20.0)>=0) {
                            n.getAndIncrement();
                        }
                    }

                    // 根据设备ID，查询企业名称、设备名称等信息
                    FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(real.getDeviceId());
                    SRaRealTimeAnalysisRunOne oldDeviceStatus = super.getOldDeviceStatus(vo.getFactoryId(),vo.getDeviceId());
                    paramsList.forEach(p -> {
                        if (p != null) {
                            if ("p1".equalsIgnoreCase(p.getParamCodeSvc()) && StringUtils.isNotEmpty(real.getP1())) {
                                // 主抽风机电流
                                m.getAndIncrement();
                                if (Double.valueOf(real.getP1()) <= p.getNormalValue().multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP).doubleValue()) {
                                    n.getAndIncrement();
                                }
                            } else if ("p2".equalsIgnoreCase(p.getParamCodeSvc()) && StringUtils.isNotEmpty(real.getP2())) {
                                // 梭车布料器下料量
                                m.getAndIncrement();
                                if (Double.valueOf(real.getP2()) <= p.getNormalValue().multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP).doubleValue()) {
                                    n.getAndIncrement();
                                }
                            } else if ("g921".equalsIgnoreCase(p.getParamCodeSvc()) && StringUtils.isNotEmpty(real.getG921())) {
                                // 燃料（煤气） 流量
                                m.getAndIncrement();
                                if (Double.valueOf(real.getG921()) <= p.getNormalValue().multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP).doubleValue()) {
                                    n.getAndIncrement();
                                }
                            }
                        }
                    });
                    //数据缺失2种以上
                    if (m.get()>=2) {
                        // false为大于66%
                        if (!MathUtils.divideSjj(n.get(), m.get())) {
                            //停产条件比例占比超过66%，设备停机
                            SRaRealTimeAnalysisRun run = super.doProcessDeviceRunStatus(vo,lastDate,tempDate,oldDeviceStatus, DeviceStatusEnum.STOP, JudgeEnum.GKSJ);
                            runList.add(run);
                            if(oldDeviceStatus!=null) {
                                String oneId = "";
                                if(StringUtils.isNotEmpty(oldDeviceStatus.getDataId())) {
                                    oneId = oldDeviceStatus.getDataId();
                                }
                                BeanUtils.copyProperties(run, oldDeviceStatus);
                                oldDeviceStatus.setDataId(oneId);
                                oldDeviceStatus.setIndustryPermissionName(vo.getIndustryPermissionName());
                                runOneList.add(oldDeviceStatus);
                            }
                            BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(),vo.getDeviceId(),DeviceStatusEnum.STOP.getValue(),"");
                            deviceStatusList.add(basStatus);
                            if(DeviceStatusEnum.STOP_RUN.getCode().equals(run.getOperationStatus())||DeviceStatusEnum.RUN_STOP.getCode().equals(run.getOperationStatus())) {
                                String runEtc = super.getRunEtc(lastDate, tempDate, "");
                                StringBuffer sb = new StringBuffer();
                                sb.append(vo.getFactoryName()).append(vo.getDeviceName())
                                    .append("于").append(runEtc).append("存在启停行为，请注意。");
                                AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(),vo.getDeviceId(),  vo.getDeviceName(), tempDate,new Date(), ProblemTypeEnum.STOP_RUN,sb.toString(),"主抽风机电流,梭车布料器下料量,摆头皮带运行信号,燃料（煤气） 流量,含氧量(出口)","p1,p2,p3,g921,o2Out");
                                alarmList.add(problemFi);
                            }
                        } else {
                            //停产条件比例占比未超过66%，设备未停机
                            SRaRealTimeAnalysisRun run = super.doProcessDeviceRunStatus(vo,lastDate,tempDate,oldDeviceStatus, DeviceStatusEnum.RUN, JudgeEnum.GKSJ);
                            runList.add(run);
                            if(oldDeviceStatus!=null) {
                                String oneId = "";
                                if(StringUtils.isNotEmpty(oldDeviceStatus.getDataId())) {
                                    oneId = oldDeviceStatus.getDataId();
                                }
                                BeanUtils.copyProperties(run, oldDeviceStatus);
                                oldDeviceStatus.setDataId(oneId);
                                oldDeviceStatus.setIndustryPermissionName(vo.getIndustryPermissionName());
                                runOneList.add(oldDeviceStatus);
                            }
                            BasDeviceSalAnalysis basStatus = super.doProcessDeviceAnalysisStatus(vo.getFactoryId(),vo.getDeviceId(),DeviceStatusEnum.RUN.getValue(),"");
                            deviceStatusList.add(basStatus);
                            if(DeviceStatusEnum.STOP_RUN.getCode().equals(run.getOperationStatus())||DeviceStatusEnum.RUN_STOP.getCode().equals(run.getOperationStatus())) {
                                String runEtc = super.getRunEtc(lastDate, tempDate, "");
                                StringBuffer sb = new StringBuffer();
                                sb.append(vo.getFactoryName()).append(vo.getDeviceName())
                                    .append("于").append(runEtc).append("存在启停行为，请注意。");
                                AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(),vo.getDeviceId(),  vo.getDeviceName(), tempDate,new Date(), ProblemTypeEnum.STOP_RUN,sb.toString(),"主抽风机电流,梭车布料器下料量,燃料（煤气） 流量,含氧量(出口)","p1,p2,g921,o2Out");
                                alarmList.add(problemFi);
                            }
                        }

                    }

                }
            });
            //批量保存
            super.doSaveBatchAnalysisRunStatus(runList);
            super.doSaveBatchAnalysisRunOneStatus(runOneList);
            super.doSaveOrUpdateBatchDeviceStatus(deviceStatusList);
            super.doSaveBatchAlarm(alarmList);
        }
    }

}
