/**
 * @vue2-client 模块加载器（单例）
 * 使用 require.context 预加载组件
 * 注意：require.context 的参数必须是字面量，不能是变量，以便 webpack 静态分析
 */
class Vue2ClientModuleLoader {
  constructor () {
    if (Vue2ClientModuleLoader.instance) {
      return Vue2ClientModuleLoader.instance
    }

    this.moduleMap = new Map()
    this.commonLoad()
    this.servicesLoad()

    console.log(`[模块加载器] 共加载 ${this.moduleMap.size} 个组件`)
    Vue2ClientModuleLoader.instance = this
  }

  commonLoad() {
    // 预加载common下vue组件
    const context = require.context(
      '@vue2-client/base-client/components/common',
      true,
      /^(?!.*\/(XReportSlot|LayerItem|demo)\.vue$).*\.vue$/,
      'sync'
    )
    const loadedPaths = []
    context.keys().forEach(key => {
      // 去除 ./ 前缀和文件名后缀
      const relativePath = key.replace(/^\.\//, '').replace(/\.[^.]+$/, '')
      const fullPath = `@vue2-client/base-client/components/common/${relativePath}`
      const module = context(key)
      const component = module.default || module
      if (this.isVueComponent(component)) {
        this.moduleMap.set(fullPath, component)
        loadedPaths.push(fullPath)
      }
    })
    console.log(`[模块加载器-common] 已加载 ${loadedPaths.length} 个组件`)
    console.log(`[模块加载器-common] 详情: ${JSON.stringify(loadedPaths)}`)
  }

  servicesLoad() {
    // 预加载services下组件
    const context = require.context(
      '@vue2-client/services',
      true,
      /\.js$/,
      'sync'
    )
    const loadedPaths = []
    context.keys().forEach(key => {
      const relativePath = key.replace(/^\.\//, '').replace(/\.[^.]+$/, '')
      const fullPath = `@vue2-client/services/${relativePath}`
      const module = context(key)
      const component = module.default || module
      this.moduleMap.set(fullPath, component)
      loadedPaths.push(fullPath)
    })
    console.log(`[模块加载器-services] 已加载 ${loadedPaths.length} 个组件`)
    console.log(`[模块加载器-services] 详情: ${JSON.stringify(loadedPaths)}`)
  }

  /**
   * 检查是否为 Vue 组件
   * @param {*} component - 模块对象
   */
  isVueComponent (component) {
    if (!component || typeof component !== 'object') {
      return false
    }
    return (
      typeof component.render === 'function' ||
      typeof component.template === 'string' ||
      typeof component.setup === 'function' ||
      component.__vccOpts !== undefined
    )
  }

  /**
   * 获取组件（同步）
   * @param {string} fullPath - 完整路径
   * @returns {Object|null}
   */
  get (fullPath) {
    return this.moduleMap.get(fullPath) || null
  }

  /**
   * 检查组件是否存在
   * @param {string} fullPath - 完整路径
   * @returns {boolean}
   */
  has (fullPath) {
    return this.moduleMap.has(fullPath)
  }

  /**
   * 获取所有已加载的组件路径
   * @returns {string[]}
   */
  getPaths () {
    return Array.from(this.moduleMap.keys())
  }

  /**
   * 获取所有已加载的组件（路径 -> 组件映射）
   * @returns {Map<string, Object>}
   */
  getAllComponents () {
    return new Map(this.moduleMap)
  }
}
// 创建单例
const vue2ClientLoader = new Vue2ClientModuleLoader()

export default vue2ClientLoader
