import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets
import Editor from 'bin-ace-editor';
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 { showLoading, hideLoading } from '@/api/loading'
import JsonViewer from 'vue-json-viewer';
Vue.use(JsonViewer);
import echarts from 'echarts'
// 按需引入需要的语言包皮肤等资源
require('brace/ext/emmet'); // 如果是lang=html时需引入
require('brace/ext/language_tools'); // language extension

require('brace/mode/sql');
require('brace/snippets/sql');
require('brace/theme/chrome');
// 注册组件后即可使用
Vue.component(Editor.name, Editor);
Vue.prototype.$echarts = echarts
Vue.use(Element, {
  size: 'small', // set element-ui default size
  i18n: (key, value) => i18n.t(key, value)
})

// 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 => {
    // showLoading()
    var xtoken = getToken()
    // console.log('axios interceptor request')
    if (xtoken != null) {
      config.headers['token'] = xtoken
    }
    return config
  }, function(error) {
    return Promise.reject(error)
  }
)
Vue.directive('debounce', {
  "inserted": function (el, bingding, vnode) {
    let time = null;
    el.addEventListener('click', function () {
      if (time) {
        clearTimeout(time);
      }
      el.disabled = true;
      if (vnode.componentInstance) {
        vnode.componentInstance.loading = true;
        vnode.componentInstance.disabled = true;
      }
      time = setTimeout(() => {
        el.disabled = false;
        if (vnode.componentInstance) {
          vnode.componentInstance.loading = false;
          vnode.componentInstance.disabled = false;
        }
      }, bingding.value || 500);
    });
  }
});

axios.interceptors.response.use(function(response) {
  // hideLoading()
  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)
})
