import router from '@/router'
import store from '@/store'
import { TSB_WORKSPACE_ROUTE } from '@/utils/tsbCmdRoute'

export const TSB_WORKSPACE_NAME = 'TsbWorkspace'

export function isWorkspaceRoute(route) {
  const r = route || router.currentRoute
  return r.name === TSB_WORKSPACE_NAME || r.path === TSB_WORKSPACE_ROUTE
}

export function findWorkspaceVisitedView() {
  return store.state.tagsView.visitedViews.find(
    v => v.name === TSB_WORKSPACE_NAME || v.path === TSB_WORKSPACE_ROUTE
  )
}

/** 移除重复的「设备操作」页签，只保留最早一条 */
export function dedupeWorkspaceTags() {
  const views = store.state.tagsView.visitedViews
  const matched = views.filter(
    v => v.name === TSB_WORKSPACE_NAME || v.path === TSB_WORKSPACE_ROUTE
  )
  if (matched.length <= 1) {
    return
  }
  matched.slice(1).forEach((view) => {
    store.dispatch('tagsView/delView', view)
  })
}

/** 刷新等工作区页已打开时，确保 tags 中存在一条「设备操作」 */
export function ensureWorkspaceTag() {
  if (!isWorkspaceRoute()) {
    return
  }
  dedupeWorkspaceTags()
  if (!findWorkspaceVisitedView()) {
    store.dispatch('tagsView/addView', router.currentRoute)
  }
}

/**
 * 进入设备工作区：已存在「设备操作」页签则激活，不新建
 */
export function navigateToWorkspace() {
  dedupeWorkspaceTags()
  const existing = findWorkspaceVisitedView()
  if (existing) {
    const target = existing.fullPath || TSB_WORKSPACE_ROUTE
    if (router.currentRoute.fullPath === target) {
      return Promise.resolve()
    }
    return router.push(target)
  }
  return router.push({ name: TSB_WORKSPACE_NAME })
}
