import Vue from 'vue'

import Cookies from 'js-cookie'

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

import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

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

import App from './App'
import store from './store'
import router from './router'

import i18n from './lang' // Internationalization
import './icons' // icon
import './errorLog' // error log
import './permission' // permission control
import axios from 'axios'
import 'babel-polyfill'
import 'url-search-params-polyfill'
import { getToken, setToken } from '@/utils/auth'
import * as filters from './filters' // global filters
import 'lib-flexible'
import BaiduMap from 'vue-baidu-map'

Vue.use(Element, {
  size: Cookies.get('size') || 'medium', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value)
})

Vue.use(BaiduMap, {
  // ak 是在百度地图开发者平台申请的密钥 详见 http://lbsyun.baidu.com/apiconsole/key */
  ak: 'ro9mKI7I7N1Zk5DadSsmYSqMU5qxnEKG'
})
// register global utility filters.
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})
axios.defaults.withCredentials = true
Vue.config.productionTip = false

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

axios.interceptors.request.use(
  config => {
    var xtoken = getToken()
    // console.log('axios interceptor request')
    if (xtoken != null) {
      config.headers['token'] = xtoken
    }
    return config
  }, function(error) {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(function(response) {
  if (response.headers.sessiontimeout === 'true') {
    var data = {}
    data.code = 10001
    data.message = '登录已超时，请重新登录'
    response.data = data
    setToken('')
    router.replace({
      path: '/login',
      query: { redirect: router.currentRoute.fullPath }
    })
  }
  return response
}, function(error) {
  // Do something with response error
  return Promise.reject(error)
})
