
import _ from 'lodash'
import Vue from 'vue'
import axios from 'axios'
import ELEMENT from 'element-ui'

import config from './config/index.js'
import util from './common/util.js'
import Privilege from './common/privilege.js'
import components from './components/index.js'
import directives from './directives/index.js'
import filters from './filters/index.js'
import MixinELEMENT from './mixins/index.js'

import commonDemo from './pages/common/zcmsComponentsDemo.vue'

Vue.use(MixinELEMENT)
Vue.use(ELEMENT)
Vue.use(components)
Vue.use(directives)
Vue.use(filters)

if (process.env.NODE_ENV === 'development') {
  Vue.config.devtools = true
}
_.merge(axios.defaults, config.axios)
// axios.interceptors.request.use(req => {
//   req.params.referer = window.location.href
//   return req
// })
axios.interceptors.response.use(res => {
  // 如果是post请求，更新用户的权限
  if (res.config.method === 'post') {
    axios.get('/ui/application/privs').then(res => new Privilege((res && res.data && res.data.data) || {}))
  }
  return res
}, err => {
  if (err.message.includes('code 403')) {
    util.showErrorNotification('用户没有该模块的权限！')
    return
  }
  if (err.message.includes('code 401')) {
    if (err.response.data.loginURL) {
      window.location.href = err.response.data.loginURL + encodeURIComponent(location.href)
      return
    }
    window.location.href = 'index.html'
    return
  }
  if (err.message.includes('code 500')) {
    util.showErrorMessageBox('服务器发生500异常，未获取到数据！')
  }
  if (err.message === 'Network Error') {
    util.showErrorMessageBox('网络错误，请检查网络是否通畅、或者服务器地址设置正确,设置服务器地址可以自行到登录页面设置.')
  }
  return Promise.reject(new Error(err))
})

window.appInit = async function () {
  let res = await axios.get('/ui/application/privs')
  let privilege = new Privilege((res && res.data && res.data.data) || {})
  if (!res || !res.data) {
    console.warn('没有通过接口 /ui/application/privs 取到当前用户的权限配置', privilege)
  }
  let appBeforeCreateEvent = document.createEvent('Event')
  appBeforeCreateEvent.initEvent('appbeforecreate', true, true)
  let appCreatedEvent = document.createEvent('Event')
  appCreatedEvent.initEvent('appcreated', true, true)
  let appBeforeMountEvent = document.createEvent('Event')
  appBeforeMountEvent.initEvent('appbeforemount', true, true)
  let appMountedEvent = document.createEvent('Event')
  appMountedEvent.initEvent('appmounted', true, true)

  window.app = new Vue({
    data: {
    },
    beforeCreate () {
      window.app = this
      document.dispatchEvent(appBeforeCreateEvent)
    },
    created () {
      document.dispatchEvent(appCreatedEvent)
    },
    beforeMount () {
      document.dispatchEvent(appBeforeMountEvent)
    },
    mounted () {
      document.dispatchEvent(appMountedEvent)
    },
    methods: {

    },
    el: '#zcmsCommonDemo',
    render: h => h(commonDemo)
  })
}
window.addEventListener('load', window.appInit, false)
