package com.zksy.manhole.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.common.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

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

@Component
public class AlarmUtil {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${alarm.api.url:http://zk-api-service/alarmData/save}")
    private String alarmApiUrl;

    public void checkAndSaveAlarm(String deviceName, String deviceCode, String deviceType,
                                    String warningType, String warningCode, Double warningValue,
                                    BigDecimal actualValue, String remark) {
        if (warningValue == null || actualValue == null) {
            return;
        }

        if (actualValue.doubleValue() > warningValue) {
            saveAlarm(deviceName, deviceCode, deviceType, warningType, warningCode,
                    BigDecimal.valueOf(warningValue), actualValue, remark);
        }
    }

    public void saveAlarm(String deviceName, String deviceCode, String deviceType,
                           String warningType, String warningCode, BigDecimal warningValue,
                           BigDecimal actualValue, String remark) {
        try {
            Map<String, Object> alarmData = new HashMap<>();
            alarmData.put("deviceName", deviceName);
            alarmData.put("deviceCode", deviceCode);
            alarmData.put("deviceType", deviceType);
            alarmData.put("warningType", warningType);
            alarmData.put("warningCode", warningCode);
            alarmData.put("warningValue", warningValue);
            alarmData.put("actualValue", actualValue);
            alarmData.put("alarmStatus", 0);
            alarmData.put("alarmTime", LocalDateTime.now().toString());
            alarmData.put("remark", remark);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(alarmData, headers);

            restTemplate.postForObject(alarmApiUrl, request, AjaxResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
