import config from '../config';

// 定义token
let token = '';
// 在登录之后设置token
export function setToken(t: string) {
  token = t;
  // 可以选择将token保存到缓存中
  // wx.setStorageSync('token', token)
}
export function clearToken() {
  token = '';
  // wx.setStorageSync('token', '')
}

interface Header {
  'X-Access-Token': string;
}
export function request(method: any = 'GET', url: string, data?: any) {
  return new Promise((resolve, reject) => {
    const header: Header = { 'X-Access-Token': '' };
    if (token) {
      header['X-Access-Token'] = token;
    } else {
      header['X-Access-Token'] = wx.getStorageSync('token');
    }
    wx.request({
      method,
      url: config.baseUrl + url,
      data,
      header,
      success: (res: any) => {
        console.log(res);
        if (res.data.code === 200 || res.data.code === 0) {
          resolve(res.data);
        } else if (res.data.message.includes('token失效')) {
          //重新登录
          wx.removeStorageSync('userInfo');
          wx.removeStorageSync('token');
          wx.removeStorageSync('organName');
          wx.reLaunch({
            url: '/pages/login/login'
          });
        } else {
          resolve(res.data);
          wx.showToast({
            title: res.data.message,
            icon: 'none'
          });
        }
      },
      fail: err => {
        wx.showToast({
          title: '访问失败，请检查当前的网络',
          icon: 'none'
        });
        console.error('请求错误', err);
        reject(err);
      }
    });
  });
}

export const getAction = (url: string, params?: Object) =>
  request('GET', generateUrl(url, params));

export const deleteAction = (url: string, params?: Object) =>
  request('DELETE', generateUrl(url, params));

export const postAction = (url: string, data?: Object) =>
  request('POST', url, data);

export const putAction = (url: string, data?: Object) =>
  request('PUT', url, data);

interface UploadOption {
  name: string;
  filePath: string;
  params?: Object;
}
export function upload(url: string, option: UploadOption) {
  const { name = 'file', filePath, params } = option;
  if (!filePath) throw new Error('filepath-not-found');
  if (!wx.getStorageSync('token')) throw new Error('请先登录！');

  return new Promise((resolve, reject) => {
    const header: any = {
      'Content-Type': 'multipart/form-data',
      'X-Access-Token': ''
    };
    if (token) {
      header['X-Access-Token'] = token;
    } else {
      header['X-Access-Token'] = wx.getStorageSync('token');
    }
    wx.uploadFile({
      url: config.baseUrl + url,
      filePath,
      name,
      formData: params,
      header,
      success: resolve,
      fail: err => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
        console.error('请求错误', err.errMsg);
        reject(err);
      }
    });
  });
}

const generateUrl = (url: string, params?: any) => {
  if (!params) return url;

  const keys = Object.keys(params);
  if (keys.length < 1) return url;

  return (
    url +
    keys.reduce((res, it, idx) => {
      if (typeof params[it] !== 'undefined') {
        return `${res}${idx > 0 ? '&' : ''}${it}=${params[it]}`;
      }
      return res;
    }, '?')
  );
};
