package com.usky.meeting.websocket;

import com.usky.common.core.bean.ApiResult;
import com.usky.meeting.service.MeetingDeviceWebSocketService;
import com.usky.meeting.service.vo.WebSocketConnectionResponseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

@Slf4j
@Controller
@RequiredArgsConstructor
@RequestMapping("/meetingDevice/websocket")
public class MeetingDeviceWebSocketController {

    @Autowired
    private MeetingDeviceWebSocketService deviceWebSocketService;

    @GetMapping("/connect")
    @ResponseBody
    public ApiResult<WebSocketConnectionResponseVO> connect(
            @RequestParam String deviceCode
            //,@RequestHeader(value = "X-Real-IP", required = false) String realIp
    ) {
        log.info("收到WebSocket连接请求, deviceCode: {}", deviceCode);
        WebSocketConnectionResponseVO response = new WebSocketConnectionResponseVO();
        try {
            Map<String, Object> validateResult = deviceWebSocketService.validateDevice(deviceCode);
            response.setDeviceCode(deviceCode);
            response.setDeviceName((String) validateResult.get("deviceName"));
            response.setDeviceStatus((Integer) validateResult.get("deviceStatus"));
            response.setIsOnline((Boolean) validateResult.get("isOnline"));
            response.setMessage("设备验证通过，可建立WebSocket连接");
            response.setTimestamp(System.currentTimeMillis());
            log.info("设备验证成功, deviceCode: {}", deviceCode);
            return ApiResult.success(response);
        } catch (Exception e) {
            log.error("设备验证失败, deviceCode: {}", deviceCode, e);
            response.setDeviceCode(deviceCode);
            response.setMessage("设备验证失败: " + e.getMessage());
            response.setTimestamp(System.currentTimeMillis());
            return ApiResult.error(e.getMessage());
        }
    }

    @GetMapping("/status/{sessionId}")
    @ResponseBody
    public ApiResult<Map<String, Object>> getConnectionStatus(@PathVariable String sessionId) {
        Map<String, Object> status = new HashMap<>();
        boolean isOpen = MeetingDeviceWebSocketHandler.isSessionOpen(sessionId);
        String deviceCode = MeetingDeviceWebSocketHandler.getDeviceCodeBySession(sessionId);
        status.put("sessionId", sessionId);
        status.put("deviceCode", deviceCode);
        status.put("isOpen", isOpen);
        status.put("checkTime", LocalDateTime.now().toString());
        return ApiResult.success(status);
    }

    @GetMapping("/close/{sessionId}")
    @ResponseBody
    public ApiResult<Void> closeConnection(@PathVariable String sessionId) {
        MeetingDeviceWebSocketHandler.removeSession(sessionId);
        log.info("WebSocket连接已手动关闭, sessionId: {}", sessionId);
        return ApiResult.success();
    }
}
