import Taro from '@tarojs/taro';

export const BASE_URL = process.env.TARO_APP_API;

interface Res<T> {
  code: number;
  data: T;
  msg: string;
}

type Method = 'GET' | 'POST' | 'PUT' | 'DELETE';

// 忽略系统提示白名单
const IGNORED_TIPS = ['/user/find/phone', '/user/check/payPassword'];

const request = (
  url: string,
  data: object = {},
  method: Method = 'GET',
): Promise<Res<any>> => {
  return new Promise((resolve, reject) => {
    Taro.request({
      url: BASE_URL + url,
      data: data,
      method: method,
      header: {
        'content-type': 'application/json',
        token: Taro.getStorageSync('token') || '',
      },
      success: ({data}) => {
        if (data.code !== 200) {
          if (!IGNORED_TIPS.includes(url)) {
            Taro.showToast({
              title: data.msg,
              icon: 'none',
            });
          }
          reject(data);
        } else {
          resolve(data);
        }
      },
      fail: err => {
        reject(err);
      },
    });
  });
};

export default request;
