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

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.domain.AmProblemFi;
import cn.cecep.talroad.domain.BasDeviceSalAnalysis;
import cn.cecep.talroad.domain.MonDevBlReal;
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.IMonDevBlRealService;
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.List;
import java.util.concurrent.atomic.AtomicInteger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: cjh
 * @Date: 2023-03-28 18:50
 * @Class: BlScxAdapter
 * @Deseription:
 * @Version V1.0
 */
@Service("BLSCX")
public class BlScxAdapter extends StatusStrategyAdapter {

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

    @Override
    protected void doProcessStatus(String industry, String deviceType,Date curr) {

        List<BasDeviceSalAnalysis> deviceStatusList = new ArrayList<>();
        List<SRaRealTimeAnalysisRun> runList = new ArrayList<>();
        List<SRaRealTimeAnalysisRunOne> runOneList = new ArrayList<>();
        List<AmProblemFi> alarmList = new ArrayList<>();

        Date lastHour = DateUtils.addMinutes(curr, -15);
        List<MonDevBlReal> realList = monDevBlRealService.selectLatestByParams(industry,deviceType, lastHour,curr);
        if(realList!=null&&realList.size()>0){
            realList.forEach(real->{
                AtomicInteger m = new AtomicInteger();
                AtomicInteger n = new AtomicInteger();
                // 根据设备ID，查询企业名称、设备名称等信息
                FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(real.getDeviceId());
                SRaRealTimeAnalysisRunOne oldDeviceStatus = super.getOldDeviceStatus(vo.getFactoryId(),vo.getDeviceId());
                List<BasDeviceParamVo> paramsList = basDeviceParamService.selectBasDeviceParamByCondition(real.getDeviceId(), Arrays.asList("bs102","bs107"));
                paramsList.forEach(param->{
                    if ("bs102".equalsIgnoreCase(param.getParamCodeSvc()) && StringUtils.isNotEmpty(real.getBs102())) {
                        m.getAndIncrement();
                        if (Double.valueOf(real.getBs102()) < param.getNormalValue().multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP).doubleValue()) {
                            n.getAndIncrement();
                        }
                    } else if ("bs107".equalsIgnoreCase(param.getParamCodeSvc()) && StringUtils.isNotEmpty(real.getBs107())) {
                        m.getAndIncrement();
                        if (Double.valueOf(real.getBs107()) < param.getNormalValue().multiply(new BigDecimal(0.1)).setScale(2, RoundingMode.HALF_UP).doubleValue()) {
                            n.getAndIncrement();
                        }
                    }
                });
                //数据缺失1种以上
                if (m.get() < 1) {
                    //数据缺失，无法判断"

                } else {
                    //满足其中一个停产条件即停机
                    if (n.get() > 0) {
                        //设备停机
                        SRaRealTimeAnalysisRun run = super.doProcessDeviceRunStatus(vo,lastHour,curr,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(lastHour, curr, "");
                            StringBuffer sb = new StringBuffer();
                            sb.append(vo.getFactoryName()).append(vo.getDeviceName())
                                .append("于").append(runEtc).append("存在启停行为，请注意。");
                            AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(),vo.getDeviceId(),  vo.getDeviceName(), lastHour,curr, ProblemTypeEnum.STOP_RUN,sb.toString(),"投料机输出频率,退火窑辊道车速","bs102,bs107");
                            alarmList.add(problemFi);
                        }
                    } else {
                        //停产条件比例占比未超过66%，设备未停机
                        SRaRealTimeAnalysisRun run = super.doProcessDeviceRunStatus(vo,lastHour,curr,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(lastHour, curr, "");
                            StringBuffer sb = new StringBuffer();
                            sb.append(vo.getFactoryName()).append(vo.getDeviceName())
                                .append("于").append(runEtc).append("存在启停行为，请注意。");
                            AmProblemFi problemFi = doProcessAlaram(vo.getFactoryId(),vo.getDeviceId(),  vo.getDeviceName(), lastHour,curr, ProblemTypeEnum.STOP_RUN,sb.toString(),"投料机输出频率,退火窑辊道车速","bs102,bs107");
                            alarmList.add(problemFi);
                        }
                    }
                }
            });

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