const baseUrl = 'https://ddbs.1024tool.vip/';
let isNavigatingToLogin = false;
function request(url, method = 'GET', data = {}) {
  const header = {
    'content-type': 'application/json',
    // 有其他content-type需求加点逻辑判断处理即可
  };
  // 获取token，有就丢进请求头
  const tokenString = wx.getStorageSync('access_token');
  if (tokenString) {
    header.Authorization = `${tokenString}`;
  }
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method,
      data,
      dataType: 'json', // 微信官方文档中介绍会对数据进行一次JSON.parse
      header,
      success(res) {
        if (res.data.code) {
          if (res.data.code == 10103) {
            wx.removeStorageSync('access_token');
            if (!isNavigatingToLogin) {
              const pages = getCurrentPages();
              const currentRoute = pages[pages.length - 1]?.route;
              if (currentRoute !== 'pages/login/login') {
                isNavigatingToLogin = true;
                wx.navigateTo({
                  url: '/pages/login/login',
                  complete: () => {
                    isNavigatingToLogin = false;
                  }
                });
              }
            }
            reject(res.data);
          }
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          });
          reject(res.data);
        } else {
          resolve(res.data);
        }

      },
      fail(err) {
        console.log(err)
        // 断网、服务器挂了都会fail回调，直接reject即可
        reject(err);
      },
    });
  });
}

// 导出请求和服务地址
export default request;