package com.usky.meeting.service;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.usky.common.core.exception.BusinessException;
import com.usky.meeting.domain.MeetingDevice;
import com.usky.meeting.domain.MeetingDeviceHeartbeat;
import com.usky.meeting.mapper.MeetingDeviceHeartbeatMapper;
import com.usky.meeting.mapper.MeetingDeviceMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Slf4j
@Service
@RequiredArgsConstructor
public class MeetingDeviceWebSocketService {

    private static final int HEARTBEAT_TIMEOUT_MINUTES = 5;

    @Autowired
    private MeetingDeviceMapper meetingDeviceMapper;

    @Autowired
    private MeetingDeviceHeartbeatMapper heartbeatMapper;

    public Map<String, Object> validateDevice(String deviceCode) {
        Map<String, Object> result = new HashMap<>();

        MeetingDevice device = validateDeviceExists(deviceCode);
        boolean isOnline = validateDeviceOnline(deviceCode);

        result.put("deviceCode", deviceCode);
        result.put("deviceName", device.getDeviceName());
        result.put("deviceStatus", isOnline ? 1 : 0);
        result.put("isOnline", isOnline);
        result.put("validateSuccess", true);

        log.info("设备验证成功, deviceCode: {}, isOnline: {}", deviceCode, isOnline);
        return result;
    }

    private MeetingDevice validateDeviceExists(String deviceCode) {
        MeetingDevice device = meetingDeviceMapper.selectOne(
                Wrappers.<MeetingDevice>lambdaQuery().eq(MeetingDevice::getDeviceCode, deviceCode)
        );
        if (device == null) {
            log.warn("设备不存在, deviceCode: {}", deviceCode);
            throw new BusinessException("设备不存在: " + deviceCode);
        }
        return device;
    }

    private boolean validateDeviceOnline(String deviceCode) {
        MeetingDeviceHeartbeat heartbeat = heartbeatMapper.selectOne(
                Wrappers.<MeetingDeviceHeartbeat>lambdaQuery()
                        .eq(MeetingDeviceHeartbeat::getDeviceCode, deviceCode)
                        .orderByDesc(MeetingDeviceHeartbeat::getCreateTime)
                        .last("LIMIT 1")
        );
        if (heartbeat == null) {
            log.warn("设备心跳记录不存在, deviceCode: {}", deviceCode);
            throw new BusinessException("设备离线: " + deviceCode + ", 未找到心跳记录");
        }
        LocalDateTime heartbeatTime = heartbeat.getCreateTime();
        LocalDateTime now = LocalDateTime.now();
        if (heartbeatTime == null || now.isAfter(heartbeatTime.plusMinutes(HEARTBEAT_TIMEOUT_MINUTES))) {
            log.warn("设备心跳超时, deviceCode: {}, heartbeatTime: {}", deviceCode, heartbeatTime);
            throw new BusinessException("设备离线: " + deviceCode + ", 心跳超时");
        }
        return true;
    }
}
