<template>
  <div class="super-form" v-loading="loading">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="computedRules"
      :label-width="config.labelWidth || '120px'"
      :label-position="config.labelPosition || 'right'"
      :inline="config.inline || false"
      :disabled="config.disabled || false"
      :size="config.size || 'default'"
      :status-icon="config.statusIcon !== false"
      :inline-message="config.inlineMessage"
      :validate-on-rule-change="config.validateOnRuleChange !== false"
      :hide-required-asterisk="config.hideRequiredAsterisk"
      :show-message="config.showMessage !== false"
      :label-suffix="config.labelSuffix"
      :scroll-to-error="config.scrollToError !== false"
      :scroll-into-view-options="config.scrollIntoViewOptions"
      @validate="handleValidate"
    >
      <el-row :gutter="config.gutter || 20">
        <el-col
          v-for="(item, index) in formItems"
          :key="item.field || index"
          :span="item.span || 24"
          :offset="item.offset"
          :xs="item.xs"
          :sm="item.sm"
          :md="item.md"
          :lg="item.lg"
          :xl="item.xl"
          :tag="item.tag"
          :pull="item.pull"
          :push="item.push"
        >
          <el-form-item
            :prop="item.field"
            :label="item.label"
            :required="item.required"
            :rules="item.rules"
            :error="item.error"
            :show-message="item.showMessage !== false"
            :inline-message="item.inlineMessage"
            :class="item.itemClass"
          >
            <!-- 输入框 -->
            <template v-if="item.type === 'input'">
              <el-input
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @input="handleFieldInput(item, $event)"
                @change="handleFieldChange(item, $event)"
                @clear="handleFieldClear(item)"
              >
                <template v-if="item.prepend" #prepend>{{ item.prepend }}</template>
                <template v-if="item.append" #append>{{ item.append }}</template>
                <template v-if="item.prefixIcon" #prefix>
                  <el-icon><component :is="item.prefixIcon" /></el-icon>
                </template>
                <template v-if="item.suffixIcon" #suffix>
                  <el-icon><component :is="item.suffixIcon" /></el-icon>
                </template>
                <template v-if="item.prefix" #prefix>{{ item.prefix }}</template>
                <template v-if="item.suffix" #suffix>{{ item.suffix }}</template>
                <template v-if="item.prependSlot" #prepend>
                  <slot :name="item.prependSlot" :item="item" :value="formData[item.field]" />
                </template>
                <template v-if="item.appendSlot" #append>
                  <slot :name="item.appendSlot" :item="item" :value="formData[item.field]" />
                </template>
              </el-input>
            </template>

            <!-- 文本域 -->
            <template v-else-if="item.type === 'textarea'">
              <el-input
                v-model="formData[item.field]"
                type="textarea"
                v-bind="getItemProps(item)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @input="handleFieldInput(item, $event)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 密码输入框 -->
            <template v-else-if="item.type === 'password'">
              <el-input
                v-model="formData[item.field]"
                type="password"
                v-bind="getItemProps(item)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @input="handleFieldInput(item, $event)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 数字输入框 -->
            <template v-else-if="item.type === 'inputNumber' || item.type === 'number'">
              <el-input-number
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 选择器 -->
            <template v-else-if="item.type === 'select'">
              <el-select
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @visible-change="handleFieldVisibleChange(item, $event)"
                @remove-tag="handleFieldRemoveTag(item, $event)"
                @clear="handleFieldClear(item)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
              >
                <template v-if="item.options">
                  <el-option
                    v-for="option in getOptions(item)"
                    :key="option[item.valueKey || 'value']"
                    :label="option[item.labelKey || 'label']"
                    :value="option[item.valueKey || 'value']"
                    :disabled="option.disabled"
                  >
                    <slot
                      v-if="item.optionSlot"
                      :name="item.optionSlot"
                      :option="option"
                      :item="item"
                    >
                      <span v-if="option.icon" style="margin-right: 8px">
                        <el-icon><component :is="option.icon" /></el-icon>
                      </span>
                      {{ option[item.labelKey || 'label'] }}
                    </slot>
                  </el-option>
                </template>
                <template v-if="item.prefix" #prefix>{{ item.prefix }}</template>
                <template v-if="item.emptySlot" #empty>
                  <slot :name="item.emptySlot" :item="item" />
                </template>
              </el-select>
            </template>

            <!-- 多选框组 -->
            <template v-else-if="item.type === 'checkbox' || item.type === 'checkboxGroup'">
              <el-checkbox-group
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              >
                <el-checkbox
                  v-for="option in getOptions(item)"
                  :key="option[item.valueKey || 'value']"
                  :label="option[item.valueKey || 'value']"
                  :disabled="option.disabled || item.disabled"
                  :border="item.border"
                  :true-label="option.trueLabel"
                  :false-label="option.falseLabel"
                  :indeterminate="option.indeterminate"
                >
                  {{ option[item.labelKey || 'label'] }}
                </el-checkbox>
              </el-checkbox-group>
            </template>

            <!-- 单选框组 -->
            <template v-else-if="item.type === 'radio' || item.type === 'radioGroup'">
              <el-radio-group
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              >
                <el-radio
                  v-for="option in getOptions(item)"
                  :key="option[item.valueKey || 'value']"
                  :label="option[item.valueKey || 'value']"
                  :disabled="option.disabled || item.disabled"
                  :border="item.border"
                  :size="item.size"
                >
                  {{ option[item.labelKey || 'label'] }}
                </el-radio>
              </el-radio-group>
            </template>

            <!-- 日期时间选择器 -->
            <template v-else-if="['date', 'dates', 'datetime', 'week', 'month', 'year', 'daterange', 'datetimerange', 'monthrange'].includes(item.type)">
              <el-date-picker
                v-model="formData[item.field]"
                :type="item.type"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @calendar-change="handleCalendarChange(item, $event)"
                @panel-change="handlePanelChange(item, $event)"
                @visible-change="handleFieldVisibleChange(item, $event)"
              />
            </template>

            <!-- 时间选择器 -->
            <template v-else-if="item.type === 'timePicker' || item.type === 'time'">
              <el-time-picker
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
              />
            </template>

            <!-- 时间选择器组 -->
            <template v-else-if="item.type === 'timeSelect'">
              <el-time-select
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
              />
            </template>

            <!-- 开关 -->
            <template v-else-if="item.type === 'switch'">
              <el-switch
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 滑块 -->
            <template v-else-if="item.type === 'slider'">
              <el-slider
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 评分 -->
            <template v-else-if="item.type === 'rate'">
              <el-rate
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 颜色选择器 -->
            <template v-else-if="item.type === 'colorPicker'">
              <el-color-picker
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @active-change="handleColorActiveChange(item, $event)"
              />
            </template>

            <!-- 穿梭框 -->
            <template v-else-if="item.type === 'transfer'">
              <el-transfer
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @left-check-change="handleTransferLeftCheckChange(item, $event)"
                @right-check-change="handleTransferRightCheckChange(item, $event)"
              />
            </template>

            <!-- 级联选择器 -->
            <template v-else-if="item.type === 'cascader'">
              <el-cascader
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @expand-change="handleCascaderExpandChange(item, $event)"
                @visible-change="handleFieldVisibleChange(item, $event)"
              />
            </template>

            <!-- 树形选择器 -->
            <template v-else-if="item.type === 'treeSelect'">
              <el-tree-select
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @node-click="handleTreeNodeClick(item, $event)"
                @check="handleTreeCheck(item, $event)"
                @node-expand="handleTreeNodeExpand(item, $event)"
                @node-collapse="handleTreeNodeCollapse(item, $event)"
              />
            </template>

            <!-- 上传 -->
            <template v-else-if="item.type === 'upload'">
              <el-upload
                v-bind="getItemProps(item)"
                :on-success="(response, file, fileList) => handleUploadSuccess(item, response, file, fileList)"
                :on-error="(error, file, fileList) => handleUploadError(item, error, file, fileList)"
                :on-progress="(event, file, fileList) => handleUploadProgress(item, event, file, fileList)"
                :on-change="(file, fileList) => handleUploadChange(item, file, fileList)"
                :on-remove="(file, fileList) => handleUploadRemove(item, file, fileList)"
                :on-preview="(file) => handleUploadPreview(item, file)"
                :before-upload="(file) => handleBeforeUpload(item, file)"
                :before-remove="(file, fileList) => handleBeforeRemove(item, file, fileList)"
                :http-request="(options) => handleHttpRequest(item, options)"
              >
                <slot v-if="item.triggerSlot" :name="item.triggerSlot" :item="item">
                  <el-button v-if="!item.drag" :type="item.buttonType || 'primary'">
                    <el-icon v-if="item.uploadIcon"><component :is="item.uploadIcon || 'UploadFilled'" /></el-icon>
                    {{ item.buttonText || '点击上传' }}
                  </el-button>
                </slot>
                <template v-if="item.tipSlot" #tip>
                  <slot :name="item.tipSlot" :item="item">
                    <div class="el-upload__tip">{{ item.tip }}</div>
                  </slot>
                </template>
                <template v-if="item.triggerSlot" #trigger>
                  <slot :name="item.triggerSlot" :item="item" />
                </template>
              </el-upload>
            </template>

            <!-- 自动完成 -->
            <template v-else-if="item.type === 'autocomplete'">
              <el-autocomplete
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @select="handleAutocompleteSelect(item, $event)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
                @change="handleFieldChange(item, $event)"
              >
                <template v-if="item.prepend" #prepend>{{ item.prepend }}</template>
                <template v-if="item.append" #append>{{ item.append }}</template>
                <template v-if="item.prefix" #prefix>{{ item.prefix }}</template>
                <template v-if="item.suffix" #suffix>{{ item.suffix }}</template>
              </el-autocomplete>
            </template>

            <!-- 计数器 -->
            <template v-else-if="item.type === 'counter'">
              <el-input-number
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
              />
            </template>

            <!-- 文本展示 -->
            <template v-else-if="item.type === 'text' || item.type === 'display'">
              <div class="form-text-display" v-bind="item.textAttrs">
                {{ item.formatter ? item.formatter(formData[item.field], item, formData) : formData[item.field] }}
              </div>
            </template>

            <!-- HTML内容 -->
            <template v-else-if="item.type === 'html'">
              <div class="form-html-content" v-html="item.htmlContent || formData[item.field]" v-bind="item.htmlAttrs"></div>
            </template>

            <!-- 分割线 -->
            <template v-else-if="item.type === 'divider'">
              <el-divider v-bind="item.dividerAttrs">{{ item.dividerText }}</el-divider>
            </template>

            <!-- 警告 -->
            <template v-else-if="item.type === 'alert'">
              <el-alert v-bind="item.alertAttrs" :type="item.alertType || 'info'">
                <template v-if="item.alertTitleSlot" #title>
                  <slot :name="item.alertTitleSlot" :item="item" />
                </template>
              </el-alert>
            </template>

            <!-- 自定义插槽 -->
            <template v-else-if="item.type === 'slot' || item.type === 'custom'">
              <slot
                :name="item.slotName || item.field"
                :item="item"
                :value="formData[item.field]"
                :formData="formData"
                :onChange="(value) => handleSlotChange(item, value)"
              />
            </template>

            <!-- 自定义组件 -->
            <template v-else-if="item.type === 'component' && item.component">
              <component
                :is="item.component"
                v-model="formData[item.field]"
                v-bind="getItemProps(item)"
                @change="handleFieldChange(item, $event)"
                @blur="handleFieldBlur(item, $event)"
                @focus="handleFieldFocus(item, $event)"
              />
            </template>

            <!-- 默认插槽兜底 -->
            <slot
              v-else
              :name="item.field"
              :item="item"
              :value="formData[item.field]"
              :formData="formData"
              :onChange="(value) => handleSlotChange(item, value)"
            />
          </el-form-item>
        </el-col>

        <!-- 表单操作按钮 -->
        <el-col
          v-if="config.showButtons !== false"
          :span="config.buttonSpan || 24"
          :offset="config.buttonOffset"
          :xs="config.buttonXs"
          :sm="config.buttonSm"
          :md="config.buttonMd"
          :lg="config.buttonLg"
          :xl="config.buttonXl"
        >
          <el-form-item :class="['form-buttons', config.buttonClass]">
            <el-button
              v-if="config.showSubmit !== false"
              :type="config.submitType || 'primary'"
              :size="config.buttonSize || config.size || 'default'"
              :loading="submitLoading"
              :icon="config.submitIcon"
              :plain="config.submitPlain"
              :round="config.submitRound"
              :circle="config.submitCircle"
              :disabled="config.submitDisabled"
              @click="handleSubmit"
            >
              {{ config.submitText || (isEdit ? '更新' : '提交') }}
            </el-button>
            <el-button
              v-if="config.showReset !== false"
              :size="config.buttonSize || config.size || 'default'"
              :icon="config.resetIcon"
              :plain="config.resetPlain"
              :round="config.resetRound"
              :circle="config.resetCircle"
              :disabled="config.resetDisabled"
              @click="handleReset"
            >
              {{ config.resetText || '重置' }}
            </el-button>
            <el-button
              v-for="btn in customButtons"
              :key="btn.key"
              :type="btn.type"
              :size="btn.size || config.buttonSize || config.size || 'default'"
              :loading="btn.loading"
              :icon="btn.icon"
              :plain="btn.plain"
              :round="btn.round"
              :circle="btn.circle"
              :disabled="btn.disabled"
              @click="handleCustomButton(btn)"
            >
              {{ btn.text }}
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, getCurrentInstance } from 'vue'
import { UploadFilled } from '@element-plus/icons-vue'

const props = defineProps({
  // 表单配置
  config: {
    type: Object,
    default: () => ({})
  },
  // 表单项配置
  items: {
    type: Array,
    default: () => []
  },
  // 表单数据
  modelValue: {
    type: Object,
    default: () => ({})
  },
  // 表单验证规则
  rules: {
    type: Object,
    default: () => ({})
  },
  // 保存接口配置
  saveApi: {
    type: [String, Object, Function],
    default: null
  },
  // 更新接口配置
  updateApi: {
    type: [String, Object, Function],
    default: null
  },
  // 获取详情接口配置（用于编辑时回显数据）
  fetchApi: {
    type: [String, Object, Function],
    default: null
  },
  // 主键字段名（用于判断新增还是编辑）
  idKey: {
    type: String,
    default: 'id'
  },
  // 是否在提交前验证
  validateBeforeSubmit: {
    type: Boolean,
    default: true
  },
  // 提交前的钩子（返回false可阻止提交）
  beforeSubmit: {
    type: Function,
    default: null
  },
  // 提交后的钩子
  afterSubmit: {
    type: Function,
    default: null
  },
  // 自定义提交方法
  customSubmit: {
    type: Function,
    default: null
  },
  // 数据转换函数（提交前转换数据格式）
  dataTransform: {
    type: Function,
    default: null
  },
  // 响应数据转换函数（获取详情后转换数据格式）
  responseTransform: {
    type: Function,
    default: null
  }
})

const emit = defineEmits([
  'update:modelValue',
  'submit',
  'success',
  'error',
  'change',
  'blur',
  'focus',
  'input',
  'validate',
  'reset',
  'field-change',
  'field-blur',
  'field-focus',
  'field-visible-change'
])

const { proxy } = getCurrentInstance()
const formRef = ref()
const formData = reactive({})
const loading = ref(false)
const submitLoading = ref(false)

// 计算属性：表单项配置
const formItems = computed(() => props.items)

// 计算属性：是否为编辑模式
const isEdit = computed(() => {
  return !!(formData[props.idKey] || props.modelValue[props.idKey])
})

// 计算属性：自定义按钮
const customButtons = computed(() => {
  return props.config.customButtons || []
})

// 计算属性：表单验证规则
const computedRules = computed(() => {
  const rules = { ...props.rules }
  formItems.value.forEach(item => {
    if (item.rules) {
      rules[item.field] = item.rules
    }
    if (item.required && !rules[item.field]) {
      rules[item.field] = [
        {
          required: true,
          message: item.requiredMessage || `请输入${item.label}`,
          trigger: item.trigger || 'blur'
        }
      ]
    }
  })
  return rules
})

// 获取表单项的属性（过滤掉组件内部使用的属性）
const getItemProps = (item) => {
  const excludeKeys = [
    'field', 'label', 'type', 'required', 'rules', 'requiredMessage', 'trigger',
    'span', 'offset', 'xs', 'sm', 'md', 'lg', 'xl', 'tag', 'pull', 'push',
    'defaultValue', 'valueKey', 'labelKey', 'options', 'optionSlot', 'emptySlot',
    'prepend', 'append', 'prefix', 'suffix', 'prefixIcon', 'suffixIcon',
    'prependSlot', 'appendSlot', 'textAttrs', 'htmlAttrs', 'htmlContent',
    'dividerAttrs', 'dividerText', 'alertAttrs', 'alertType', 'alertTitleSlot',
    'slotName', 'component', 'componentProps', 'itemClass', 'formatter',
    'buttonText', 'buttonType', 'uploadIcon', 'triggerSlot', 'tipSlot', 'tip'
  ]
  const props = {}
  Object.keys(item).forEach(key => {
    if (!excludeKeys.includes(key)) {
      props[key] = item[key]
    }
  })
  return props
}

// 获取选项数据
const getOptions = (item) => {
  if (typeof item.options === 'function') {
    return item.options(item, formData)
  }
  return item.options || []
}

// 初始化表单数据
const initFormData = () => {
  // 清空现有数据
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  // 设置默认值或外部传入的值
  formItems.value.forEach(item => {
    if (item.field) {
      const externalValue = props.modelValue[item.field]
      if (externalValue !== undefined) {
        formData[item.field] = externalValue
      } else {
        formData[item.field] = item.defaultValue !== undefined
          ? item.defaultValue
          : getDefaultValue(item.type)
      }
    }
  })
}

// 获取不同类型的默认值
const getDefaultValue = (type) => {
  const defaultValues = {
    checkbox: [],
    switch: false,
    inputNumber: undefined,
    number: undefined,
    rate: 0,
    slider: 0,
    upload: [],
    transfer: [],
    treeSelect: null,
    cascader: [],
    timeSelect: ''
  }
  return defaultValues[type] !== undefined ? defaultValues[type] : ''
}

// 监听表单数据变化
watch(
  formData,
  (newVal) => {
    emit('update:modelValue', { ...newVal })
    emit('change', newVal)
  },
  { deep: true }
)

// 监听外部数据变化
watch(
  () => props.modelValue,
  (newVal) => {
    Object.keys(newVal).forEach(key => {
      if (Object.prototype.hasOwnProperty.call(formData, key)) {
        formData[key] = newVal[key]
      }
    })
  },
  { deep: true }
)

// 字段事件处理
const handleFieldInput = (item, event) => {
  emit('input', item.field, event.target ? event.target.value : event)
}

const handleFieldChange = (item, value) => {
  emit('field-change', item.field, value, formData)
  emit('change', item.field, value)
}

const handleFieldBlur = (item, event) => {
  emit('field-blur', item.field, event)
  emit('blur', item.field, event)
}

const handleFieldFocus = (item, event) => {
  emit('field-focus', item.field, event)
  emit('focus', item.field, event)
}

const handleFieldClear = (item) => {
  emit('field-clear', item.field)
}

const handleFieldVisibleChange = (item, visible) => {
  emit('field-visible-change', item.field, visible)
}

const handleFieldRemoveTag = (item, tag) => {
  emit('field-remove-tag', item.field, tag)
}

const handleCalendarChange = (item, value) => {
  emit('calendar-change', item.field, value)
}

const handlePanelChange = (item, value) => {
  emit('panel-change', item.field, value)
}

// 颜色选择器事件
const handleColorActiveChange = (item, color) => {
  emit('color-active-change', item.field, color)
}

// 级联选择器事件
const handleCascaderExpandChange = (item, value) => {
  emit('cascader-expand-change', item.field, value)
}

// 树形选择器事件
const handleTreeNodeClick = (item, data) => {
  emit('tree-node-click', item.field, data)
}

const handleTreeCheck = (item, data) => {
  emit('tree-check', item.field, data)
}

const handleTreeNodeExpand = (item, data) => {
  emit('tree-node-expand', item.field, data)
}

const handleTreeNodeCollapse = (item, data) => {
  emit('tree-node-collapse', item.field, data)
}

// 穿梭框事件
const handleTransferLeftCheckChange = (item, value) => {
  emit('transfer-left-check-change', item.field, value)
}

const handleTransferRightCheckChange = (item, value) => {
  emit('transfer-right-check-change', item.field, value)
}

// 自动完成事件
const handleAutocompleteSelect = (item, value) => {
  emit('autocomplete-select', item.field, value)
}

// 上传事件处理
const handleUploadSuccess = (item, response, file, fileList) => {
  if (item.onSuccess) {
    item.onSuccess(response, file, fileList, formData)
  }
  emit('upload-success', item.field, response, file, fileList)
}

const handleUploadError = (item, error, file, fileList) => {
  if (item.onError) {
    item.onError(error, file, fileList)
  }
  emit('upload-error', item.field, error, file, fileList)
}

const handleUploadProgress = (item, event, file, fileList) => {
  if (item.onProgress) {
    item.onProgress(event, file, fileList)
  }
  emit('upload-progress', item.field, event, file, fileList)
}

const handleUploadChange = (item, file, fileList) => {
  if (item.onChange) {
    item.onChange(file, fileList, formData)
  }
  emit('upload-change', item.field, file, fileList)
}

const handleUploadRemove = (item, file, fileList) => {
  if (item.onRemove) {
    item.onRemove(file, fileList, formData)
  }
  emit('upload-remove', item.field, file, fileList)
}

const handleUploadPreview = (item, file) => {
  if (item.onPreview) {
    item.onPreview(file)
  }
  emit('upload-preview', item.field, file)
}

const handleBeforeUpload = (item, file) => {
  if (item.beforeUpload) {
    return item.beforeUpload(file, formData)
  }
  emit('before-upload', item.field, file)
  return true
}

const handleBeforeRemove = (item, file, fileList) => {
  if (item.beforeRemove) {
    return item.beforeRemove(file, fileList, formData)
  }
  emit('before-remove', item.field, file, fileList)
  return true
}

const handleHttpRequest = (item, options) => {
  if (item.httpRequest) {
    return item.httpRequest(options, formData)
  }
  emit('http-request', item.field, options)
}

// 插槽变更处理
const handleSlotChange = (item, value) => {
  formData[item.field] = value
  emit('field-change', item.field, value, formData)
}

// 表单验证事件
const handleValidate = (prop, isValid, message) => {
  emit('validate', prop, isValid, message)
}

// 表单提交
const handleSubmit = async () => {
  try {
    // 如果有自定义提交方法，使用自定义方法
    if (props.customSubmit) {
      props.customSubmit(formData, { isEdit: isEdit.value })
      return
    }

    // 验证表单
    if (props.validateBeforeSubmit) {
      const valid = await formRef.value.validate()
      if (!valid) return
    }

    // 执行提交前钩子
    if (props.beforeSubmit) {
      const shouldContinue = await props.beforeSubmit(formData, isEdit.value)
      if (shouldContinue === false) return
    }

    submitLoading.value = true

    // 转换数据格式
    let submitData = props.dataTransform ? props.dataTransform(formData) : { ...formData }

    // 判断是新增还是编辑
    const apiUrl = isEdit.value ? props.updateApi : props.saveApi

    if (!apiUrl) {
      // 如果没有配置接口，直接触发提交事件
      emit('submit', submitData, isEdit.value)
      submitLoading.value = false
      return
    }

    // 发送请求
    proxy.$post({
      url: typeof apiUrl === 'function' ? apiUrl(isEdit.value) : apiUrl,
      data: submitData,
      callback: (response) => {
        submitLoading.value = false
        emit('success', response, submitData, isEdit.value)

        // 执行提交后钩子
        if (props.afterSubmit) {
          props.afterSubmit(response, submitData, isEdit.value)
        }
      },
      error: (err) => {
        submitLoading.value = false
        emit('error', err, submitData, isEdit.value)
      }
    })
  } catch (error) {
    submitLoading.value = false
    emit('validate', false, error)
  }
}

// 表单重置
const handleReset = () => {
  formRef.value.resetFields()
  initFormData()
  emit('reset')
}

// 获取详情数据（用于编辑）
const fetchDetail = async (id) => {
  if (!props.fetchApi) return

  loading.value = true
  try {
    proxy.$post({
      url: typeof props.fetchApi === 'function' ? props.fetchApi(id) : props.fetchApi,
      data: { [props.idKey]: id },
      callback: (response) => {
        const data = props.responseTransform ? props.responseTransform(response) : response
        Object.keys(data).forEach(key => {
          if (Object.prototype.hasOwnProperty.call(formData, key)) {
            formData[key] = data[key]
          }
        })
        emit('update:modelValue', { ...formData })
        loading.value = false
      },
      error: (err) => {
        loading.value = false
        emit('error', err)
      }
    })
  } catch (error) {
    loading.value = false
    emit('error', error)
  }
}

// 表单验证
const validate = async () => {
  try {
    const valid = await formRef.value.validate()
    emit('validate', true)
    return valid
  } catch (error) {
    emit('validate', false, error)
    return false
  }
}

// 验证指定字段
const validateField = async (prop) => {
  try {
    await formRef.value.validateField(prop)
    return true
  } catch (error) {
    return false
  }
}

// 清除验证
const clearValidate = (fields) => {
  formRef.value.clearValidate(fields)
}

// 重置表单
const resetFields = () => {
  formRef.value.resetFields()
  initFormData()
}

// 设置表单数据
const setFormData = (data) => {
  Object.keys(data).forEach(key => {
    if (Object.prototype.hasOwnProperty.call(formData, key)) {
      formData[key] = data[key]
    }
  })
  emit('update:modelValue', { ...formData })
}

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

// 设置字段值
const setFieldValue = (field, value) => {
  formData[field] = value
}

// 获取字段值
const getFieldValue = (field) => {
  return formData[field]
}

// 暴露方法和属性
defineExpose({
  formRef,
  validate,
  validateField,
  clearValidate,
  resetFields,
  setFormData,
  getFormData,
  setFieldValue,
  getFieldValue,
  fetchDetail,
  handleSubmit,
  formData,
  isEdit
})

onMounted(() => {
  initFormData()
})
</script>

<style scoped lang="less">
.super-form {
  .form-text-display {
    padding: 0 11px;
    line-height: 32px;
    color: #606266;
    word-break: break-all;
  }

  .form-html-content {
    padding: 0 11px;
    line-height: 1.5;
    color: #606266;
  }

  .form-buttons {
    :deep(.el-form-item__content) {
      display: flex;
      justify-content: flex-end;
      align-items: center;
      gap: 12px;
      flex-wrap: wrap;
    }
  }

  :deep(.el-input-number) {
    width: 100%;
  }

  :deep(.el-select) {
    width: 100%;
  }

  :deep(.el-cascader) {
    width: 100%;
  }

  :deep(.el-tree-select) {
    width: 100%;
  }

  :deep(.el-date-editor) {
    width: 100%;
  }

  :deep(.el-time-picker) {
    width: 100%;
  }

  :deep(.el-autocomplete) {
    width: 100%;
  }

  :deep(.el-color-picker) {
    .el-color-picker__mask {
      border-radius: 4px;
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
    color: #303133;
  }

  :deep(.el-form-item) {
    margin-bottom: 18px;
  }

  :deep(.el-form--inline) {
    .el-form-item {
      display: inline-flex;
      vertical-align: middle;
      margin-right: 10px;
    }
  }

  :deep(.el-transfer) {
    text-align: left;
  }

  :deep(.el-upload) {
    .el-upload-dragger {
      padding: 40px;
    }
  }
}
</style>
