import { defineStore } from 'pinia'
import { ref } from 'vue'
import { MenuTreeNode } from '@/types/api/role'

const STORAGE_KEY = 'sysMenus'

function readFromStorage(): MenuTreeNode[] {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    if (!raw) return []
    const parsed = JSON.parse(raw)
    return Array.isArray(parsed) ? (parsed as MenuTreeNode[]) : []
  } catch {
    return []
  }
}

function writeToStorage(data: MenuTreeNode[]) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch {
    // ignore quota errors
  }
}

const useMenuTreeStore = defineStore('menuTree', () => {
  const menusTree = ref<MenuTreeNode[]>(readFromStorage()) // 功能按钮里的菜单(带左边栏和按钮)
  const menusTreeNoBtn = ref<MenuTreeNode[]>(readFromStorage()) // 专门渲染三级菜单(带左边栏和按钮)

  const reqMenu = ref<{ buttons: string[] }>({
    buttons: [],
  })

  const setMenuTree = (data: MenuTreeNode[]) => {
    menusTree.value = data
    // writeToStorage(data) // 这里不写入本地存储，避免覆盖 menusTreeNoBtn
  }

  const clearMenuTree = () => {
    menusTree.value = []
    menusTreeNoBtn.value = []
    reqMenu.value = { buttons: [] }
    localStorage.removeItem(STORAGE_KEY)
  }
  const setMenuTreeNoBtn = (data: MenuTreeNode[]) => {
    menusTreeNoBtn.value = data
    writeToStorage(data)
  }
  const setReqMenu = (data: { buttons: string[] }) => {
    reqMenu.value = data
  }

  return {
    menusTree,
    menusTreeNoBtn,
    reqMenu,
    setMenuTree,
    clearMenuTree,
    setReqMenu,
    setMenuTreeNoBtn,
  }
})

export default useMenuTreeStore
