// utils/request.js
function request(options) {
  const app = getApp();
  const token = wx.getStorageSync('token');
  
  // 🔥 没有 token 时不发送请求，直接返回一个“空响应”对象，不影响后续代码
  if (!token) {
    // 返回一个模拟的响应，状态码为 401，但不会触发任何弹窗或跳转
    return Promise.resolve({
      statusCode: 401,
      data: { code: 401, msg: '未登录' },
      errMsg: 'request:ok'
    });
  }

  const header = {
    'Content-Type': 'application/json',
    ...options.header,
  };
  if (token) {
    header['Authorization'] = 'Bearer ' + token;
  }

  return new Promise((resolve, reject) => {
    wx.request({
      url: app.globalData.apiBaseUrl + options.url,
      method: options.method,
      data: options.data || {},
      header,
      success: async (res) => {
        if (res.statusCode === 401 || res.statusCode === 403) {
          // 注意：这里的弹窗逻辑只会在有 token 且 token 失效时触发
          // 无 token 的情况已经在上面直接返回，不会走到这里
          if (app.globalData.loginPromise) {
            try {
              await app.globalData.loginPromise;
              const retryRes = await request(options);
              resolve(retryRes);
            } catch (err) {
              wx.showModal({
                content: '操作失败，请先登录',
                success: (modalRes) => {
                  if (modalRes.confirm) {
                    wx.removeStorageSync('token');
                    wx.switchTab({ url: '/pages/mine/mine' });
                  }
                },
              });
              resolve(res);
            }
            return;
          }

          wx.showModal({
            content: '操作失败，请先登录',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.removeStorageSync('token');
                wx.reLaunch({ url: '/pages/mine/mine' });
              }
            },
          });
          resolve(res);
          return;
        }
        resolve(res);
      },
      fail: reject,
    });
  });
}

export default request;