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 './styles/element-variables.scss'

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

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

import './icons' // icon
import './permission' // permission control
import './utils/error-log' // error log

import * as filters from './filters' // global filters

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online! ! !
 */
// import { mockXHR } from '../mock'
// if (process.env.NODE_ENV === 'production') {
//   mockXHR()
// }

Vue.use(Element, {
  size: Cookies.get('size') || 'medium' // set element-ui default size
})

// 注册全局过滤器
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

Vue.config.productionTip = false

// 注册全局组件
import Pagination from '@/components/Pagination'
Vue.component('pagination', Pagination)
import TinymceEditor from '@/components/TinymceEditor'
Vue.component('editor', TinymceEditor)

// 注册全局指令
Vue.directive('permit', {
  inserted(el, binding) {
    const { getters } = store
    // 超级管理员拥有所有权限
    if (getters.role === 'root') {
      return false
    }
    try {
      // 获取el上绑定的roles @dataset{Array} roles 该页面所拥有的所有按钮权限
      const roles = el.getAttribute('roles-permit') ? el.getAttribute('roles-permit').split(',') : []
      // 该el对应的权限 强制转为字符串
      const { value } = binding

      if (typeof value === 'string' || typeof value === 'number') {
        // 判断是否存在权限roles 不存在删除元素
        if (roles.indexOf(String(value)) === -1) {
          el.parentNode.removeChild(el)
        }
      } else {
        if (Array.isArray(value)) {
          value.filter(item => {
            return roles.indexOf(String(item)) !== -1
          }).length === 0 ? el.parentNode.removeChild(el) : ''
        } else {
          el.parentNode.removeChild(el)
        }
      }
    } catch (e) {
      // 抛出异常 直接删除元素
      el.parentNode.removeChild(el)
    }
  }
})

// 注册全局自定义快速读取 excel `v-read-excel`
Vue.directive('read-excel', {
  inserted: (el, { value }) => {
    const id = Date.now()
    const input = document.createElement('input')
    el['read-excel-id'] = id
    input.id = id
    input.type = 'file'
    input.accept = '.xlsx, .xls'
    input.style.display = 'none'
    document.body.appendChild(input)
    input.onchange = ({ target: { files: [excel] }}) => {
      try {
        const XLSX = require('xlsx')
        const reader = new FileReader()
        reader.onload = async({ target: { result }}) => {
          const workbook = XLSX.read(result, { type: 'array' })
          value && value(XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]))
        }
        reader.readAsArrayBuffer(excel)
      } catch (e) {
        console.log(e)
        this.$message.error('上传文件失败,请刷新重试')
      }
    }
    el.addEventListener('click', () => {
      input.value = ''
      input.click()
    })
  },
  unbind: el => document.getElementById(el['read-excel-id']).remove()
})

// 注册 EventBus
Vue.prototype.$event = new Vue()

// 注册全局自定义请求方法
Vue.prototype.$request = function(api, fun, conf) {
  this._loading = this.$loading()
  if (api.length) {
    Promise.all(api).then((res) => {
      fun(res.map(e => e.data || {}))
    }).catch(() => this.$message.error((conf && conf.errorMsg) || '操作失败')).finally(() => (conf && conf.endStillLoading) || this._loading.close())
  } else {
    api.then(({ code, message, data }) => { // 发送网络请求
      code === 200 ? fun(data || {}) : this.$message.error(message)
    }).catch(() => {
      // this.$message.error((conf && conf.errorMsg) || '操作失败')
      this._loading.close()
    }).finally(() => (conf && conf.endStillLoading) || this._loading.close())
  }
}

Vue.prototype.$excel = function(list, name) {
  !list.length ? list = [{ '暂无数据': '' }] : ''
  import('@/vendor/Export2Excel').then(excel => {
    excel.export_json_to_excel({
      header: Object.keys(list[0]),
      data: list.map(listItem => Object.keys(list[0]).map(j => listItem[j])),
      filename: name || '下载Excel',
      bookType: 'xlsx'
    })
  })
}

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