const BASE_URL = 'https://a.bianyifang.com'; // 统一接口域名

function request({ loading = true, url, method = 'GET', data = {}, header = {} }) {
  return new Promise((resolve, reject) => {
    if (loading) {
      wx.showLoading({
        title: '加载中...',
        mask: true
      });
    }
    wx.request({
      url: BASE_URL + url,
      method,
      data,
      header: {
        'content-type': 'application/json',
        'Authorization': wx.getStorageSync('token') || '',
        ...header
      },
      timeout: 10000,
      success(res) {
        if (loading) wx.hideLoading();
        if (res.statusCode === 200) {
          resolve(res.data);
        } else {
          wx.showToast({
            title: res.data?.message || '请求错误',
            icon: 'none',
            duration: 2000
          });
          reject(res.data);
        }
      },
      fail(err) {
        if (loading) wx.hideLoading();
        wx.showToast({
          title: '网络异常，请重试',
          icon: 'none',
          duration: 2000
        });
        reject(err);
      }
    });
  });
}

export default request;
