package org.ts.ddcs.worker;

import com.alibaba.fastjson.JSONObject;
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.Date;
import java.util.concurrent.Callable;


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

    private String body;

    WarningProcessTask(String body) {
        this.body = body;
    }

    @Override
    public Integer call() throws Exception {
        try {
            RedisTemplate redisTemplate = DataProcessHolder.newInstance().dataProcess.redisTemplate;
            HashOperations<String, String, String> opsHash = redisTemplate.opsForHash();
            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            JSONObject warningData = JSONObject.parseObject(body);
            Date checkTime = new Date();
            if (warningData.containsKey(GBConstants.BASE_KEY_WARNING_CHECK_TIME)) {
                String dt = warningData.getString(GBConstants.BASE_KEY_WARNING_CHECK_TIME);
                checkTime = timeFormat.parse(dt);
            }
            String rtuCode = warningData.getString(GBConstants.BASE_KEY_RTU);
            if (null == rtuCode || rtuCode.length() == 0) {
                return 0;
            }
            String status = warningData.getString(GBConstants.BASE_KEY_WARNING_STATUS);
            if (null == status || status.length() == 0) {
                return 0;
            }
            String projectId = opsHash.get(rtuCode, "projectId");
            if (null == projectId || projectId.equals("")) {
                return 0;
            }
            String agreement = warningData.getString(GBConstants.BASE_KEY_AGREEMENT);
            String datagram = warningData.getString(GBConstants.BASE_KEY_DATAGRAM);
            String warningKind = warningData.getString(GBConstants.BASE_KEY_WARNING_KIND);
            String warningInfo = warningData.getString(GBConstants.BASE_KEY_WARNING_INFO);

            JSONObject wc = new JSONObject();
            wc.put(GBConstants.BASE_KEY_AGREEMENT,agreement);
            wc.put(GBConstants.BASE_KEY_DATAGRAM,datagram);
            String warningContent = wc.toJSONString();


            /**检查所属项目配置,规则：项目预警开关配置需要显式配置为开，才会进行预警检查，没有配置或配置成关，不进行预警检查**/
            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) {
                return 0;
            }
            String warningSwitch = "";
            if (warningKind.equals(GBConstants.WARNING_TYPE_OFFLINE)) {
                warningSwitch = projectWarningSettingInfo.getOfflineSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_DATAGRAM_DELAY)) {
                warningSwitch = projectWarningSettingInfo.getDatagramDelaySwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_RTU_FAULT_SE)) {
                warningSwitch = projectWarningSettingInfo.getFaultSeSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_RTU_FAULT_AC)) {
                warningSwitch = projectWarningSettingInfo.getFaultAcSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_RTU_FAULT_BV)) {
                warningSwitch = projectWarningSettingInfo.getFaultBvSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_RTU_COLLECT_TIME_ERROR)) {
                warningSwitch = projectWarningSettingInfo.getCollectTimeErrorSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_CRC_ERROR)) {
                warningSwitch = projectWarningSettingInfo.getCrcErrorSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_OUTLIER_DATA)) {
                warningSwitch = projectWarningSettingInfo.getOutlierDataSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_SD_DAMAGE)) {
                warningSwitch = projectWarningSettingInfo.getSdDamageSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_RTU_NET_BLOCKING)) {
                warningSwitch = projectWarningSettingInfo.getRtuNetBlockingSwitch();
            } else if (warningKind.equals(GBConstants.WARNING_TYPE_SUN_VOLTAGE)) {
                warningSwitch = projectWarningSettingInfo.getSunVoltageSwitch();
            }
            /**检查项目预警类别设置是否打开**/
            if (null != warningSwitch && warningSwitch.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) {
                    return 0;
                }
                if (status.equals(GBConstants.WARNING_STATUS_HAPPEN)) {
                    WarningInfo info = WarningHelper.toWarningInfo(rtuCode, warningKind, status, checkTime, warningInfo, warningContent);
                    //保存预警信息
                    DataProcessHolder.newInstance().dataProcess.warningService.saveWarning(info);
                    if (opsHash.hasKey(rtuCode, "warning_" + warningKind)) {
                        String warning = opsHash.get(rtuCode, "warning_" + warningKind);
                        if (null == warning || warning.equals(GBConstants.WARNING_STATUS_RECOVERY)) {
                            //更新缓存
                            opsHash.put(rtuCode, "warning_" + warningKind, GBConstants.WARNING_STATUS_HAPPEN);
                            //推送预警信息
                            DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(info);
                        }
                    } else {
                        //更新缓存
                        opsHash.put(rtuCode, "warning_" + warningKind, GBConstants.WARNING_STATUS_HAPPEN);
                        //推送预警信息
                        DataProcessHolder.newInstance().dataProcess.submitWarningNotifyTask(info);
                    }

                } else if (status.equals(GBConstants.WARNING_STATUS_RECOVERY)) {
                    WarningInfo info = WarningHelper.toWarningInfo(rtuCode, warningKind, status, checkTime, warningInfo, warningContent);
                    //保存预警信息
                    DataProcessHolder.newInstance().dataProcess.warningService.warningRecovery(info);
                    if (opsHash.hasKey(rtuCode, "warning_" + warningKind)) {
                        String warning = opsHash.get(rtuCode, "warning_" + warningKind);
                        if (null != warning && warning.equals(GBConstants.WARNING_STATUS_HAPPEN)) {
                            //更新缓存
                            opsHash.put(rtuCode, "warning_" + warningKind, GBConstants.WARNING_STATUS_RECOVERY);
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogHelper.error(e);
        }
        return 0;
    }
}
