// 字段控件覆盖机制
// 约定：/src/views/pagetype/<pagetype>/form/controls/<fieldtype>.vue

type AsyncComponentLoader = () => Promise<any>

// 扫描所有可能的控件覆盖组件
const allControlOverrides: Record<string, AsyncComponentLoader> = import.meta.glob(
  '/src/views/pagetype/**/form/controls/**.vue'
)

// 预计算路径映射，提高查找效率
const pathMap = new Map<string, string>()

// 初始化路径映射
Object.keys(allControlOverrides).forEach(path => {
  const segments = path.split('/').filter(Boolean)
  if (segments.length >= 7) {
    const entity = segments[3]
    const fieldtype = segments[6].replace(/\.vue$/i, '')
    const key = `${entity}:${fieldtype}`
    pathMap.set(key, path)
  }
})

/**
 * 解析并返回指定 pagetype 和 fieldtype 的控件覆盖组件
 * @param entity pagetype名称
 * @param fieldtype 字段类型
 */
export async function resolveControlOverride(entity: string, fieldtype: string): Promise<any | null> {
  if (!entity || !fieldtype) return null
  
  // 标准化输入
  const entityKey = entity.toLowerCase().replace(/-/g, '_')
  const fieldtypeKey = fieldtype.replace(/\s+/g, '')
  
  // 直接查找匹配的路径
  const key = `${entityKey}:${fieldtypeKey}`
  const path = pathMap.get(key)
  
  if (!path) return null
  
  try {
    const module = await allControlOverrides[path]()
    return module?.default ?? module
  } catch {
    return null
  }
}
