package com.usky.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.meeting.domain.MeetingDeviceHeartbeat;
import com.usky.meeting.mapper.MeetingDeviceHeartbeatMapper;
import com.usky.meeting.service.MeetingDeviceHeartbeatService;
import com.usky.common.mybatis.core.AbstractCrudService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 * 会议设备心跳表 服务实现类
 * </p>
 *
 * @author fu
 * @since 2025-11-13
 */
@Service
public class MeetingDeviceHeartbeatServiceImpl extends AbstractCrudService<MeetingDeviceHeartbeatMapper, MeetingDeviceHeartbeat> implements MeetingDeviceHeartbeatService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void heartbeatEscalation(MeetingDeviceHeartbeat heartbeat) {
        if (StringUtils.isBlank(heartbeat.getDeviceCode())) {
            throw new BusinessException("设备编码不能为空!");
        }
        if (StringUtils.isBlank(heartbeat.getIpAddr())) {
            throw new BusinessException("设备IP不能为空!");
        }
        if (heartbeat.getCreateTime() == null) {
            heartbeat.setCreateTime(LocalDateTime.now());
        }
        if (heartbeat.getDeviceType() == null) {
            throw new BusinessException("设备类型不能为空!");
        }

        // 删除旧数据
        LambdaQueryWrapper<MeetingDeviceHeartbeat> deleteWrapper = Wrappers.lambdaQuery();
        deleteWrapper.eq(MeetingDeviceHeartbeat::getDeviceCode, heartbeat.getDeviceCode());
        baseMapper.delete(deleteWrapper);

        baseMapper.insert(heartbeat);
    }
}
