import LoginApi from '@/pages/login/login-api.ts'
import Colls from '@/common/utils/colls.ts'
import { useAppSettingStore } from '@/common/app/app-setting-store.ts'
import { useAppUserStore } from '@/common/app/app-user-store.ts'
import Utils from '@/common/utils'

export const reloadUserInfo = () => {
  const appSettingStore = useAppSettingStore()
  const appUserStore = useAppUserStore()
  LoginApi.my()
      .then(({data}) => {
        // data.menus.unshift(HomeMenu)
        const menuTree = Utils.clone(Colls.toTree(data.menus))
        appSettingStore.$patch({
          menus: data.menus, menuTree,
          theme: data.setting?.theme ?? 'light',
          collectedMenus: data.setting?.collectedMenus ?? [],
          logo: data.setting?.logo,
          language: data.setting?.language ?? 'zh',
        })
        appUserStore.$patch({
          userId: data.id,
          nickname: data.nickname,
          avatar: data.avatar,
          tenantId: data.tenantId,
          tenantName: data.tenantName,
        })
      })
}

export function hasPermission(resSn?: string) {
  const appSettingStore = useAppSettingStore()
  const res = appSettingStore.menus.find(it => it.sn === resSn)
  return res != null
}
