import { shortcutManager } from '@vue2-client/base-client/utils/shortcutManager'

export const shortcutRouterPlugin = {
  install(Vue, options = {}) {
    const { router } = options

    if (!router) {
      console.warn('[ShortcutRouter] 未提供 router 实例')
      return
    }

    router.beforeEach((to, from, next) => {
      if (!shortcutManager.isEnabled) {
        next()
        return
      }

      const fromPath = from.path
      const toPath = to.path

      if (fromPath) {
        // 保存该路由下所有作用域状态（激活和停用的都保存）
        const tabStates = new Map()
        const prefix = `${fromPath}::`
        shortcutManager.scopeActive.forEach((active, scopeId) => {
          if (scopeId.startsWith(prefix)) {
            tabStates.set(scopeId, active)
            shortcutManager.setScopeActive(scopeId, false)
          }
        })

        if (tabStates.size > 0) {
          shortcutManager.routeStateSnapshots.set(fromPath, {
            tabStates,
            lastAccess: Date.now()
          })
        }
      }

      // 激活新路由作用域
      const toScope = `${toPath}::`
      shortcutManager.setScopeActive(toScope, true)

      next()
    })

    Vue.prototype.$activateRouteShortcuts = function(routePath) {
      shortcutManager.setScopeActive(`${routePath}::`, true)
    }

    Vue.prototype.$deactivateRouteShortcuts = function(routePath) {
      shortcutManager.setScopeActive(`${routePath}::`, false)
    }
  }
}
