// websocket.js
let socketTask = null;
let reconnectAttempts = 0;
const maxReconnectAttempts = 5;

let heartbeatTimer = null;


export function connectWebSocket() {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('Access-Token');
    const Ids = uni.getStorageSync('login_user_info')['id'];
    const userId = Ids + '_app?token=' + token;

    // const url = 'http://' + window.location.hostname + ':9999'?.replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId;
    const url =  uni.getStorageSync("apiUrl").replace('https://', 'wss://').replace('http://', 'ws://') + '/websocket/' + userId;
    console.log(url, 'url======')
    // 创建连接
    socketTask = uni.connectSocket({
      url: url,
      success: () => {
        console.log('WebSocket 连接创建中...');
      },
      fail: (err) => {
        console.error('连接创建失败:', err);
        reject(err);
      }
    });

    // 监听打开事件
    socketTask.onOpen((res) => {
      console.log('WebSocket 连接已打开');
      startHeartbeat();
      reconnectAttempts = 0;
      resolve(socketTask);
    });

    // 监听错误事件
    socketTask.onError((err) => {
      console.error('WebSocket 错误:', err);
      handleReconnection();
      reject(err);
    });

    // 监听关闭事件
    socketTask.onClose((res) => {
      console.log('WebSocket 连接已关闭', res);
      clearInterval(heartbeatTimer);
      if (!res.code === 1000) { // 非正常关闭
        handleReconnection();
      }
    });
  });
}

function handleReconnection() {
  if (reconnectAttempts < maxReconnectAttempts) {
    reconnectAttempts++;
    const delay = Math.min(1000 * reconnectAttempts, 5000);

    console.log(`尝试第 ${reconnectAttempts} 次重连，${delay}ms后执行`);

    setTimeout(() => {
      connectWebSocket().catch(console.error);
    }, delay);
  } else {
    console.error(`已达到最大重连次数 ${maxReconnectAttempts}`);
  }
}

// 发送消息
export function sendWebSocketMessage(message) {
  return new Promise((resolve, reject) => {
    if (!socketTask || socketTask.readyState !== 1) {
      reject('WebSocket 未连接');
      return;
    }

    socketTask.send({
      data: JSON.stringify(message),
      success: () => resolve(),
      fail: (err) => reject(err)
    });
  });
}

// 关闭连接
export function closeWebSocket() {
  if (socketTask) {
    socketTask.close({
      code: 1000,
      reason: '用户主动关闭'
    });
  }
}




function startHeartbeat() {
  // 每30秒发送一次心跳
  heartbeatTimer = setInterval(() => {
    sendWebSocketMessage({
      type: 'heartbeat',
      timestamp: Date.now()
    }).catch(() => {
      clearInterval(heartbeatTimer);
    });
  }, 60000);
}

