import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'
import type { PermissionState } from './types'
import { constantRoutes } from '@/router/system'

const modules = import.meta.glob('../../views/**/**.vue')
export const Layout = () => import('@/layout/index.vue')

export const filterAsyncRoutes = (routes: any[], parentPath?: string): any[] => {
  const res: any[] = []
  routes &&
    routes.forEach((route) => {
      const path =
        parentPath && route.path.startsWith(parentPath)
          ? route.path.slice(parentPath.length + 1)
          : route.path
      const tmp = {
        name: route.path,
        path: path,
        menuId: route.id,
        type: route.resourceType,
        component: () => {},
        meta: {
          hidden: !!route.visible,
          title: route.resourceName,
          icon: route.icon,
          keepAlive: route.isCache,
          keepAliveName: getPureName(route.path),
          link: route.link
        },
        children: route.childList
      }
      if (tmp.type === 0) {
        tmp.component = Layout
      } else {
        const component = modules[`../../views${route.path}.vue`] as any
        if (component) {
          tmp.component = component
        } else {
          tmp.component = modules['../../views/home/errorpage.vue']
        }
      }
      res.push(tmp)
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, path)
      }
    })
  return res
}

const getPureName = (path: string) => {
  const arr = path.split('/')
  return arr.reduce((str: string, cur: string, index: number) => {
    if (arr.length === index + 1 && cur === 'index') {
      return str
    }
    if (!str && cur) {
      return (str = cur)
    } else if (str && cur) {
      return (str += '-' + cur)
    }
    return str
  }, '')
}

const usePermissionStore = defineStore({
  id: 'permission',
  state: (): PermissionState => ({
    routes: [],
    addRoutes: []
  }),
  actions: {
    setRoutes(routes: RouteRecordRaw[]) {
      this.addRoutes = routes
      this.routes = constantRoutes.concat(routes)
    },
    generateRoutes(menuList: any[]) {
      return new Promise((resolve) => {
        const routes = filterAsyncRoutes(menuList)
        routes.push({
          path: '/:pathMatch(.*)*',
          name: 'error',
          redirect: '/error'
        })
        this.setRoutes(routes)
        resolve(routes)
      })
    }
  }
})

export default usePermissionStore
