const viewModules = import.meta.glob('../view/**/*.vue')
const moduleViews = import.meta.glob('../modules/**/*.vue')
const legacyModuleComponents = {
  'plugin/email/view/index.vue': 'modules/email/view/index.vue',
  'plugin/announcement/view/info.vue': 'modules/announcement/view/info.vue',
  'plugin/announcement/form/info.vue': 'modules/announcement/form/info.vue'
}

export const asyncRouterHandle = (asyncRouter) => {
  asyncRouter.forEach((item) => {
    if (item.component && typeof item.component === 'string') {
      const component = legacyModuleComponents[item.component] || item.component
      item.meta.path = '/src/' + component
      if (component.split('/')[0] === 'view') {
        item.component = dynamicImport(viewModules, component)
      } else if (component.split('/')[0] === 'modules') {
        item.component = dynamicImport(moduleViews, component)
      }
    }
    if (item.children) {
      asyncRouterHandle(item.children)
    }
  })
}

function dynamicImport(dynamicViewsModules, component) {
  const keys = Object.keys(dynamicViewsModules)
  const matchKeys = keys.filter((key) => {
    const k = key.replace('../', '')
    return k === component
  })
  const matchKey = matchKeys[0]
  const matched = dynamicViewsModules[matchKey]
  // 找不到组件时返回占位组件，避免 component 为 undefined 导致路由白屏。
  if (!matched) {
    console.warn(`[asyncRouter] 未找到组件: ${component}，已使用占位组件代替`)
    return {
      name: 'MissingComponentPlaceholder',
      render: () => null
    }
  }
  return matched
}
