package com.zksy.environment.utils;

import com.alibaba.fastjson.JSONObject;
import com.zksy.api.domain.AlarmData;
import com.zksy.api.service.AlarmDataService;
import com.zksy.api.service.EarlyWarningAutoService;
import com.zksy.api.utils.AlarmLevelUtil;
import com.zksy.api.utils.SmsUtil;
import com.zksy.utils.DevicePhoneFetchUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Component
public class AlarmUtil {

    private static final Logger log = LoggerFactory.getLogger(AlarmUtil.class);

    @Autowired
    private AlarmDataService alarmDataService;
    @Autowired
    private EarlyWarningAutoService earlyWarningAutoService;
    @Autowired
    private SmsUtil smsUtil;
    @Autowired
    private DevicePhoneFetchUtil devicePhoneFetchUtil;

    /**
     * 越限 → 报警；接近阈值未越限 → 自动预警
     * @return 是否触发报警
     */
    public boolean checkAndSaveAlarm(String deviceCode,
                                    String warningType, String warningCode, Double minValue, Double maxValue,
                                    BigDecimal actualValue, String remark) {
        if (actualValue == null || (minValue == null && maxValue == null)) {
            return false;
        }

        BigDecimal minBd = minValue != null ? BigDecimal.valueOf(minValue) : null;
        BigDecimal maxBd = maxValue != null ? BigDecimal.valueOf(maxValue) : null;

        boolean shouldAlarm = false;
        if (minValue != null && actualValue.doubleValue() <= minValue) {
            shouldAlarm = true;
        }
        if (maxValue != null && actualValue.doubleValue() >= maxValue) {
            shouldAlarm = true;
        }

        if (shouldAlarm) {
            saveAlarm(deviceCode, warningType, warningCode, minBd, maxBd, actualValue, remark);
            earlyWarningAutoService.closeAutoWarning(deviceCode, warningCode, "已达报警阈值，转报警处理");
            return true;
        } else {
            earlyWarningAutoService.checkAndGenerate(deviceCode, warningType, warningCode,
                    minBd, maxBd, actualValue, remark);
            return false;
        }
    }

    public int saveAlarm(String deviceCode,
                           String warningType, String warningCode, BigDecimal minValue, BigDecimal maxValue,
                           BigDecimal actualValue, String remark) {
        int alarmLevel = 4;
        try {
            AlarmData alarmData = new AlarmData();
            alarmData.setDeviceCode(deviceCode);
            alarmData.setWarningType(warningType);
            alarmData.setWarningCode(warningCode);
            alarmData.setMinValue(minValue);
            alarmData.setMaxValue(maxValue);
            alarmData.setActualValue(actualValue);

            alarmLevel = AlarmLevelUtil.calculateLevel(actualValue, minValue, maxValue);
            BigDecimal deviationRatio = AlarmLevelUtil.calculateDeviationRatio(actualValue, minValue, maxValue);
            alarmData.setAlarmLevel(alarmLevel);
            alarmData.setDeviationRatio(deviationRatio);

            alarmData.setAlarmStatus(0);
            alarmData.setAlarmTime(LocalDateTime.now());
            alarmData.setRemark(remark);
            alarmData.setCreateTime(LocalDateTime.now());

            alarmDataService.saveAlarmData(alarmData);

            if (alarmLevel == 1) {
                log.warn("【1级紧急告警】deviceCode={}, warningCode={}, deviationRatio={}%",
                        deviceCode, warningCode, deviationRatio);
                sendAlarmSms(deviceCode, warningType, actualValue, minValue, maxValue);
            }
            log.info("告警数据入库成功: deviceCode={}, warningCode={}, level={}级", deviceCode, warningCode, alarmLevel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return alarmLevel;
    }

    private void sendAlarmSms(String deviceCode, String warningType, BigDecimal actualValue,
                              BigDecimal minValue, BigDecimal maxValue) {
        try {
            List<String> phoneList = devicePhoneFetchUtil.getPhoneListByDeviceId(deviceCode);
            if (phoneList == null || phoneList.isEmpty()) {
                log.warn("报警短信发送失败：未找到设备{}的联系人手机号", deviceCode);
                return;
            }
            JSONObject params = new JSONObject();
            params.put("deviceNo", deviceCode);
            params.put("alarmType", warningType);
            params.put("location", "当前值：" + actualValue + "，正常范围：" + minValue + "~" + maxValue);

            Map<String, Boolean> result = smsUtil.sendBatchSms(phoneList, params.toJSONString());
            long successCount = result.values().stream().filter(Boolean::booleanValue).count();
            log.info("1级告警短信发送完成，成功{}条，失败{}条", successCount, phoneList.size() - successCount);
        } catch (Exception e) {
            log.error("发送报警短信异常: {}", e.getMessage());
        }
    }
}
