import ElementUI from 'element-ui'
import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import qs from 'querystring'
import { getToken } from '@/utils/auth'
import cleanDeep from 'clean-deep'
// import { Loading } from 'element-ui'
import load from '@/utils/loading'
import router from '@/router/index'
import Vue from 'vue'
const showMessage = Symbol('showMessage')
class DonMessage {
  success (options, single = true) {
    this[showMessage]('success', options, single)
  }
  warning (options, single = true) {
    this[showMessage]('warning', options, single)
  }
  info (options, single = true) {
    this[showMessage]('info', options, single)
  }
  error (options, single = true) {
    this[showMessage]('error', options, single)
  }
  [showMessage] (type, options, single) {
    if (single) {
      // 判断是否已存在Message
      if (document.getElementsByClassName('el-message').length === 0) {
        Message[type](options)
      }
    } else {
      Message[type](options)
    }
  }
}

Vue.use(ElementUI)
// 命名根据需要，DonMessage只是在文章中使用
Vue.prototype.$message = new DonMessage()

let vue = new Vue()

// let loading        //定义loading变量

// function startLoading () {    //使用Element loading-start 方法
//   loading = Loading.service({
//     lock: true,
//     fullscreen: true,
//     text: '加载中……',
//     background: 'rgba(0, 0, 0, 0.7)'
//   })
// }
// function endLoading () {
//   //使用Element loading-close 方法
//   loading.close();
// }
//那么 showFullScreenLoading() tryHideFullScreenLoading() 要干的事儿就是将同一时刻的请求合并。
//声明一个变量 needLoadingRequestCount，每次调用showFullScreenLoading方法 needLoadingRequestCount + 1。
//调用tryHideFullScreenLoading()方法，needLoadingRequestCount - 1。needLoadingRequestCount为 0 时，结束 loading。
let needLoadingRequestCount = 0
function showFullScreenLoading () {
  if (needLoadingRequestCount === 0) {
    load.startLoading()
  }
  needLoadingRequestCount++

}

function tryHideFullScreenLoading () {
  if (needLoadingRequestCount <= 0) return
  needLoadingRequestCount--
  if (needLoadingRequestCount === 0) {
    load.endLoading();

  }

}

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';


// create an axios instance
const service = axios.create({
  baseURL: '', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 180000, // request timeout
})
// { fullscreen: true, text: '努力加载中', spinner: 'el-icon-loading' }
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    showFullScreenLoading()
    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = getToken()
    }
    if (config.requestType === 'form') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
      config.data = qs.stringify(cleanDeep(config.data))
    } else {
      config.data = cleanDeep(config.data)
    }
    config.params = cleanDeep(config.params)
    return config
  },
  error => {
    // do something with request error
    tryHideFullScreenLoading()
    return Promise.reject(error)

  }
)

// response interceptor
service.interceptors.response.use(
  res => {
    //res.code !== 200
    if (res.data) {
      let data = JSON.parse(JSON.stringify(res.data))
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (data.code == 401 || data.code == 403) {
        // Message({
        //   message: `登录过期，请重新登录！`,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        vue.$message.error(`登录过期，请重新登录！`)
        setTimeout(() => {
          tryHideFullScreenLoading()
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        }, 1000);
        return;
      }
      if (data.code == 404) {
        router.push('/404')
      }
      if (data.code != 200) {
        // Message({
        //   message: data.msg || `请求失败code码为${ data.code }`,
        //   type: 'error',
        //   duration: 5 * 1000
        // })
        let str = data.msg || `请求失败code码为${data.code}`
        if (res.config.hint !== true) {
          vue.$message.error(str)
        }
        tryHideFullScreenLoading()
        return Promise.reject(data)
      } else {
        tryHideFullScreenLoading()
        return data

      }
    } else {

      tryHideFullScreenLoading()
      return Promise.reject()
    }
  },
  error => {
    if (error.message == 'Network Error') {
      vue.$message.error('网络异常，请检查网络连接')
    } else {
      vue.$message.error(error.message)
    }
    tryHideFullScreenLoading()
    return Promise.reject(error)
  }
)
export default service
