import { defineStore } from 'pinia'
import { getStore, setStore } from '@/utils/storage'
import { Menu, MenuState } from './types'
import { getMenuTree } from '@/api/upms/menu'
import addRoutes from '@/router/util'

export const useMenuStore = defineStore('menu', {
  state: (): MenuState => ({
    menus: getStore('menus') || [],
    loading: 'wait'
  }),
  getters: {
    /**
     * 展示的菜单，只展示有字节点的
     * @param state
     */
    showMenus(state: MenuState): any[] {
      const menus: any[] = []
      state.menus.forEach((item: any) => {
        const isSubmenu = item.children && item.children.length > 0
        if (isSubmenu || item.path === '/') {
          menus.push(item)
        }
      })
      return menus
    }
  },
  actions: {
    setMenus(menus: Array<Menu>) {
      setStore('menus', menus)
      this.menus = menus
    },
    /**
     * 加载菜单
     */
    loadMenus() {
      // 延迟设为加载中避免骨架屏一闪而过
      if (this.menus.length > 0) {
        this.loading = 'done'
      } else {
        setTimeout(() => {
          if (this.loading !== 'done') {
            this.loading = 'ing'
          }
        }, 250)
      }
      // 请求后端获取菜单
      getMenuTree().then((res: any) => {
        addRoutes(res)
        this.setMenus(res)
        this.loading = 'done'
      })
    }
  }
})
