<template>
  <div class="dynamic-form">
    <!-- 表单标题 -->
    <el-divider v-if="title" content-position="left">{{ title }}</el-divider>

    <!-- 动态表单项目 -->
    <el-row :gutter="gutter">
      <el-col v-for="item in formItems" :key="item.key" :span="getColumnSpan(item)">
        <el-form-item :label="item.label" :required="item.required">
          <div class="form-field-container">
            <!-- 输入控件区域 -->
            <div class="form-field-input" :class="{ 'with-standard': item.showStandard && item.standard }">
              <!-- 数字输入 -->
              <el-input-number v-if="item.type === 'number'" v-model="formData[item.key]" :min="item.min"
                :max="item.max" :precision="item.precision || 0" :step="item.step || 1" :placeholder="item.placeholder"
                :disabled="item.disabled" :clearable="item.clearable !== false" style="width: 100%"
                @change="handleFieldChange(item.key, $event)" />

              <!-- 文本输入 -->
              <el-input v-else-if="item.type === 'text'" v-model="formData[item.key]" :type="item.inputType || 'text'"
                :placeholder="item.placeholder" :disabled="item.disabled" :clearable="item.clearable !== false"
                :rows="item.rows || 1" :maxlength="item.maxlength" :show-word-limit="!!item.maxlength"
                @input="handleFieldChange(item.key, $event)" />

              <!-- 多行文本 -->
              <el-input v-else-if="item.type === 'textarea'" v-model="formData[item.key]" type="textarea"
                :placeholder="item.placeholder" :disabled="item.disabled" :clearable="item.clearable !== false"
                :rows="item.rows || 3" @input="handleFieldChange(item.key, $event)" />

              <!-- 选择器 -->
              <el-select v-else-if="item.type === 'select'" v-model="formData[item.key]" :placeholder="item.placeholder"
                :disabled="item.disabled" :clearable="item.clearable !== false" :filterable="item.filterable"
                :multiple="item.multiple" style="width: 100%" @change="handleFieldChange(item.key, $event)">
                <el-option v-for="option in item.options" :key="option.value" :label="option.label"
                  :value="option.value" :disabled="option.disabled" />
              </el-select>

              <!-- 日期选择 -->
              <el-date-picker v-else-if="item.type === 'date'" v-model="formData[item.key]"
                :type="item.dateType || 'date'" :placeholder="item.placeholder" :disabled="item.disabled"
                :clearable="item.clearable !== false" :format="item.format" :value-format="item.valueFormat"
                style="width: 100%" @change="handleFieldChange(item.key, $event)" />

              <!-- 时间选择 -->
              <el-time-picker v-else-if="item.type === 'time'" v-model="formData[item.key]"
                :placeholder="item.placeholder" :disabled="item.disabled" :clearable="item.clearable !== false"
                :format="item.format || 'HH:mm:ss'" :value-format="item.valueFormat || 'HH:mm:ss'" style="width: 100%"
                @change="handleFieldChange(item.key, $event)" />

              <!-- 开关 -->
              <el-switch v-else-if="item.type === 'switch'" v-model="formData[item.key]" :disabled="item.disabled"
                :active-text="item.activeText" :inactive-text="item.inactiveText"
                @change="handleFieldChange(item.key, $event)" />

              <!-- 单选框组 -->
              <el-radio-group v-else-if="item.type === 'radio'" v-model="formData[item.key]" :disabled="item.disabled"
                @change="handleFieldChange(item.key, $event)">
                <el-radio v-for="option in item.options" :key="option.value" :value="option.value"
                  :disabled="option.disabled">
                  {{ option.label }}
                </el-radio>
              </el-radio-group>

              <!-- 复选框组 -->
              <el-checkbox-group v-else-if="item.type === 'checkbox'" v-model="formData[item.key]"
                :disabled="item.disabled" @change="handleFieldChange(item.key, $event)">
                <el-checkbox v-for="option in item.options" :key="option.value" :value="option.value"
                  :disabled="option.disabled">
                  {{ option.label }}
                </el-checkbox>
              </el-checkbox-group>

              <!-- 滑块 -->
              <el-slider v-else-if="item.type === 'slider'" v-model="formData[item.key]" :min="item.min || 0"
                :max="item.max || 100" :step="item.step || 1" :disabled="item.disabled" :show-input="item.showInput"
                :show-stops="item.showStops" :show-tooltip="item.showTooltip"
                @change="handleFieldChange(item.key, $event)" />

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

              <!-- 未知类型提示 -->
              <div v-else class="unknown-type">
                <el-alert :title="`未知的表单类型: ${item.type}`" type="warning" :closable="false" />
              </div>
            </div>

            <!-- 质检标准显示区域 -->
            <div
              v-if="item.showStandard && (item.standard || item.standardValue || item.standardRange || item.standardOptions?.length)"
              class="form-field-standard">
              <el-tooltip :content="getStandardTooltip(item)" placement="top">
                <div class="standard-display">
                  <Icon icon="ep:info-filled" class="standard-icon" />
                  <span class="standard-text">{{ getStandardDisplayText(item) }}</span>
                </div>
              </el-tooltip>
            </div>
          </div>
        </el-form-item>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue'
import type { DynamicFormItem } from './types'

// 定义Props
interface Props {
  modelValue?: Record<string, any>
  items?: DynamicFormItem[]
  title?: string
  gutter?: number
  columnSpan?: number
  formProp?: string
}

// 定义Emits
interface Emits {
  (e: 'update:modelValue', value: Record<string, any>): void
  (e: 'fieldChange', key: string, value: any, item: DynamicFormItem): void
  (e: 'formChange', value: Record<string, any>): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => ({}),
  items: () => [],
  title: '',
  gutter: 16,
  columnSpan: 12,
  formProp: ''
})

const emit = defineEmits<Emits>()

// 表单数据
const formData = ref<Record<string, any>>({ ...props.modelValue })

// 计算属性
const formItems = computed(() => props.items)

// 获取列跨度
const getColumnSpan = (item: DynamicFormItem) => {
  if (item.fullWidth) return 24
  return item.span || props.columnSpan
}


// 处理字段变化
const handleFieldChange = (key: string, value: any) => {
  formData.value[key] = value

  // 查找对应的表单项配置
  const item = formItems.value.find(item => item.key === key)

  // 触发事件
  emit('fieldChange', key, value, item!)
  emit('update:modelValue', { ...formData.value })
  emit('formChange', { ...formData.value })
}

// 获取标准显示文本（只显示标准值）
const getStandardDisplayText = (item: DynamicFormItem): string => {
  // 如果没有标准信息，不显示
  if (!item.standardValue && !item.standardRange && !item.standardOptions?.length) {
    return ''
  }

  // 根据标准类型显示标准值
  switch (item.standardType) {
    case 'text':
      return item.standardValue || ''
    case 'number':
      return item.standardValue !== undefined ? String(item.standardValue) : ''
    case 'range':
      if (item.standardRange) {
        const { min, max } = item.standardRange
        // 如果只有最小值（max为null、undefined或0）
        if (min !== undefined && min !== null && (max === undefined || max === null || max === 0)) {
          return `≥${min}`
        }
        // 如果只有最大值（min为null、undefined或0）
        if ((min === undefined || min === null || min === 0) && max !== undefined && max !== null) {
          return `≤${max}`
        }
        // 如果有范围（两个值都有且不为null/undefined/0）
        if (min !== undefined && min !== null && max !== undefined && max !== null && min !== 0 && max !== 0) {
          return `${min}~${max}`
        }
      }
      return ''
    case 'select':
      return item.standardOptions?.length ? item.standardOptions.map(opt => opt.label).join(', ') : ''
    default:
      return ''
  }
}

// 获取标准提示内容（只显示标准描述）
const getStandardTooltip = (item: DynamicFormItem): string => {
  // 只显示标准描述
  return item.standard || ''
}

// 监听外部数据变化
watch(() => props.modelValue, (newValue) => {
  formData.value = { ...newValue }
}, { deep: true })

// 暴露方法
const getFormData = () => {
  return { ...formData.value }
}

const setFormData = (data: Record<string, any>) => {
  formData.value = { ...data }
  emit('update:modelValue', { ...formData.value })
}

const resetForm = () => {
  formData.value = {}
  emit('update:modelValue', {})
}

const validateForm = () => {
  // 这里可以添加表单验证逻辑
  return true
}

defineExpose({
  getFormData,
  setFormData,
  resetForm,
  validateForm
})
</script>

<style scoped>
.dynamic-form {
  width: 100%;
}

.unknown-type {
  margin: 8px 0;
}

.form-field-container {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.form-field-input {
  flex: 1;
}

.form-field-input.with-standard {
  flex: 0 0 calc(100% - 200px);
}

.form-field-standard {
  flex: 0 0 180px;
  margin-top: 4px;
}

.standard-display {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.standard-display:hover {
  background: #e0f2fe;
  border-color: #7dd3fc;
}

.standard-icon {
  color: #0ea5e9;
  font-size: 14px;
}

.standard-text {
  color: #0369a1;
  font-size: 12px;
  font-weight: 500;
  line-height: 1.4;
  word-break: break-all;
}

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

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

/* 响应式设计 */
@media (max-width: 768px) {
  .form-field-container {
    flex-direction: column;
    gap: 8px;
  }

  .form-field-input.with-standard {
    flex: 1;
  }

  .form-field-standard {
    flex: 1;
  }
}
</style>
