import { onMounted, onUnmounted, ref } from 'vue';

import { useAccessStore } from '@vben/stores';

import { getWebSocketUrl } from '#/util/tool';
import {
  handleRegisterNotifyMessage,
  REGISTER_NOTIFY_MESSAGE_TYPE,
} from '#/utils/register-notify';

import { useChatStore } from '../stores/chat';
import { useUserStore } from '../stores/user';
// useVbenUserStore
export function useWebSocket() {
  const userStore = useUserStore();
  const chatStore = useChatStore();
  const accessStore = useAccessStore();
  
  // 认证状态
  const isAuthenticated = ref(false);
  const cachedToken = ref<string | null>(null);

  const socket = ref();
  const isConnected = ref(false);
  const isConnecting = ref(false);
  const reconnectAttempts = ref(0);
  const maxReconnectAttempts = 5;
  const reconnectDelay = ref(1000);

  const connectWebSocket = () => {
    if (isConnecting.value || isConnected.value) return;

    isConnecting.value = true;
    chatStore.connectionStatus = 'connecting';

    try {
      const wsUrl = getWebSocketUrl();
      socket.value = new WebSocket(wsUrl);

      socket.value.addEventListener('open', handleOpen);
      socket.value.onmessage = handleMessage;
      socket.value.addEventListener('close', handleClose);
      socket.value.onerror = handleError;
    } catch (error) {
      console.error('WebSocket连接失败:', error);
      isConnecting.value = false;
      chatStore.connectionStatus = 'disconnected';
    }
  };

  const handleOpen = (event) => {
    console.log('WebSocket连接已建立');
    isConnected.value = true;
    isConnecting.value = false;
    reconnectAttempts.value = 0;
    reconnectDelay.value = 1000;
    chatStore.connectionStatus = 'connected';
    chatStore.socket = socket.value;
    console.log(userStore.currentUser, 'ssssssssss')

    // 绑定当前用户
    if (userStore.currentUser?.doctor_id) {
      bindUser(userStore.currentUser.doctor_id);
    }
  };

  const handleMessage = (event) => {
    try {
      const data = JSON.parse(event.data);
      console.log('收到WebSocket消息:', data);

      // 处理认证响应
      if (data.auth_status !== undefined) {
        if (data.auth_status === 'success') {
          console.log('WebSocket认证成功');
          isAuthenticated.value = true;
        } else if (data.auth_status === 'failed') {
          console.error('WebSocket认证失败:', data.message);
          isAuthenticated.value = false;
          cachedToken.value = null;
        } else if (data.auth_status === 'token_expired') {
          console.warn('Token已过期，需要重新认证');
          isAuthenticated.value = false;
          cachedToken.value = null;
          // 尝试重新绑定
          if (userStore.currentUser?.doctor_id) {
            bindUser(userStore.currentUser.doctor_id);
          }
        }
        return;
      }

      // 处理clientId响应，进行用户绑定
      if (data.clientId) {
        console.log('收到clientId，准备绑定用户');
        if (userStore.currentUser?.doctor_id) {
          bindUser(userStore.currentUser.doctor_id);
        }
        return;
      }

      // 挂号实时提醒（message_type=15 系统通知）：弹桌面/站内通知+提示音，不进聊天窗口
      if (Number(data.message_type) === REGISTER_NOTIFY_MESSAGE_TYPE) {
        handleRegisterNotifyMessage(data);
        return;
      }

      // 优先处理通话信令（无论是否在当前聊天窗口）
      if (data.call_id && data.call_status) {
        handleCallSignal(data);
        return;
      }

      // 处理普通消息 - 添加来源判断防止循环
      if (data.sender_user_id && data.receiver_user_id) {
        chatStore.handleIncomingMessage(data, userStore.currentUser?.doctor_id);
      }
    } catch (error) {
      console.error('解析WebSocket消息失败:', error);
    }
  };

  const handleClose = (event) => {
    console.log('WebSocket连接已关闭:', event.code, event.reason);
    isConnected.value = false;
    isConnecting.value = false;
    chatStore.connectionStatus = 'disconnected';
    chatStore.socket = null;

    // 自动重连
    if (reconnectAttempts.value < maxReconnectAttempts) {
      setTimeout(() => {
        reconnectAttempts.value++;
        reconnectDelay.value = Math.min(reconnectDelay.value * 2, 30_000);
        console.log(
          `尝试重连 (${reconnectAttempts.value}/${maxReconnectAttempts})`,
        );
        connectWebSocket();
      }, reconnectDelay.value);
    }
  };

  const handleError = (error) => {
    console.error('WebSocket错误:', error);
    isConnecting.value = false;
    chatStore.connectionStatus = 'disconnected';
  };

  const handleCallSignal = (data) => {
    console.log('收到通话信令:', data);
    chatStore.handleCallSignal(data);
  };

  /**
   * 获取当前用户的token
   */
  const getToken = (): string | null => {
    // 优先使用缓存的token
    if (cachedToken.value) {
      return cachedToken.value;
    }
    // 从accessStore获取token
    let token = accessStore.accessToken;
    if (token) {
      // 移除Bearer前缀（如果有）
      token = token.replace('Bearer ', '');
      cachedToken.value = token;
    }
    return token || null;
  };

  /**
   * 绑定用户（携带token进行认证）
   */
  const bindUser = (userId) => {
    if (!isConnected.value || !userId) return;

    const token = getToken();
    if (!token) {
      console.error('绑定用户失败：token不存在');
      return false;
    }

    const bindMessage = {
      request_type: 'bind',
      user_type: 'doctor',
      sender_user_id: `doctor-${userId}`,
      token: token,
    };

    return send(bindMessage);
  };

  /**
   * 发送消息（自动携带token）
   * @param message 消息对象
   * @param requireAuth 是否需要认证（默认true）
   */
  const send = (message: any, requireAuth = true) => {
    if (!isConnected.value || !socket.value) {
      console.error('WebSocket未连接，无法发送消息');
      return false;
    }

    try {
      // 如果需要认证且消息中没有token，自动添加token
      if (requireAuth && !message.token && message.request_type !== 'ping') {
        const token = getToken();
        if (token) {
          message.token = token;
        }
      }

      socket.value.send(JSON.stringify(message));
      console.log('发送消息:', message);
      return true;
    } catch (error) {
      console.error('发送消息失败:', error);
      return false;
    }
  };

  const sendMessage = (receiverUserId, messageType, content) => {
    const message = {
      request_type: 'send_message',
      sender_user_id: userStore.currentUser?.doctor_id,
      receiver_user_id: receiverUserId,
      message_type: messageType,
      message_content: content,
    };

    return send(message);
  };

  const sendCallSignal = (signal) => {
    return send({
      request_type: 'call_signal',
      ...signal,
      sender_user_id: userStore.currentUser?.doctor_id,
    });
  };

  const disconnect = () => {
    if (socket.value) {
      socket.value.close();
      socket.value = null;
    }
    isConnected.value = false;
    isConnecting.value = false;
    chatStore.connectionStatus = 'disconnected';
    chatStore.socket = null;
  };

  // 生成唯一ID
  const generateCallId = () => {
    return Date.now().toString() + Math.random().toString(36).slice(2, 11);
  };

  // onMounted(() => {
  //   connectWebSocket();
  // });

  onUnmounted(() => {
    disconnect();
  });

  return {
    socket,
    isConnected,
    isConnecting,
    isAuthenticated,
    connectWebSocket,
    disconnect,
    send,
    sendMessage,
    sendCallSignal,
    bindUser,
    generateCallId,
    getToken,
  };
}
