package com.mvc.service.alarm;

import com.mvc.entity.TAiread;
import com.mvc.entity.TAlarmSubscriptionDetail;
import com.mvc.model.StationAccModel;
import com.mvc.model.alarm.TAlarmSubscriptionModel;
import com.mvc.service.copy.TAireadService;
import com.mvc.service.taizhang.StationAccService;
import com.mvc.utils.DateUtil;
import com.mvc.utils.NotifyUtil;
import com.mvc.utils.SmsUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TAlarmSubscriptionMana {
    private static Logger log = LoggerFactory.getLogger(TAlarmSubscriptionMana.class);

    @Resource
    private TAlarmSubscriptionService alarmSubscriptionService;

    @Resource
    private TAireadService aireadService;

    @Resource
    private NotifyUtil notifyUtil;

    @Resource
    private StationAccService stationAccService;

    /**
     * 处理订阅报警
     */
    public void handleSubscribeAlarm() {
        List<TAlarmSubscriptionModel> alarmSubscriptionModels = alarmSubscriptionService.findAlarmSubscriptionsByExample(null, true);
        for (TAlarmSubscriptionModel model : alarmSubscriptionModels) {
            if (model.getUseFlag() != 1) {
                continue;
            }
            for (TAlarmSubscriptionDetail detail : model.getDetails()) {
                handleAlarmData(model, detail.getStationCode());
            }
        }
    }

    /**
     * 处理、分析报警数据
     *
     * @param model
     * @param stationCode
     */
    private void handleAlarmData(TAlarmSubscriptionModel model, String stationCode) {
        Date today = DateUtil.getZeroTimeOfDay(new Date());
        int durationDays = model.getDurationHours();//已经将小时转为天数了
        if (durationDays < 1) {//持续时间无效
            return;
        }
        Date startTime = DateUtil.getOtherDateByCurrentDate(today, -durationDays);
        List<TAiread> aireads = aireadService.findAllTaireadByStationCodeAndTime(stationCode, startTime, today);//正序的
        Map<Date, TAiread> map = aireads.stream().collect(Collectors.toMap(TAiread::getSampleTime, TMarkRecord -> TMarkRecord));
        Date temp = startTime;

        int num = 0;
        for (int i = 0; i < durationDays; i++) {
            TAiread airead0 = null;
            TAiread airead1 = null;
            if (map.containsKey(temp)) {
                airead0 = map.get(temp);
            }
            temp = DateUtil.getOtherDateByCurrentDate(temp, 1);
            if (map.containsKey(temp)) {
                airead1 = map.get(temp);
            }
            if (airead0 == null || airead1 == null) {//少记录
                num = -1;
                break;
            }
            if (airead0.getResultValue() == null || airead1.getResultValue() == null) {//值无效
                num = -1;
                break;
            }
            if (airead1.getResultValue().subtract(airead0.getResultValue()).intValue() > model.getThresholdValue()) {
                num++;
            }
            if (temp.compareTo(today) >= 0) {
                break;
            }
        }
        if (num == -1) {
            log.error("报警订阅处理:{},数据不完整", stationCode);
            return;
        } else if (num < durationDays) {//符合条件,无需推送
            return;
        }

        try {
            StationAccModel accModel = stationAccService.findStationAccByStationCode(stationCode);
            String stationInfo = accModel != null ? accModel.getStationName() : stationCode;
            log.info("报警订阅处理:{},符合条件", stationInfo);
            //需要邮件通知
            if (StringUtils.isNotEmpty(model.getEmailAddress())) {
                String content = String.format("站点：%s，连续 %d 天超过设定的用量阈值 %d m³，请注意观察！", stationInfo, durationDays, model.getThresholdValue());
                notifyUtil.sendEMail(model.getEmailAddress(), "【边缘AI抄表器】用量预警通知", content);
            }

            //需要短信通知
            if (StringUtils.isNotEmpty(model.getPhoneNumber())) {
                stationInfo = stationInfo.length() > 20 ? stationInfo.substring(0, 20) : stationInfo;//防止站名过长导致短信变2条
                String[] phoneNumbers = model.getPhoneNumber().split(";");
                String[] templateParamSet = new String[]{stationInfo, String.valueOf(durationDays), model.getThresholdValue().toString()};
                String templateId = (model.getApiTemplateId() == null ? null : model.getApiTemplateId().toString());
                SmsUtil.sendSms(phoneNumbers, templateParamSet, templateId, null);
            }
        } catch (Exception ex) {
            log.error("TAlarmSubscriptionMana", ex);
        }
    }
}
