import type { FormBuilderItem, FormBuilderConfig } from './types'

/**
 * 创建表单构建器项目
 */
export const createFormBuilderItem = (
  label: string,
  key: string,
  defaultValue: string = '',
  id?: string
): FormBuilderItem => {
  return {
    id: id || `item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
    label,
    key,
    defaultValue
  }
}

/**
 * 创建表单构建器配置
 */
export const createFormBuilderConfig = (
  items: FormBuilderItem[],
  title: string = '表单构建器'
): FormBuilderConfig => {
  return {
    title,
    items
  }
}

/**
 * 验证表单构建器项目
 */
export const validateFormBuilderItem = (item: FormBuilderItem): boolean => {
  if (!item.id || !item.label || !item.key) {
    console.error('表单构建器项目配置不完整:', item)
    return false
  }

  // 验证键值格式
  if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(item.key)) {
    console.error('键值格式不正确，只能包含字母、数字和下划线，且不能以数字开头:', item.key)
    return false
  }

  return true
}

/**
 * 验证表单构建器配置
 */
export const validateFormBuilderConfig = (config: FormBuilderConfig): boolean => {
  if (!config.items || config.items.length === 0) {
    console.error('表单构建器配置必须有表单项')
    return false
  }

  // 检查键值是否重复
  const keys = config.items.map(item => item.key)
  const uniqueKeys = new Set(keys)
  if (keys.length !== uniqueKeys.size) {
    console.error('表单项的键值不能重复')
    return false
  }

  return config.items.every(validateFormBuilderItem)
}

/**
 * 生成默认的表单构建器项目
 */
export const generateDefaultItems = (count: number = 3): FormBuilderItem[] => {
  const items: FormBuilderItem[] = []

  for (let i = 1; i <= count; i++) {
    items.push(createFormBuilderItem(
      `项目${i}`,
      `item_${i}`,
      ''
    ))
  }

  return items
}

/**
 * 从JSON数据导入表单构建器项目
 */
export const importFromJson = (jsonData: any[]): FormBuilderItem[] => {
  const items: FormBuilderItem[] = []

  jsonData.forEach((item, index) => {
    if (typeof item === 'object' && item !== null) {
      items.push(createFormBuilderItem(
        item.label || `项目${index + 1}`,
        item.key || `item_${index + 1}`,
        item.defaultValue || '',
        item.id
      ))
    }
  })

  return items
}

/**
 * 导出表单构建器项目为JSON
 */
export const exportToJson = (items: FormBuilderItem[]): string => {
  return JSON.stringify(items, null, 2)
}

/**
 * 复制表单构建器项目
 */
export const duplicateItem = (item: FormBuilderItem): FormBuilderItem => {
  return createFormBuilderItem(
    `${item.label}_副本`,
    `${item.key}_copy`,
    item.defaultValue
  )
}

/**
 * 批量创建表单构建器项目
 */
export const createBatchItems = (
  labels: string[],
  keys?: string[],
  defaultValues?: string[]
): FormBuilderItem[] => {
  const items: FormBuilderItem[] = []

  labels.forEach((label, index) => {
    const key = keys?.[index] || `item_${index + 1}`
    const defaultValue = defaultValues?.[index] || ''

    items.push(createFormBuilderItem(label, key, defaultValue))
  })

  return items
}



