import { createApp } from 'vue'
import App from './App.vue'

import router, { registerDynamicRoutes } from './router'
import store from './store'
import './styles/index.scss'
import 'element-plus/es/components/message/style/css'
import roleShow from './utils/roleShow'
import VxeUITable from 'vxe-table'
import 'vxe-table/lib/style.css'
import { isPermissionBtn } from '@/utils/index'
import { getToken } from '@/api/axios'
import { buildDynamicRoutes } from '@/router/dynamicRoutes'
import { MenuTreeNode } from '@/types/api/role'

// 确保在渲染用户提供的HTML内容时，不会执行任何潜在的恶意脚本，从而提高应用的安全性
import vueDomPurifyHTMLPlugin from 'vue-dompurify-html'

/**
 * 应用挂载前还原动态路由：用户已登录时把 localStorage 里的 sysMenus
 * 重新挂到 / (Home) 下。必须先于 app.mount()，否则首次路由解析时
 * 业务路由还没注册，会出现刷新即 404。
 */
function restoreDynamicRoutes() {
  if (!getToken()) return
  try {
    const raw = localStorage.getItem('sysMenus')
    if (!raw) return
    const parsed = JSON.parse(raw) as MenuTreeNode[]
    if (Array.isArray(parsed) && parsed.length) {
      registerDynamicRoutes(buildDynamicRoutes(parsed))
    }
  } catch {
    // ignore
  }
}

restoreDynamicRoutes()

const app = createApp(App)

app
  .use(vueDomPurifyHTMLPlugin)
  .use(router)
  .use(store)
  .use(roleShow)
  .use(VxeUITable)
  .mount('#app')

app.config.globalProperties.$isPermissionBtn = isPermissionBtn
