import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n

import '@/styles/index.scss' // global css

import moment from 'moment'

import App from './App'
import store from './store'
import router, { resetRouter } from './router'
import '@/icons' // icon
import '@/permission' // permission control
import axios from 'axios'

import { MessageBox, Message } from 'element-ui'

import { getToken, removeToken } from './utils/auth'
import { getBrowserToken } from './utils/commonFuc' // get token from cookie

import 'xe-utils'
import VXETable from 'vxe-table'
import 'vxe-table/lib/index.css'
import XEUtils from 'xe-utils'

Vue.prototype.$XEUtils = XEUtils
Vue.use(VXETable)
Vue.prototype.$moment = moment

import echarts from 'echarts'
import dataV from '@jiaminghi/data-view'

Vue.use(dataV)
Vue.prototype.$echarts = echarts

import _ from 'lodash'
Vue.prototype._ = _

/* import 'vue2-animate/dist/vue2-animate.min.css'*/

import animate from 'animate.css'
Vue.use(animate)

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
/* if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}*/

// set ElementUI lang to EN
Vue.use(ElementUI, { locale })
// 如果想要中文版 element-ui，按如下方式声明
// Vue.use(ElementUI)

Vue.config.productionTip = false
Vue.prototype.$axios = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 1000 * 60 * 10 // request timeout
})

Vue.prototype.$axios.interceptors.request.use(
  config => {
    if (getBrowserToken()) { // 判断是否存在token，如果存在的话，则每个http header都加上token
      config.headers['Authorization'] = getBrowserToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// // response interceptor
// Vue.prototype.$axios.interceptors.response.use(
//   /**
//    * If you want to get http information such as headers or status
//    * Please return  response => response
//    */
//
//   /**
//    * Determine the request status by custom code
//    * Here is just an example
//    * You can also judge the status by HTTP Status Code
//    */
//   response => {
//     const res = response.data
//     if (!res.data) {
//       return response
//     }
//     // if the custom code is not 20000, it is judged as an error.
//     if (res.code !== 0) {
//       Message({
//         message: res.message || 'Error',
//         type: 'error',
//         duration: 5 * 1000
//       })
//
//       return Promise.reject(new Error(res.message || 'Error'))
//     } else {
//       return res
//     }
//   },
//   error => {
//     if (error.response) {
//       switch (error.response.status) {
//         case 401:
//           console.log('用户验证失败！')
//           // 返回 401 清除token信息并跳转到登录页面
//           removeToken()
//           resetRouter()
//           Message({
//             message: error.response.data.data,
//             type: 'error',
//             duration: 5 * 1000
//           })
//           break
//         case 403:
//           console.log('登录超时！')
//           // 返回 401 清除token信息并跳转到登录页面
//           removeToken()
//           resetRouter()
//           router.push('/login')
//           Message({
//             message: '登录超时',
//             type: 'error',
//             duration: 5 * 1000
//           })
//           break
//         case 500:
//           Message({
//             message: '服务器关闭了！请联系相关工作人员',
//             type: 'error',
//             duration: 5 * 1000
//           })
//           removeToken()
//           resetRouter()
//           router.push('/login')
//           break
//         case 504:
//           console.log('服务器关闭了！')
//           resetRouter()
//           break
//       }
//     }
//     /*    console.log('err' + error) // for debug
//     Message({
//       message: error.message,
//       type: 'error',
//       duration: 5 * 1000
//     })*/
//     return Promise.reject(error)
//   }
// )


// response interceptor
Vue.prototype.$axios.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 处理下载文件
    if (response.headers && response.headers['content-type'] && (response.headers['content-type'].indexOf('application/x-msdownload') != -1)) {
      // 创建一个blob对象,file的一种
      const blob = new Blob([response.data], {type: response.headers['content-type']})
      const fileName = decodeURI(response.headers['content-disposition'].split('=')[1])
      if (window.navigator.msSaveOrOpenBlob) {
        // 兼容IE10
        navigator.msSaveBlob(blob, fileName)
      } else {
        // 非IE下载
        const elink = document.createElement('a')
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      }

      response.data = ''
      response.headers['content-type'] = 'text/json'
      return response
    } else {
      const res = response.data
      // if the custom code is not 20000, it is judged as an error.

      if (res.code !== 0) {
        Message({
          message: res.message || 'Error',
          type: 'error',
          duration: 5 * 1000
        })

        // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
        if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
          // to re-login
          MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
            confirmButtonText: 'Re-Login',
            cancelButtonText: 'Cancel',
            type: 'warning'
          }).then(() => {
            store.dispatch('user/resetToken').then(() => {
              location.reload()
            })
          })
        }
        return Promise.reject(new Error(res.message || 'Error'))
      } else {
        return res
      }
    }
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          console.log('用户验证失败！')
          // 返回 401 清除token信息并跳转到登录页面
          removeToken()
          resetRouter()
          Message({
            message: error.response.data.data,
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 403:
          console.log('登录超时！')
          // 返回 401 清除token信息并跳转到登录页面
          removeToken()
          resetRouter()
          router.push('/login')
          Message({
            message: '登录超时',
            type: 'error',
            duration: 5 * 1000
          })
          break
        case 500:
          Message({
            message: '服务器关闭了！请联系相关工作人员',
            type: 'error',
            duration: 5 * 1000
          })
          removeToken()
          resetRouter()
          router.push('/login')
          break
        case 504:
          console.log('服务器关闭了！')
          resetRouter()
          break
      }
    }
    /*    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })*/
    return Promise.reject(error)
  }
)

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
