import { ref, provide } from 'vue'

export function useFormValidation(fieldConfigs = {}) {
  const errors = ref({})

  // 字段配置管理
  const configs = ref(fieldConfigs)

  // 获取字段配置
  const getFieldConfig = (fieldName) => {
    return configs.value[fieldName] || {}
  }

  // 设置字段配置
  const setFieldConfig = (fieldName, config) => {
    configs.value[fieldName] = config
  }

  // 批量设置字段配置
  const setFieldConfigs = (newConfigs) => {
    configs.value = { ...configs.value, ...newConfigs }
  }

  // 提供给子组件使用
  provide('errors', errors)
  provide('getFieldConfig', getFieldConfig)
  
  // 校验单个字段
  const validateField = (fieldName, value, rules) => {
    if (!rules || !Array.isArray(rules)) {
      return true
    }
    
    const fieldErrors = []
    
    for (const rule of rules) {
      // 必填校验
      if (rule.required && (!value || value === '')) {
        fieldErrors.push(rule.message || '此字段为必填项')
        break
      }

      // 如果值为空且不是必填，跳过其他校验
      if (!value || value === '') {
        continue
      }

      // 最小长度校验
      if (rule.min && value.length < rule.min) {
        fieldErrors.push(rule.message || `最少输入${rule.min}个字符`)
        break
      }

      // 最大长度校验
      if (rule.max && value.length > rule.max) {
        fieldErrors.push(rule.message || `最多输入${rule.max}个字符`)
        break
      }

      // 正则校验
      if (rule.pattern && !rule.pattern.test(value)) {
        fieldErrors.push(rule.message || '格式不正确')
        break
      }
      
      // 自定义校验函数
      if (rule.validator && typeof rule.validator === 'function') {
        const result = rule.validator(value)
        if (result !== true) {
          fieldErrors.push(result || rule.message || '校验失败')
          break
        }
      }
    }

    // 更新错误信息
    if (fieldErrors.length > 0) {
      errors.value[fieldName] = fieldErrors
      return false
    } else {
      delete errors.value[fieldName]
      return true
    }
  }
  
  // 提供给子组件使用
  provide('validateField', validateField)
  
  // 获取嵌套字段值的辅助函数
  const getNestedFieldValue = (formData, fieldPath) => {
    const pathArray = fieldPath.split('.')
    let value = formData
    for (const key of pathArray) {
      value = value?.[key]
    }
    return value
  }

  // 校验整个表单
  const validateForm = (formData, formRules) => {
    console.log('validateForm开始:', { formData, formRules })
    let isValid = true

    for (const fieldName in formRules) {
      // 支持嵌套字段路径（如 "xcd_0.qkms"）
      const fieldValue = getNestedFieldValue(formData, fieldName)
      const fieldRules = formRules[fieldName].rules || formRules[fieldName]

      console.log(`校验字段 ${fieldName}:`, { fieldValue, fieldRules })
      const fieldValid = validateField(fieldName, fieldValue, fieldRules)
      console.log(`字段 ${fieldName} 校验结果:`, fieldValid)

      if (!fieldValid) {
        isValid = false
      }
    }

    console.log('validateForm结束:', isValid)
    return isValid
  }
  
  // 清除所有错误
  const clearErrors = () => {
    errors.value = {}
  }

  // 清除指定字段错误
  const clearFieldError = (fieldName) => {
    delete errors.value[fieldName]
  }

  return {
    errors,
    validateField,
    validateForm,
    clearErrors,
    clearFieldError,
    getFieldConfig,
    setFieldConfig,
    setFieldConfigs,
    configs
  }
}
