// utils/request.js
const app = getApp();

function request(options) {
  const token = wx.getStorageSync('token');
  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) {
          // 如果当前正在执行静默登录，等待登录完成后重试一次
          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.reLaunch({ url: '/pages/wode/wode' });
                  }
                },
              });
              resolve(res);   // 返回原始响应让调用方知晓
            }
            return;
          }

          // 无登录流程进行中，直接弹窗（原逻辑）
          wx.showModal({
            content: '操作失败，请先登录',
            success: (modalRes) => {
              if (modalRes.confirm) {
                wx.removeStorageSync('token');
                wx.reLaunch({ url: '/pages/wode/wode' });
              }
            },
          });
          resolve(res);
          return;
        }
        // 正常响应
        resolve(res);
      },
      fail: reject,
    });
  });
}

export default request;