import config from '../config.js';
const getDomain = (uri, method, type) => {
  let wx_env = config.wx_miniProgram;
  let system = config.system;
  let url = config.serverUrl;
  if (type && type == 'file') return url + `/files` + uri;
  if (type && type == 'integral') return url + `/point/zr/v1/api` + uri;
  if (uri.startsWith('/wechat/api')) return url + uri;
  else {
    if (system.uniPlatform == 'app') {
      return url + `/point/v1/api` + uri;
    } else if (system.uniPlatform == 'mp-weixin') {
      if (wx_env.envVersion == 'develop' || wx_env.envVersion == 'trial') {
        return url + `${config.wx_dev}/point/v1/api` + uri;
      } else if (wx_env.envVersion == 'release') {
        return url + '/point/v1/api' + uri;
      }
    }
  }
};
// 获取token
const getToken = () => {
  try {
    const value = uni.getStorageSync('token');
    if (value) return value;
  } catch {}
};
// 获取请求key
const getRequestKey = (uri, method, data) => {
  let baseUrl = getDomain('/util/crk');
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl,
      method: 'POST',
      data: { uri, method, data },
      success: (res) => {
        if (res.data && res.data.data) resolve(res.data.data);
        else reject();
      },
      fail: (err) => {
        reject(err.data);
      },
    });
  });
};

export const requestBase = async (uri, method = 'GET', data, type) => {
  let baseUrl = getDomain(uri, method, type);
  let token = getToken();
  let header = {};
  if (method !== 'GET') {
    let rk = await getRequestKey(uri, method, data);
    header.rk = rk;
  }
  if (token) header.token = token;
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl,
      method: method || 'GET',
      data: data || {},
      header,
      success: (res) => {
        resolve(res.data);
      },
      fail: (err) => {
        console.log(err);
        uni.showToast({
          title: '请求接口失败',
          icon: 'fail',
        });
        reject(err.data);
      },
    });
  });
};
export const requestFile = (uri, method, data, type) => {
  let baseUrl = getDomain(uri, method, type);
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: baseUrl,
      filePath: data,
      name: method || 'file',
      formData: {},
      success: (res) => {
        let data = JSON.parse(res.data);
        if (data.errcode != '0') {
          return uni.showToast({
            title: data.errmsg,
            icon: 'error',
          });
        }
        resolve(data);
      },
      fail: (err) => {
        let data = JSON.parse(err.data);
        uni.showToast({
          title: '请求接口失败',
          icon: 'fail',
        });
        reject(data);
      },
    });
  });
};
