package com.zksy.api.controller;

import com.zksy.api.service.EquipmentStatusApiService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 设备状态统一更新接口
 * 供各采集服务在告警处理后调用，同步设备报警状态
 */
@Slf4j
@RestController
@RequestMapping("/equipmentStatus")
@Api(tags = "设备状态管理", description = "统一更新设备报警状态")
public class EquipmentStatusController {

    @Autowired
    private EquipmentStatusApiService equipmentStatusApiService;

    /**
     * 更新设备报警状态
     * @param params { deviceCode: "设备编码", alarmStatus: 0或1 }
     * @return 更新结果
     */
    @PostMapping("/updateAlarmStatus")
    @ApiOperation(value = "更新设备报警状态")
    public Map<String, Object> updateAlarmStatus(@RequestBody Map<String, Object> params) {
        String deviceCode = (String) params.get("deviceCode");
        Integer alarmStatus = null;
        Object alarmStatusObj = params.get("alarmStatus");
        if (alarmStatusObj instanceof Integer) {
            alarmStatus = (Integer) alarmStatusObj;
        } else if (alarmStatusObj != null) {
            alarmStatus = Integer.parseInt(alarmStatusObj.toString());
        }

        if (deviceCode == null || deviceCode.isEmpty()) {
            log.warn("更新报警状态参数无效：deviceCode为空");
            return Map.of("success", false, "msg", "deviceCode不能为空");
        }
        if (alarmStatus == null || (alarmStatus != 0 && alarmStatus != 1)) {
            log.warn("更新报警状态参数无效：alarmStatus={}", alarmStatus);
            return Map.of("success", false, "msg", "alarmStatus必须为0或1");
        }

        try {
            boolean result = equipmentStatusApiService.updateAlarmStatus(deviceCode, alarmStatus);
            return Map.of("success", result, "deviceCode", deviceCode, "alarmStatus", alarmStatus);
        } catch (Exception e) {
            log.error("更新设备报警状态异常: deviceCode={}, alarmStatus={}", deviceCode, alarmStatus, e);
            return Map.of("success", false, "msg", "更新失败: " + e.getMessage());
        }
    }
}