import { defineStore } from 'pinia'
import Evt from '@/common/utils/evt.ts'
import Strings from '@/common/utils/strings.ts'
import Utils from '@/common/utils'
import { SpecialPage } from '@/common/router/constants.ts'

export const useAppPageStore = defineStore('AppPage', () => {
  const pages = Utils.resetAble(reactive<AppTypes.PageContext[]>([]))

  const currentPage = Utils.resetAble(reactive<AppTypes.PageContext>({
    insId: '',
    title: '',
    keepAlive: false,
    params: {},
    routeName: '',
    menuId: '',
    icon: '',
    breadcrumb: [],
  }))

  const keepAliveInclude = computed(() => {
    return pages.filter(it => it.keepAlive).map(it => Strings.pascalCase(it.routeName))
  })

  function open(ctx?: AppTypes.PageContext) {
    if (
      ctx == null
      || Strings.isBlank(ctx.insId)
      || currentPage.insId === ctx.insId) return Promise.reject('已在当前页面')
    const page = pages.find(it => it.insId === ctx.insId)
    if (page == null) pages.push(ctx)
    currentPage.$reset(ctx)
    return Promise.resolve(ctx)
  }

  function reopen(insId: string) {
    const page = pages.find(it => it.insId === insId)
    return open(page)
  }

  function closePage(insId: string) {
    const index = pages.findIndex(it => it.insId === insId)
    if (index < 1 || pages[index].routeName === SpecialPage.Home) return Promise.reject('不能关闭首页')
    pages.splice(index, 1)
    if (currentPage.insId !== insId) return Promise.resolve(null)
    const newLen = pages.length
    const oldLen = newLen + 1
    let page: AppTypes.PageContext | undefined
    if (index === 1) {
      page = newLen > 1 ? pages[1] : pages[0]
    } else if (index === oldLen - 1) {
      page = pages[newLen - 1]
    } else {
      page = pages[index]
    }
    return open(page)
  }

  function closeCurrent(id?: string) {
    return closePage(id ?? currentPage.insId)
  }

  function closeLeft(id?: string) {
    const index = pages.findIndex(it => it.insId === (id ?? currentPage.insId))
    if (index < 2) return
    pages.splice(1, index - 1)
  }

  function closeRight(id?: string) {
    const index = pages.findIndex(it => it.insId === (id ?? currentPage.insId))
    if (index < 0) return
    pages.splice(index + 1, pages.length - index - 1)
  }

  function closeOther(id?: string) {
    const pageList = pages.filter(it => it.routeName === SpecialPage.Home || it.insId === (id ?? currentPage.insId))
    pages.$reset(pageList)
  }

  function closeAll() {
    const page = pages.find(it => it.routeName === SpecialPage.Home)!
    pages.$reset([ page ])
    return open(page)
  }

  function $reset() {
    pages.$reset()
    currentPage.$reset()
  }

  Evt.on('logout', $reset)

  return {
    reopen,
    open,
    closePage,
    closeCurrent,
    closeLeft,
    closeRight,
    closeOther,
    closeAll,
    pages,
    currentPage,
    keepAliveInclude,
    $reset,
  }
})
