package com.zksy.gas.utils;

import com.zksy.api.domain.AlarmData;
import com.zksy.api.service.AlarmDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Component
public class AlarmUtil {

    @Autowired
    private AlarmDataService alarmDataService;

    public void checkAndSaveAlarm(String deviceCode,
                                    String warningType, String warningCode, Double minValue, Double maxValue,
                                    BigDecimal actualValue, String remark) {
        if (actualValue == null) {
            return;
        }

        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,
                    minValue != null ? BigDecimal.valueOf(minValue) : null,
                    maxValue != null ? BigDecimal.valueOf(maxValue) : null,
                    actualValue, remark);
        }
    }

    public void saveAlarm(String deviceCode,
                           String warningType, String warningCode, BigDecimal minValue, BigDecimal maxValue,
                           BigDecimal actualValue, String remark) {
        try {
            AlarmData alarmData = new AlarmData();
            alarmData.setDeviceCode(deviceCode);
            alarmData.setWarningType(warningType);
            alarmData.setWarningCode(warningCode);
            alarmData.setMinValue(minValue);
            alarmData.setMaxValue(maxValue);
            alarmData.setActualValue(actualValue);
            alarmData.setAlarmStatus(0);
            alarmData.setAlarmTime(LocalDateTime.now());
            alarmData.setRemark(remark);
            alarmData.setCreateTime(LocalDateTime.now());

            alarmDataService.saveAlarmData(alarmData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
