package org.ts.ddcs.worker;

import org.ts.ddcs.entity.ProjectWarningSettingInfo;
import org.ts.ddcs.entity.RtuWarningSettingInfo;
import org.ts.ddcs.entity.WarningInfo;
import org.ts.ddcs.log.LogHelper;
import org.ts.ddcs.tool.WarningHelper;
import org.ts.ddcs.utils.GBConstants;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.Callable;


/**
 * @author dylan
 */
public class RtuOnlineCheckTask implements Callable<Integer> {

    private Date checkTime;

    RtuOnlineCheckTask(Date checkTime) {
        this.checkTime = checkTime;
    }

    @Override
    public Integer call() throws Exception {
        try {
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            if (null == redisTemplate) {
                return 0;
            }
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            Set<String> keys = opsHash.keys("rtu_online");
            if (null != keys && keys.size() > 0) {
                for (String rtuCode : keys) {
                    String projectId = opsHash.get(rtuCode, "projectId");
                    if (null != projectId) {
                        /**检查所属项目配置,规则：项目预警开关配置需要显式配置为开，才会进行预警检查，没有配置或配置成关，不进行预警检查**/
                        boolean warningActive = false;
                        ProjectWarningSettingInfo projectWarningSettingInfo = WarningHelper.getProjectWarningSetting(projectId, redisTemplate);
                        if (null != projectWarningSettingInfo) {
                            String globalSwitch = projectWarningSettingInfo.getGlobalSwitch();
                            if (null != globalSwitch && globalSwitch.equals(GBConstants.WARNING_ACTIVE_ON)) {
                                warningActive = true;
                            }
                        }
                        if (warningActive) {
                            /**检查项目在线预警类别是否打开**/
                            String offlineSwitch = projectWarningSettingInfo.getOfflineSwitch();
                            if (null != offlineSwitch && offlineSwitch.equals(GBConstants.WARNING_ACTIVE_ON)) {
                                /**
                                 * 检查RTU预警开关是否打开,在项目预警开关打时，如果RTU预警开关没有配置或配置成开，需要进行检测；只有明显设置成关，才不检测
                                 */
                                RtuWarningSettingInfo rtuWarningSettingInfo = WarningHelper.getRtuWarningSetting(rtuCode, redisTemplate);
                                boolean rtuWarningActive = true;
                                if (null != rtuWarningSettingInfo) {
                                    String globalSwitch = rtuWarningSettingInfo.getGlobalSwitch();
                                    if (null != globalSwitch && globalSwitch.equals(GBConstants.WARNING_ACTIVE_OFF)) {
                                        rtuWarningActive = false;
                                    }
                                }
                                if (rtuWarningActive) {
                                    //最后上线时间
                                    String lastOnlineTime = opsHash.get("rtu_online", rtuCode);
                                    //默认在线维持时长
                                    int durationMinute = DataProcessHolder.newInstance().dataProcess.config.getOnlineDuration();
                                    //先从测站设置中取在线预警信息
                                    if (null != rtuWarningSettingInfo) {
                                        String offlineActive = rtuWarningSettingInfo.getOfflineWarningActive();
                                        if (null != offlineActive && offlineActive.equals(GBConstants.WARNING_ACTIVE_ON)) {
                                            String onlineDurationSetting = rtuWarningSettingInfo.getOfflineDuration();
                                            if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
                                                durationMinute = Integer.parseInt(onlineDurationSetting);
                                            }
                                        } else {
                                            //从项目设置中取在线预警信息
                                            String onlineDurationSetting = projectWarningSettingInfo.getOfflineDuration();
                                            if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
                                                durationMinute = Integer.parseInt(onlineDurationSetting);
                                            }
                                        }
                                    } else {
                                        //从项目设置中取在线预警信息
                                        String onlineDurationSetting = projectWarningSettingInfo.getOfflineDuration();
                                        if (null != onlineDurationSetting && onlineDurationSetting.length() > 0) {
                                            durationMinute = Integer.parseInt(onlineDurationSetting);
                                        }
                                    }
                                    Date lastOnlineDt = timeFormat.parse(lastOnlineTime);
                                    long goingTm = checkTime.getTime() - lastOnlineDt.getTime();
                                    if (goingTm > 0) {
                                        goingTm = goingTm / (60 * 1000);
                                    } else {
                                        goingTm = 0;
                                    }
                                    if (goingTm >= durationMinute) {
                                        WarningInfo warningInfo = WarningHelper.toWarningInfo(rtuCode, GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN, checkTime, "设备不在线", null);
                                        //保存预警信息
                                        DataProcessHolder.newInstance().dataProcess.warningService.saveWarning(warningInfo);
                                        if (opsHash.hasKey(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE)) {
                                            String warningStatusValue = opsHash.get(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE);
                                            //只在第一次预警时处理
                                            if (null == warningStatusValue || warningStatusValue.equals(GBConstants.WARNING_STATUS_RECOVERY)) {
                                                //更新缓存
                                                opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN);
                                                //推送预警信息
                                                DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
                                            }
                                        } else {
                                            //更新缓存
                                            opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_HAPPEN);
                                            //推送预警信息
                                            DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
                                        }
                                    } else {
                                        WarningInfo warningInfo = WarningHelper.toWarningInfo(rtuCode, GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_RECOVERY, checkTime, "设备在线恢复", null);
                                        //保存预警信息
                                        DataProcessHolder.newInstance().dataProcess.warningService.warningRecovery(warningInfo);
                                        if (opsHash.hasKey(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE)) {
                                            String warningStatus = opsHash.get(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE);
                                            if (null != warningStatus && warningStatus.equals(GBConstants.WARNING_STATUS_HAPPEN)) {
                                                //更新缓存
                                                opsHash.put(rtuCode, "warning_" + GBConstants.WARNING_TYPE_OFFLINE, GBConstants.WARNING_STATUS_RECOVERY);
                                                //推送预警信息
                                                DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(warningInfo);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return 0;
    }
}
