import { createApp } from 'vue'

import Cookies from 'js-cookie'

import ElementPlus from 'element-plus'
import locale from 'element-plus/lib/locale/lang/zh-cn' // 中文语言
import { ElMessageBox } from 'element-plus'

import '@/assets/styles/index.scss' // global css
import '@/assets/styles/page.scss' // global css
import App from './App'
import store from './store'
import router from './router'
import directive from './directive' // directive
import { getToken,setToken } from '@/utils/auth'
import { getQueryObject } from '@/utils'
import useUserStore from '@/store/modules/user'

// 注册指令
import plugins from './plugins' // plugins
import request from '@/utils/request'
import { download,downloadBy } from '@/utils/request'

// svg图标
import 'virtual:svg-icons-register'
import SvgIcon from '@/components/SvgIcon'
import elementIcons from '@/components/SvgIcon/svgicon'

import VXETable from 'vxe-table'
import 'vxe-table/lib/style.css'

import lodash from 'lodash'

// 如果您正在使用CDN引入，请删除下面一行。
// import * as ElementPlusIconsVue from '@element-plus/icons-vue'

import './permission' // permission control

import gmComponent from './benyun/plugins/registerComponent' //组件注册

import { useDict } from '@/utils/dict'
import { getConfigKey, updateConfigByKey } from "@/api/system/config";
import { parseTime, resetForm, addDateRange, handleTree, selectDictLabel, selectDictLabels } from '@/utils/ruoyi'

// 分页组件
import Pagination from '@/components/Pagination'
// 自定义表格工具组件
import RightToolbar from '@/components/RightToolbar'
// 富文本组件
import Editor from "@/components/Editor"
// 文件上传组件
import FileUpload from "@/components/FileUpload"
// 图片上传组件
import ImageUpload from "@/components/ImageUpload"
// 图片预览组件
import ImagePreview from "@/components/ImagePreview"
// 自定义树选择组件
import TreeSelect from '@/components/TreeSelect'
// 字典标签组件
import DictTag from '@/components/DictTag'
// 地图
import mapMaker from '@/components/mapMaker'
//上传
import ByUpload from '@/components/upload/upload'

const app = createApp(App)

// for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
//   app.component(key, component)
// }

// 全局方法挂载
app.config.globalProperties.useDict = useDict
app.config.globalProperties.getConfigKey = getConfigKey
app.config.globalProperties.updateConfigByKey = updateConfigByKey
app.config.globalProperties.download = download
app.config.globalProperties.downloadBy = downloadBy
app.config.globalProperties.parseTime = parseTime
app.config.globalProperties.resetForm = resetForm
app.config.globalProperties.handleTree = handleTree
app.config.globalProperties.addDateRange = addDateRange
app.config.globalProperties.selectDictLabel = selectDictLabel
app.config.globalProperties.selectDictLabels = selectDictLabels
app.config.globalProperties.request = request
app.config.globalProperties.lodash = lodash

// 全局组件挂载
app.component('DictTag', DictTag)
app.component('Pagination', Pagination)
app.component('TreeSelect', TreeSelect)
app.component('FileUpload', FileUpload)
app.component('ImageUpload', ImageUpload)
app.component('ImagePreview', ImagePreview)
app.component('RightToolbar', RightToolbar)
app.component('Editor', Editor)
app.component('MapMaker', mapMaker)
app.component('ByUpload',ByUpload)


app.use(gmComponent)

function useTable (app) {
  app.use(VXETable)
}
app.use(useTable)

app.use(router)
app.use(store)
app.use(plugins)
app.use(elementIcons)
app.component('svg-icon', SvgIcon)

directive(app)

// 使用element-plus 并且设置全局的大小
app.use(ElementPlus, {
  locale: locale,
  // 支持 large、default、small
  size: Cookies.get('size') || 'default'
})

// 修改 el-dialog 默认点击遮照为不关闭
app._context.components.ElDialog.props.closeOnClickModal.default = false

const importJS = () => { // 引入 "天地图"
  return new Promise((resolve) => {
    // const key = process.env.TMAP_KEY
    // const url = `http://api.tianditu.gov.cn/api?v=4.0&tk=873e4a15f0f80945cd0ba56f069c19bc`

    const importHandle = url => {
      const head = document.getElementsByTagName('head')[0]
      const script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = url
      script.onload = function() {
        resolve(true)
      }
      script.onerror = () => {
        resolve(false)
      }
      head.appendChild(script)
    }
    let key = import.meta.env.VITE_APP_TIANDIKEY
    importHandle('https://api.tianditu.gov.cn/api?v=4.0&tk=' + key)
    importHandle('/static/js/xlsx.full.min.js')

  })
  
}


const omsLogin = () => {
  // return new Promise((resolve) => {
    let params = getQueryObject();
    console.log('参数', params)
    const ticket = params.ticket;
    const ssoToken = params.ssoToken;
    if(ticket || ssoToken){
      let data = {}
      const url = ticket ? '/sso/doLoginByTicket' : '/sso/doLoginByToken'
      if(ticket) {
        data.ticket = ticket
      }
      if(ssoToken) {
        data.token = ssoToken
      }
      useUserStore().getTokenHandle({url:url,data:data})
      // request({
      //   url: url,
      //   method:'get',
      //   params:data
      // })
      .then(() => {
        unitVue()
        // resolve(true)
      }).catch(err =>{
        let msg = '未知错误，请联系管理员！'
        if(err && err.msg) {
          msg = err.msg
        }
        ElMessageBox.alert(msg, '提示', {
          confirmButtonText: '确定',
          callback: () => {
            store.dispatch('LogOut').then(() => {})
          }
        });
      })
    }
    else if(getToken()){
      unitVue()
    }
    else{
      const redirect = location.origin
      location.href = `${import.meta.env.VITE_APP_LOGIN_URL}?&redirect=${encodeURIComponent(redirect)}`
    }
  // })
  
}

const unitVue = () => {
  Promise.all([importJS()]).then(result => {
    app.mount('#app')
  })
}

// omsLogin()

Promise.all([importJS()]).then(result => {
  app.mount('#app');
})

