import router from '@/common/router/index.ts'
import Toast from '@/components/toast'
import Evt from '@/common/utils/evt.ts'
import { useAppSettingStore } from '@/common/app/app-setting-store.ts'
import { useAppPageStore } from '@/common/app/app-page-store.ts'
import { nanoid } from 'nanoid'

/**
 * 打开页面并添加标签
 *
 * @param option
 */
function open(option: string | Partial<Pick<AppTypes.PageContext, 'params' | 'insId' | 'title'>> & Pick<AppTypes.PageContext, 'routeName'>) {
  let ctx: AppTypes.PageContext
  const appSettingStore = useAppSettingStore()
  if (typeof option === 'string') {
    const routeName = option
    if (!router.hasRoute(routeName)) {
      Toast.error('页面不存在')
      return Promise.reject('页面不存在')
    }
    const menu = appSettingStore.menus.find(it => it.routeName === routeName)
    if (menu == null) {
      Toast.error('页面不存在')
      return Promise.reject('页面不存在')
    }
    ctx = {
      insId: routeName + '_' + nanoid(),
      title: menu.title,
      keepAlive: true,
      params: {},
      routeName,
      menuId: menu.id
    }
  } else {
    const routeName = option.routeName
    if (!router.hasRoute(routeName)) {
      Toast.error('页面不存在')
      return Promise.reject('页面不存在')
    }
    const menu = appSettingStore.menus.find(it => it.routeName === routeName)
    if (menu == null) {
      Toast.error('页面不存在')
      return Promise.reject('页面不存在')
    }

    ctx = {
      insId: option.insId ?? routeName + '_' + nanoid(),
      title: option.title ?? menu.title,
      routeName: routeName,
      keepAlive: true,
      params: option.params ?? {},
      menuId: menu.id
    }
  }
  ctx.insId = ctx.routeName
  useAppPageStore().open(ctx)
  return router.push({name: ctx.routeName})
      .then(err => {
        if (err == null) {
          Evt.emit('openPage')
          return Promise.resolve(true)
        } else {
          return Promise.reject(err)
        }
      })
      .catch(err => {
        return Promise.reject(err)
      })
}

/**
 * 关闭页面并删除标签
 *
 * @param id
 */
function close(id: string) {
  useAppPageStore().close(id)
  Evt.emit('closePage', id)
}

export default {
  open,
  close,
}


