import axios from 'axios'
import router from '@/router'
import {
  getToken,
  getUserId,
  setToken
} from '@/utils/auth'
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)


const service = 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)
  }]
})

var bool = true; //五秒执行一次变量
service.interceptors.request.use(
  config => {
    if (getToken()) {
      config.headers['A-Token'] = getToken()
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.data.code === 1) {
      if (response.data.refresh_token) {
        if (response.data.refresh_token !== getToken()) {
          localStorage.setItem('Admin-Token', response.data.refresh_token)
        }
      }
      var timestamp = parseInt((new Date()).valueOf() / 1000)
      if (window.plus) {
        var temp_timestamp = plus.storage.getItem('token-expire')
        if (temp_timestamp < timestamp && response.data.refresh_token) {
          setToken(response.data.refresh_token)
          plus.storage.setItem('token-expire', timestamp + 7200)
        }
      } else {
        var temp_timestamp = localStorage.getItem('token-expire')
        if (temp_timestamp < timestamp && response.data.refresh_token) {
          setToken(response.data.refresh_token)
          localStorage.setItem('token-expire', timestamp + 7200)
        }
      }
      return response
    } else if (response.data.code === 401) {
      if (window.plus) {
        plus.storage.clear()
      } else {
        localStorage.clear()
      }
      Cookies.remove('Admin-Token')
      window.location.href = process.env.BASE_API //直接重新授权
    } 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) { //系统过期
      console.log(response)
      if (window.plus) {
        plus.storage.clear()
      } else {
        localStorage.clear()
      }
      router.push({
        path: '/noAccess',
        query: {
          msg: response.data.msg
        }
      })
      return Promise.reject('error')
    } else {
      return response
    }
  },
  error => {
    if (error.message == 'interrupt') {
      return Promise.reject(error.message)
    }
    //五秒内只执行一次
    if (bool) {
      if (error.message == 'timeout of 10000ms exceeded') {
        Notify({
          type: 'warning',
          message: "网络连接超时，请稍后重试",
          duration: 3000,
        });
      }
      if (error.message == 'Network Error') {
        Notify({
          type: 'danger',
          message: "网络连接失败，请检查您的网络",
          duration: 3000,
        });
      }
      bool = false
      setTimeout(() => {
        bool = true
      }, 5000)
    }
    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 'v4':
      Accept = 'application/vnd.test.v4+json'
      break;
  }
  return new Promise((resolve, reject) => { //封装ajax
    var aa = {
      method: type,
      url: url,
      headers: {
        'Accept': Accept
      },
      cancelToken: new CancelToken(c => { //强行中断请求要用到的
        Vue.$httpRequestList.push(c);
      })
    }
    var json = (type == 'get') ? Object.assign(aa, {
      params: data
    }) : Object.assign(aa, {
      data: data
    });
    var ajax = service(json).then(res => {
      resolve(res);
    }).catch(error => { //中断请求和请求出错的处理
      if (error == "interrupt") {
        return;
      } else {
        reject(error);
      }
    })
    return ajax;
  })
};
