import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getStore, setStore } from '@/utils/storage'
import { constantRouterMap, noMenuRouterMap, filterAsyncRoutes } from '@/router'
import { leftMenus } from '@/api/user'
import type { RouterItem } from '@/utils/crypto'

export const usePermissionStore = defineStore('permission', () => {
  const constantRouters = constantRouterMap
  const routers = ref<RouterItem[]>([])
  const authBtnCodes = ref<string[]>(getStore('permissions') || [])
  const multipleTag = ref<RouterItem[]>(getStore('multipleTag', true) || [])
  const curTag = ref<string>(getStore('curTag', true) || '/home')

  function SET_ROUTERS(r: RouterItem[]) {
    routers.value = r
  }

  function setAuthBtnCodes(codes: string[]) {
    authBtnCodes.value = codes
    setStore('permissions', codes)
  }

  function SET_MULTIPLE_TAG(tags: RouterItem[]) {
    multipleTag.value = tags
    setStore('multipleTag', tags, true)
  }

  function SET_CUR_TAG(tag: string) {
    curTag.value = tag
    setStore('curTag', tag, true)
  }

  async function generateRoutes() {
    const res = await leftMenus()
    const asyncMenu = filterAsyncRoutes(res.data, '')
    const accessedRouters = [...noMenuRouterMap as any, ...asyncMenu]
    const storedTags = getStore('multipleTag', true)
    SET_ROUTERS(accessedRouters)
    if (!storedTags || storedTags.length === 0) {
      SET_MULTIPLE_TAG([(accessedRouters[0] || {}) as RouterItem])
    } else {
      SET_MULTIPLE_TAG(storedTags)
    }
    return accessedRouters
  }

  async function removeRoutes() {
    SET_ROUTERS([])
  }

  async function setMultipleTag(tags: RouterItem[]) {
    SET_MULTIPLE_TAG(tags)
  }

  async function setCurTag(tag: string) {
    SET_CUR_TAG(tag)
  }

  return {
    constantRouters,
    routers,
    authBtnCodes,
    multipleTag,
    curTag,
    SET_ROUTERS,
    setAuthBtnCodes,
    SET_MULTIPLE_TAG,
    SET_CUR_TAG,
    generateRoutes,
    removeRoutes,
    setMultipleTag,
    setCurTag
  }
})
