import {createRouter, createWebHashHistory} from 'vue-router'
import {setupLayouts} from 'virtual:generated-layouts'
import generatedRoutes from 'virtual:generated-pages'
import {$favicon} from "~/tool/favicon"
import {
  useStore, useRouterActive
} from '~/store'
import {$image, $response, ConfigGetAction} from "~/api";

const allow_unlogged_in_page = ['404'];
const $router_active = useRouterActive()
const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL), routes: setupLayouts(generatedRoutes)
})

const updateRouterActive = (matched) => {
  matched.shift()
  const last = matched[matched.length - 1]
  if (allow_unlogged_in_page.indexOf(last.name) !== -1) return
  setTimeout(() => {
    $router_active.value = matched.map((item) => {
      return {
        title: 'title' in item.meta ? item.meta.title : item.name,
        key: 'active' in item.meta ? item.meta.active : item.name,
      }
    })
  })
}
let token_check = ''
let error_status = false
router.beforeEach(async (to, from, next) => {
  const $store = useStore()
  if (!$store.config) {
    const response = await ConfigGetAction({
      config_arr: [
        "Favicon",
        "网站名称",
      ]
    })
    $response(response, () => {
      $store.config = response.data
      $favicon($image(response.data['Favicon']))
    })
    if (!response) error_status = true
  }
  if (!!error_status) {
    $store.config = {
      "Favicon": "https://www.sa0.online/storage/assets/default/favicon.png",
      "网站名称": "网络错误",
    }
    $favicon($image($store.config['Favicon']))
  }
  document.title = ('title' in to.meta && to.meta.title !== '首页') ? `${to.meta.title} ${$store.config['网站名称']}` : $store.config['网站名称']
  if (allow_unlogged_in_page.indexOf(to.name) === -1) {
    updateRouterActive(to.matched.map(item => item))
    next()
  } else {
    next()
  }
})
export default router
