import Axios from 'axios';
import { Toast } from 'vant';
import { API_CONFIG, REPONSE_CODE } from '@/utils/enumerate';

const { VUE_ENV } = process.env; // server or client
const cookies = require('cookie-universal')();

Axios.interceptors.request.use(
  config => {
    // 0. Do something before request is sent
    // 1. can be add loading
    // 2. make sure if need token
    const method = config.method.toLocaleLowerCase();
    if (method === 'post' || method === 'put' || method === 'delete') {}
    if (config.withCredentials) {
      config.headers.token = cookies.get('token') || sessionStorage.getItem('token');
    }
    return config;
  },
  error => {
    // when set loading close it    
    if (
      error.code === 'ECONNABORTED' &&
      error.message.indexOf('timeout') !== -1
    ) {
      VUE_ENV === 'client' && Toast({ message: '请求超时', duration: 1000 });
    }
    return Promise.reject(error);  
  }
)

export default function(options) {
  if (typeof options !== 'object') {
    throw new Error('make sure the params options is an Object...');
  }
  
  const cf = JSON.parse(JSON.stringify(API_CONFIG));
  options = Object.assign(cf, options); // 合并 config
  return new Promise((resolve, reject) => {
    Axios(options)
      .then(res => {        
        const { status, data } = res;

        if (status !== 200) {
          let cmsg = REPONSE_CODE[status];
          let message = cmsg !== undefined ? cmsg : '系统异常。';

          throw Error(message);
        }
        
        if (!data) throw Error('axios reponse data in not defined.');
        if (data.code != '000000') {
          // 如果要是有其他特殊需求在此处添加
          console.log(`调用后台接口报错，CODE: ${data.code}，MESSAGE: ${data.message}。`);
        }
        resolve(res.data);
      })
      .catch(error => {
        console.log('axios catch error: ', error.message);
        VUE_ENV === 'client' && Toast({ message: error.message, duration: 1000 });
        // reject(error);
      })
  })
}