import router from '@/router'
import axios from 'axios'
import qs from 'qs'
import Vue from 'vue'
import Cookies from 'js-cookie'
import {
  Dialog,
  Toast,
  Notify
} from 'vant'
Vue.use(Dialog).use(Toast).use(Notify)

// create an axios instance
const request = axios.create({
  baseURL: process.env.BASE_API, // api的base_url
  timeout: 10000,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  transformRequest: [function(data) {
    // 对 data 进行任意转换处理
    return qs.stringify(data)
  }]
})

request.interceptors.request.use(
  config => {
    var token = localStorage.getItem('a-token-temp');
    config.headers['A-Token'] = token || ''
    return config
  },
  error => {
    Promise.reject(error)
  }
)

request.interceptors.response.use(
  response => {
    if (response.data.code === 1) {
      if (response.data.refresh_token) {
        if (response.data.refresh_token != localStorage.getItem('a-token-temp')) {
          localStorage.setItem('a-token-temp', response.data.refresh_token)
        }
      }
      return response
    } else if (response.data.code === 401) {
      Dialog.alert({
        message: '当前登录授权时间已经过期，请重新授权登录',
      }).then(() => {
        if (window.plus) {
          plus.storage.clear()
          Cookies.remove('Admin-Token')
        } else {
          window.localStorage.clear()
          Cookies.remove('Admin-Token')
        }
        router.push({
          name: 'login'
        })
      });
    } 
    else if (response.data.code === 0) {
      Notify({
        message: response.data.msg,
        color: '#ad0000',
        background: '#d1d1d1',
      });
      return Promise.reject('error')
    } else if (response.data.code === 2001) {
      Notify({
        message: response.data.msg,
        color: '#ad0000',
        background: '#ffe1e1',
      });
      return Promise.reject('error')
    } else if (response.data.code === 999) {
      Notify({
        message: response.data.msg,
        color: '#ad0000',
        background: '#ffe1e1',
      });
      return Promise.reject('error')
    } else if (response.data.code === 3000) {
      Notify({
        message: '服务暂时不可用，请稍后重试，或联系客服',
        color: '#ad0000',
        background: '#ffe1e1',
      });
      return Promise.reject('error')
    }else if (response.data.code === 4444) { //系统过期
       Dialog.alert({
         title: '系统已到期',
         message: "请在功道云积分服务群中联系客服顾问或电话咨询：<span class='color-blue'>400-6877-880</span>",
         theme: 'round-button',
       }).then(() => {
         if (window.plus) {
           plus.storage.clear()
           Cookies.remove('Admin-Token')
         } else {
           window.localStorage.clear()
           Cookies.remove('Admin-Token')
         }
         router.replace({name: 'login'});
       });
     }else {
      return response
    }
  },
  error => {
    if (error.message == 'interrupt') {
      return Promise.reject(error.message)
    }
    return Promise.reject(error)
  }
)

// 接口再次封装
var CancelToken = axios.CancelToken;
Vue.$httpRequestList = [];
export default (type, url, data, heaStr) => {
  var Accept, Token = '';
  switch (heaStr) {
    case 'v2':
      Accept = 'application/vnd.test.v2+json'
      break;
    case 'v3':
      Accept = 'application/vnd.test.v3+json'
      break;
    case 'token':
      Token = localStorage.getItem('a-token-temp');
      break;
  }
  return new Promise((resolve, reject) => { //封装ajax
    var aa = {
      method: type,
      url: url,
      headers: {
        'Accept': Accept,
        'A-Token': Token
      },
      cancelToken: new CancelToken(c => { //强行中断请求要用到的
        Vue.$httpRequestList.push(c);
      })
    }
    var json = (type == 'get') ? Object.assign(aa, {
      params: data
    }) : Object.assign(aa, {
      data: data
    });
    var ajax = request(json).then(res => {
      resolve(res);
    }).catch(error => { //中断请求和请求出错的处理
      if (error == "interrupt") {
        return;
      } else {
        reject(error);
      }
    })
    return ajax;
  })
};
