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.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.BasDeviceSite;
import cn.cecep.talroad.domain.MonElecReal;
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.IBasDeviceService;
import cn.cecep.talroad.service.IBasDeviceSiteService;
import cn.cecep.talroad.service.IBasParamService;
import cn.cecep.talroad.service.IMonDevJhRealService;
import cn.cecep.talroad.service.IMonElecRealService;
import cn.cecep.talroad.service.strategy.AbstractStrategyAdapter;
import cn.cecep.talroad.service.strategy.StatusStrategyAdapter;
import cn.cecep.talroad.vo.FactoryDeviceVo;
import cn.cecep.talroad.vo.MonElecRealSiteVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @Auther: cjh
 * @Date: 2023-04-03 11:04
 * @Class: JhJlAdapter
 * @Deseription: 任务调度-定时
 * @Version V1.0
 */
@Service("JHJL")
public class JhJlAdapter extends StatusStrategyAdapter {


    @Autowired
    private IBasDeviceService basDeviceService;
    @Autowired
    private IMonElecRealService monElecRealService;



    @Override
    protected void doProcessStatus(String industry, String deviceType,Date curr) {
        //查询该行业所有设备

        Date lastHour = DateUtils.addMinutes(curr,-15);

        List<MonElecRealSiteVo> list = monElecRealService.selectLatestMonElecRealByParams(industry,deviceType,lastHour,curr);

        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->{
                if(StringUtils.isNotEmpty(real.getActivePower())&&StringUtils.isNotEmpty(real.getMinValue())){
                    // 根据设备ID，查询企业名称、设备名称等信息
                    FactoryDeviceVo vo = basDeviceService.selectFactoryDeviceVoByDeviceId(real.getDeviceId());
                    SRaRealTimeAnalysisRunOne oldDeviceStatus = super.getOldDeviceStatus(vo.getFactoryId(),vo.getDeviceId());
                    oldDeviceStatus = super.getOldDeviceStatus(vo.getFactoryId(),vo.getDeviceId());
                    // 总功率低于额定功率10%视为停产
                    if (Double.valueOf(real.getActivePower()) <= Double.valueOf(real.getMinValue())) {
                        //低于额定功率10%，设备停产
                        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(),"","");
                            problemFi.setParamName("总有功功率（千瓦）");
                            problemFi.setParamProperty("activePower");
                            //总有功功率（千瓦）
                            Map<String, Object> map = new HashMap<>();
                            List<Map<String, Object>> mapList = new ArrayList<>();
                            Map m = new HashMap();
                            m.put("deviceSiteId", real.getDeviceSiteId());
                            m.put("params", Arrays.asList(new String[]{"activePower"}));
                            mapList.add(m);
                            map.put("elecDeviceSiteList", mapList);
                            problemFi.setExtra(JSON.toJSONString(map));
                            alarmList.add(problemFi);
                        }
                    }else{
                        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(),"","");
                            problemFi.setParamName("总有功功率（千瓦）");
                            problemFi.setParamProperty("activePower");
                            //总有功功率（千瓦）
                            Map<String, Object> map = new HashMap<>();
                            List<Map<String, Object>> mapList = new ArrayList<>();
                            Map m = new HashMap();
                            m.put("deviceSiteId", real.getDeviceSiteId());
                            m.put("params", Arrays.asList(new String[]{"activePower"}));
                            mapList.add(m);
                            map.put("elecDeviceSiteList", mapList);
                            problemFi.setExtra(JSON.toJSONString(map));
                            alarmList.add(problemFi);
                        }
                    }
                }
            });
            //批量保存
            super.doSaveBatchAnalysisRunStatus(runList);
            super.doSaveBatchAnalysisRunOneStatus(runOneList);
            super.doSaveOrUpdateBatchDeviceStatus(deviceStatusList);
            super.doSaveBatchAlarm(alarmList);
        }
    }
}
