/**
 * 动态表单Composable
 * 提供表单数据管理和验证功能
 */

import { ref, computed, reactive } from 'vue'
import type { FieldConfig, FormData, FormValidationState, FormActions } from '@/types/form'
import { validateFields } from '@/utils/fieldValidator'

/**
 * 动态表单Hook
 * @param fields 字段配置列表
 */
export function useDynamicForm(fields: FieldConfig[]) {
  // 表单数据
  const formData = ref<FormData>({})

  // 验证错误
  const validationErrors = ref<Record<string, string[]>>({})

  // 是否已修改
  const isDirty = ref(false)

  // 是否正在提交
  const isSubmitting = ref(false)

  // 初始数据（用于重置）
  const initialData = ref<FormData>({})

  /**
   * 表单是否有效
   */
  const isValid = computed(() => {
    return Object.keys(validationErrors.value).length === 0
  })

  /**
   * 设置字段值
   */
  const setFieldValue = (fieldName: string, value: any) => {
    formData.value = {
      ...formData.value,
      [fieldName]: value
    }
    isDirty.value = true
  }

  /**
   * 批量设置字段值
   */
  const setFieldValues = (values: Record<string, any>) => {
    formData.value = {
      ...formData.value,
      ...values
    }
    isDirty.value = true
  }

  /**
   * 获取字段值
   */
  const getFieldValue = (fieldName: string) => {
    return formData.value[fieldName]
  }

  /**
   * 验证单个字段
   */
  const validateField = async (fieldName: string): Promise<boolean> => {
    const field = fields.find((f) => f.name === fieldName)
    if (!field) return false

    const value = formData.value[fieldName]
    const result = validateField(value, field, formData.value)

    if (!result.isValid) {
      validationErrors.value = {
        ...validationErrors.value,
        [fieldName]: result.errors
      }
    } else {
      const newErrors = { ...validationErrors.value }
      delete newErrors[fieldName]
      validationErrors.value = newErrors
    }

    return result.isValid
  }

  /**
   * 验证所有字段
   */
  const validateAll = async (): Promise<boolean> => {
    const errors = validateFields(formData.value, fields)
    validationErrors.value = errors
    return Object.keys(errors).length === 0
  }

  /**
   * 清除验证错误
   */
  const clearValidation = () => {
    validationErrors.value = {}
  }

  /**
   * 清除单个字段的验证错误
   */
  const clearFieldValidation = (fieldName: string) => {
    const newErrors = { ...validationErrors.value }
    delete newErrors[fieldName]
    validationErrors.value = newErrors
  }

  /**
   * 重置表单
   */
  const resetForm = () => {
    formData.value = { ...initialData.value }
    validationErrors.value = {}
    isDirty.value = false
  }

  /**
   * 设置表单数据
   */
  const setFormData = (data: FormData) => {
    formData.value = { ...data }
    initialData.value = { ...data }
    isDirty.value = false
  }

  /**
   * 获取表单数据
   */
  const getFormData = (): FormData => {
    return { ...formData.value }
  }

  /**
   * 获取提交数据（只返回有值的字段）
   */
  const getSubmitData = (): FormData => {
    const submitData: FormData = {}
    Object.keys(formData.value).forEach((key) => {
      if (formData.value[key] !== undefined && formData.value[key] !== null && formData.value[key] !== '') {
        submitData[key] = formData.value[key]
      }
    })
    return submitData
  }

  /**
   * 初始化默认值
   */
  const initDefaultValues = () => {
    const defaultData: FormData = {}
    fields.forEach((field) => {
      if (field.defaultValue !== undefined) {
        defaultData[field.name] = field.defaultValue
      }
    })
    formData.value = defaultData
    initialData.value = { ...defaultData }
  }

  /**
   * 提交表单
   */
  const submitForm = async (handleSubmit: (data: FormData) => Promise<void> | void) => {
    // 验证表单
    const valid = await validateAll()
    if (!valid) {
      throw new Error('表单验证失败')
    }

    isSubmitting.value = true
    try {
      await handleSubmit(getSubmitData())
    } finally {
      isSubmitting.value = false
    }
  }

  // 初始化默认值
  initDefaultValues()

  return {
    // 状态
    formData,
    validationErrors,
    isValid,
    isDirty,
    isSubmitting,

    // 方法
    setFieldValue,
    setFieldValues,
    getFieldValue,
    validateField,
    validateAll,
    clearValidation,
    clearFieldValidation,
    resetForm,
    setFormData,
    getFormData,
    getSubmitData,
    submitForm
  }
}

/**
 * 动态表单状态管理Hook（带Pinia集成）
 * @param formId 表单唯一标识
 */
export function useFormState(formId: string) {
  const formStates = reactive<Map<string, FormData>>(new Map())

  /**
   * 保存表单状态
   */
  const saveState = (data: FormData) => {
    formStates.set(formId, { ...data })
  }

  /**
   * 获取表单状态
   */
  const getState = (): FormData | undefined => {
    return formStates.get(formId)
  }

  /**
   * 清除表单状态
   */
  const clearState = () => {
    formStates.delete(formId)
  }

  return {
    saveState,
    getState,
    clearState
  }
}
