package com.zksy.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zksy.api.domain.EquipmentBase;
import com.zksy.api.domain.EquipmentStatus;
import com.zksy.api.mapper.EquipmentBaseApiMapper;
import com.zksy.api.mapper.EquipmentStatusApiMapper;
import com.zksy.api.service.EquipmentStatusApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 设备报警状态服务实现
 * 根据设备编码更新 equipment_status 表的报警状态
 */
@Slf4j
@Service
public class EquipmentStatusApiServiceImpl implements EquipmentStatusApiService {

    @Autowired
    private EquipmentBaseApiMapper equipmentBaseApiMapper;

    @Autowired
    private EquipmentStatusApiMapper equipmentStatusApiMapper;

    @Override
    @Transactional
    public boolean updateAlarmStatus(String deviceCode, Integer alarmStatus) {
        if (deviceCode == null || deviceCode.isEmpty()) {
            log.warn("更新设备报警状态失败：deviceCode为空");
            return false;
        }

        // 1. 根据设备编码查询设备基础信息，获取 equipmentId
        EquipmentBase equipmentBase = equipmentBaseApiMapper.selectOne(
                new LambdaQueryWrapper<EquipmentBase>()
                        .eq(EquipmentBase::getEquipmentCode, deviceCode)
                        .last("LIMIT 1"));
        if (equipmentBase == null) {
            log.warn("更新设备报警状态失败：未找到设备编码对应的设备信息，deviceCode={}", deviceCode);
            return false;
        }

        String equipmentId = equipmentBase.getEquipmentId();

        // 2. 查询是否已有状态记录
        EquipmentStatus existingStatus = equipmentStatusApiMapper.selectOne(
                new LambdaQueryWrapper<EquipmentStatus>()
                        .eq(EquipmentStatus::getEquipmentId, equipmentId));

        if (existingStatus != null) {
            // 更新已有记录
            existingStatus.setAlarmStatus(alarmStatus);
            existingStatus.setStatusUpdateTime(LocalDateTime.now());
            equipmentStatusApiMapper.updateById(existingStatus);
            log.info("更新设备报警状态成功: deviceCode={}, equipmentId={}, alarmStatus={}",
                    deviceCode, equipmentId, alarmStatus);
        } else {
            // 不存在则创建新记录
            EquipmentStatus newStatus = new EquipmentStatus();
            newStatus.setEquipmentId(equipmentId);
            newStatus.setAlarmStatus(alarmStatus);
            newStatus.setCurrentStatus(1); // 默认在用
            newStatus.setOnlineStatus(1);  // 默认在线
            newStatus.setStatusUpdateTime(LocalDateTime.now());
            newStatus.setCreateTime(LocalDateTime.now());
            equipmentStatusApiMapper.insert(newStatus);
            log.info("创建设备报警状态记录成功: deviceCode={}, equipmentId={}, alarmStatus={}",
                    deviceCode, equipmentId, alarmStatus);
        }

        return true;
    }
}