import { computed, ref } from 'vue'
import { useAccountStore } from 'stores/account'
import { useTabStore } from 'stores/tab'
import type { TabItem } from 'core/types/menu'
import { checkPermission } from 'src/utils/permission'
import { hasPermission } from 'src/directives/permission'

export default function () {
  const accountStore = useAccountStore()
  const tabStore = useTabStore()

  const account = computed(() => {
    return accountStore.account
  })

  const isLogin = computed(() => {
    return accountStore.accountId !== undefined
  })

  // workspace
  const workspace = computed(() => {
    return accountStore.workspace
  })
  const workspaces = computed(() => {
    return accountStore.workspaces
  })
  const activeWorkspaces = computed(() => {
    return accountStore.activeWorkspaces
  })

  const initWorkspace = async () => {
    try {
      if (isLogin.value) {
        const defaultWorkspace = await accountStore.initWorkspaces() as Indexable
        if (defaultWorkspace.id) {
          tabStore.updateWorkspace(defaultWorkspace.id)
        }
      }
    } catch (err) {
      //
    }
  }

  const setWorkspace = (value: Indexable) => {
    accountStore.setWorkspace(value)
  }

  const setWorkspaces = (value: Indexable[]) => {
    accountStore.setWorkspaces(value)
  }

  const switchWorkspace = (workspace: Indexable) => {
    accountStore.switchWorkspace(workspace)
    tabStore.updateWorkspace(workspace.id)
  }

  const switchWorkspaceByTab = (tab: TabItem) => {
    const workspace = accountStore.getWorkspace(tab.workspaceId)
    if (workspace) {
      accountStore.switchWorkspace(workspace, '')
    }
  }

  function setAccount(value: Indexable) {
    accountStore.setAccount(value)
  }

  function logout() {
    accountStore.logout()
  }


  return {
    accountStore,
    account,
    isLogin,
    workspace,
    workspaces,
    activeWorkspaces,

    logout,
    setAccount,
    initWorkspace,
    setWorkspace,
    switchWorkspace,
    switchWorkspaceByTab,
    setWorkspaces,
  }
}
