import { defineStore } from 'pinia'
import { store } from '../index'
import { cloneDeep } from 'lodash-es'
import remainingRouter from '@/router/modules/remaining'
import staticRouter from '@/router/modules/static'
import { generateRoute, flatMultiLevelRoutes } from '@/utils/routerHelper'
import { CACHE_KEY } from '@/hooks/web/useCache'

import cache from '@/plugins/cache'

export interface PermissionState {
  routers: AppRouteRecordRaw[]
  addRouters: AppRouteRecordRaw[]
  menuTabRouters: AppRouteRecordRaw[]
}

export const usePermissionStore = defineStore('permission', {
  state: (): PermissionState => ({
    routers: [],
    addRouters: [],
    menuTabRouters: []
  }),
  getters: {
    getRouters(): AppRouteRecordRaw[] {
      return this.routers
    },
    getAddRouters(): AppRouteRecordRaw[] {
      return flatMultiLevelRoutes(cloneDeep(this.addRouters))
    },
    getMenuTabRouters(): AppRouteRecordRaw[] {
      return this.menuTabRouters
    }
  },
  actions: {
    async generateRoutes(): Promise<unknown> {
      return new Promise<void>(async (resolve) => {
        let res: AppCustomRouteRecordRaw[] = []
        if (cache.local.get(CACHE_KEY.ROLE_ROUTERS)) {
          res = cache.local.get(CACHE_KEY.ROLE_ROUTERS) as AppCustomRouteRecordRaw[]
        }
        const staticRouters = cloneDeep(staticRouter)
        // 与动态路由比较，首先判断目录是否存在，如果存在就合并，并替换动态路由中的目录
        staticRouters.forEach((item) => {
          const index = res.findIndex((item2) => item2.path === item.path)
          if (index !== -1) {
            const arr = []
            if (!item.children || item.children.length === 0) {
              item.children = arr
            }
            if (res[index].children && res[index].children.length > 0) {
              item.children = item.children.concat(res[index].children)
            }
            // routerMap[index].children = item.children
            // 插入动态路由数组的第二位
            res[index] = { ...res, ...item }
          } else {
            res = [...staticRouters, ...res]
          }
        })
        const routerMap: AppRouteRecordRaw[] = generateRoute(res)
        // 动态路由，404一定要放到最后面
        this.addRouters = routerMap.concat([
          {
            path: '/:path(.*)*',
            redirect: '/404',
            name: '404Page',
            meta: {
              hidden: true,
              breadcrumb: false
            }
          }
        ])

        // 渲染菜单的所有路由
        this.routers = cloneDeep(remainingRouter).concat(routerMap)
        resolve()
      })
    },
    setMenuTabRouters(routers: AppRouteRecordRaw[]): void {
      this.menuTabRouters = routers
    }
  }
})

export const usePermissionStoreWithOut = () => {
  return usePermissionStore(store)
}
