/* global localStorage */
import _ from 'lodash'
import Vue from 'vue'
import VueRouter from 'vue-router'
import axios from 'axios'
import ELEMENT from 'element-ui'

import config from './config/index.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 ContentEditor from './pages/contentcore/contentEditor.vue'

Vue.use(VueRouter)
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.response.use(res => {
  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(window.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.refreshOpenerContentList = _ => {
  // 更新父窗口内容列表
  let topOpener = (_ => {
    let top = window
    while (top.opener) {
      top = top.opener
    }
    return top
  })()
  if (topOpener) {
    topOpener.refreshContentList && topOpener.refreshContentList()
  }
}
window.DetailComponents = []
window.appInit = async function () {
  let appBeforeInstantiate = document.createEvent('Event')
  appBeforeInstantiate.initEvent('appbeforeinstantiate', true, true)
  document.dispatchEvent(appBeforeInstantiate)
  const router = new VueRouter({
    mode: 'hash',
    routes: [{
      path: '/contentEditor/:id',
      name: 'contentEditor',
      component: ContentEditor
    }]
  })
  let res = await axios.get('/ui/sites')
  let siteID = res.data.siteID || 0
  let prefix = res.data.prefix || ''
  let siteName = res.data.siteName || ''
  let siteURL = res.data.siteURL || ''
  let platformAttributes = res.data.platformAttributes

  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)
  }

  window.document.title = `${localStorage._appCode + '-' + localStorage._appName}`

  /* eslint-disable no-new */
  new Vue({
    data: {
      siteID,
      prefix,
      siteURL,
      siteName,
      platformAttributes,
      isRouterAlive: true
    },
    beforeCreate () {
      window.app = this
    },
    methods: {
      reload() {
        this.isRouterAlive = false
        this.$nextTick(() => {
          this.isRouterAlive = true
        })
      }
    },
    el: '#root',
    router: router,
    template: '<router-view :key="$route.name" v-if="isRouterAlive"></router-view>'
  })
}
window.addEventListener('load', window.appInit, false)
