/*
  支持预览格式有：
    content:内容,
    special:专题,
    ADPosition:广告,
    ImagePlayer:图片播放器
    Vote:调查广告
*/
import _ from 'lodash'
import Vue from 'vue'
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 util from './common/util.js'

import special from './pages/special/preview.vue'
import content from './pages/contentcore/preview.vue'
import advertise from './pages/advertise/atverdisePreview.vue'
import imageplayer from './pages/imageplayer/imagePlayerPreview.vue'
import vote from './pages/vote/preview.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.response.use(res => {
  return res
}, err => {
  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
  }
  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)
  }
  window.renderDom = function () {
    let type = util.url.getQueryValue(location.href, 'type')
    type = type.toLowerCase()
    if (type === 'special') {
      return special
    } else if (type === 'adposition') {
      return advertise
    } else if (type === 'imageplayer') {
      return imageplayer
    } else if (type === 'vote') {
      return vote
    }
    return content
  }
  window.app = new Vue({
    el: '#preview',
    render: h => h(window.renderDom())
  })
}
window.appInit()
