import { defineStore } from 'pinia'
import Evt from '@/common/utils/evt.ts'
import { HomeMenu } from '@/common/app/contants.ts'

const pageContextCache = new Map<string, AppTypes.PageContext>()


function initCache() {
  pageContextCache.clear()
  pageContextCache.set(HomeMenu.routeName, {
    insId: HomeMenu.routeName,
    title: HomeMenu.title,
    keepAlive: false,
    params: {},
    routeName: HomeMenu.routeName,
    menuId: HomeMenu.id
  })
}

initCache()

export const useAppPageStore = defineStore('AppPage', () => {
  const keepAliveInclude = ref<string[]>([])

  const currentPage = ref<string>(HomeMenu.routeName)

  const ctx = computed(() => {
    return pageContextCache.get(currentPage.value)!
  })

  function open(ctx_: AppTypes.PageContext) {
    currentPage.value = ctx_.insId
    if (!pageContextCache.has(ctx_.insId)) {
      pageContextCache.set(ctx_.insId, ctx_)
    }
    if (!keepAliveInclude.value.includes(ctx_.insId)) {
      keepAliveInclude.value.push(ctx_.insId)
    }
  }

  function close(insId: string) {
    pageContextCache.delete(insId)
    if (keepAliveInclude.value.includes(insId)) {
      keepAliveInclude.value = keepAliveInclude.value.splice(keepAliveInclude.value.indexOf(insId), 1)
    }
  }

  function $reset() {
    keepAliveInclude.value = []
    currentPage.value = HomeMenu.id
    initCache()
  }

  Evt.on('logout', $reset)

  return {
    ctx,
    open,
    close,
    keepAliveInclude,
    $reset,
  }
})
