// @ts-nocheck
import routerService from 'vue-tidyroutes'
import VueRouter from 'vue-router'

// 处理Avoided redundant navigation to current location错误，避免点击当前URL的链接时报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((error) => {
    if (error.type === VueRouter.NavigationFailureType.duplicated) return
    throw error
  })
}

const exportMethod = routerService.export
const routeMethod = routerService.route

routerService.export = () => {
  // 获取所有路由
  const routes = exportMethod.apply(routerService)
  // 找到挂在sd-frame下的所有路由
  const frame = routes.find((route) => route.path === '/sd-frame')
  const frameChildren = frame.children
    // 去掉 * ，避免匹配到所有的路由
    .filter((route) => route.path !== '*')
    .map((route) => {
      return {
        ...route,
        path: '/' + route.path,
      }
    })
  // 把sd-frame的子路由与原有路由合并
  return [...frameChildren, ...routes]
}

routerService.route = function(path, options) {
  // 只有一个参数，获取已有路由：直接调用原方法
  if (!options) return routeMethod.call(routerService, path, options)

  // 两个参数，设置路由：把已有的先删除掉，再设置新的
  if (this.routes.has(path)) {
    this.routes.delete(path)
  }
  return routeMethod.call(routerService, path, options)
}

routerService.routeInFrame = (url, param) => {
  return routerService.route('/sd-frame').child(url, param)
}

export default routerService
