<template>
  <div class="form-builder">
    <!-- 表单构建器标题 -->
    <div class="form-builder-header">
      <h4>{{ title }}</h4>
      <div class="header-actions">
        <el-select v-model="selectedFieldType" placeholder="选择字段类型" style="width: 120px; margin-right: 8px;">
          <el-option v-for="type in availableFieldTypes" :key="type" :label="getFieldTypeLabel(type)" :value="type" />
        </el-select>
        <el-button type="primary" @click="() => addItem(selectedFieldType)">
          <Icon icon="ep:plus" />
          添加项目
        </el-button>
      </div>
    </div>

    <!-- 表单项列表 -->
    <div class="form-items-list">
      <div v-for="(item, index) in formItems" :key="item.id" class="form-item-card">
        <div class="form-item-header">
          <span class="item-index">第 {{ index + 1 }} 个质检项目</span>
          <div class="item-actions">
            <el-button type="primary" size="small" @click="moveUp(index)" :disabled="index === 0">
              <Icon icon="ep:arrow-up" />
            </el-button>
            <el-button type="primary" size="small" @click="moveDown(index)" :disabled="index === formItems.length - 1">
              <Icon icon="ep:arrow-down" />
            </el-button>
            <el-button type="danger" size="small" @click="removeItem(index)">
              <Icon icon="ep:delete" />
            </el-button>
          </div>
        </div>

        <div class="form-item-content">
          <el-row :gutter="16">
            <el-col :span="6">
              <el-form-item label="项目名称" :prop="`items.${index}.label`">
                <el-input v-model="item.label" placeholder="请输入项目标题" @input="handleItemChange" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目key（建议保持默认）" :prop="`items.${index}.key`">
                <el-input v-model="item.key" placeholder="请输入项目键值" @input="handleItemChange" />
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="输入类型" :prop="`items.${index}.type`">
                <el-select v-model="item.type" placeholder="选择类型" @change="handleTypeChange(index, $event)">
                  <el-option v-for="type in availableFieldTypes" :key="type" :label="getFieldTypeLabel(type)"
                    :value="type" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="默认值" :prop="`items.${index}.defaultValue`">
                <!-- 根据字段类型显示不同的输入控件 -->
                <el-input v-if="item.type === 'text' || item.type === 'textarea'" v-model="item.defaultValue"
                  :type="item.type === 'textarea' ? 'textarea' : 'text'" :rows="item.type === 'textarea' ? 2 : 1"
                  placeholder="请输入默认值" @input="handleItemChange" />
                <el-input-number v-else-if="item.type === 'number'" v-model="item.defaultValue" placeholder="请输入数字"
                  @change="handleItemChange" style="width: 100%" />
                <el-select v-else-if="item.type === 'select'" v-model="item.defaultValue" placeholder="请选择默认值"
                  @change="handleItemChange" style="width: 100%">
                  <el-option label="选项1" value="option1" />
                  <el-option label="选项2" value="option2" />
                </el-select>
                <el-switch v-else-if="item.type === 'switch'" v-model="item.defaultValue" @change="handleItemChange" />
                <el-date-picker v-else-if="item.type === 'date'" v-model="item.defaultValue" type="date"
                  placeholder="选择日期" @change="handleItemChange" style="width: 100%" />
                <el-input v-else v-model="item.defaultValue" placeholder="请输入默认值" @input="handleItemChange" />
              </el-form-item>
            </el-col>
          </el-row>

          <!-- text类型特殊配置 -->
          <el-row :gutter="16" v-if="item.type === 'text'" style="margin-top: 16px; padding: 16px; background: #f0f9ff; border-radius: 8px; border: 1px solid #e0f2fe;">
            <el-col :span="24">
              <div style="display: flex; align-items: center; margin-bottom: 12px;">
                <Icon icon="ep:document-copy" style="color: #0ea5e9; margin-right: 8px;" />
                <span style="font-weight: 600; color: #0f172a;">文本字段配置</span>
                <el-tooltip content="为文本字段设置显示行数和最大长度限制" placement="top">
                  <Icon icon="ep:question-filled" style="color: #64748b; margin-left: 8px; cursor: help;" />
                </el-tooltip>
              </div>
            </el-col>
            <el-col :span="12">
              <el-form-item label="显示行数">
                <el-input-number v-model="item.rows" :min="1" :max="10" placeholder="行数" @change="handleItemChange" style="width: 100%" />
                <div style="font-size: 12px; color: #64748b; margin-top: 4px;">
                  设置文本框的显示行数（1-10行）
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大长度">
                <el-input-number v-model="item.maxlength" :min="1" :max="10000" placeholder="字符数" @change="handleItemChange" style="width: 100%" />
                <div style="font-size: 12px; color: #64748b; margin-top: 4px;">
                  设置允许输入的最大字符数
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <!-- 质检标准配置 -->
          <el-row :gutter="16"
            style="margin-top: 16px; padding: 16px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef;">
            <el-col :span="24">
              <div style="display: flex; align-items: center; margin-bottom: 12px;">
                <Icon icon="ep:info-filled" style="color: #409eff; margin-right: 8px;" />
                <span style="font-weight: 600; color: #303133;">质检标准配置</span>
                <el-tooltip content="为这个字段设置质检标准，帮助质检员了解检验要求" placement="top">
                  <Icon icon="ep:question-filled" style="color: #909399; margin-left: 8px; cursor: help;" />
                </el-tooltip>
              </div>
            </el-col>
            <el-col :span="8">
              <el-form-item label="标准描述" :required="true">
                <el-input v-model="item.standard" placeholder="例如：重量必须符合标准要求" @input="handleItemChange" />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  描述这个字段的质检标准要求
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="标准类型">
                <div style="padding: 8px 12px; background: #f5f7fa; border-radius: 4px; color: #606266; font-size: 14px;">
                  {{ getStandardTypeLabel(item.standardType) }}
                </div>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  根据字段类型自动设置
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item :label="getStandardValueLabel(item.standardType)">
                <el-input v-if="item.standardType === 'text'" v-model="item.standardValue" placeholder="例如：合格"
                  @input="handleItemChange" />
                <div v-else-if="item.standardType === 'range'" style="display: flex; gap: 8px;">
                  <el-input-number v-model="item.standardRange!.min" placeholder="最小值" @change="handleItemChange"
                    style="flex: 1" />
                  <span style="line-height: 32px;">~</span>
                  <el-input-number v-model="item.standardRange!.max" placeholder="最大值" @change="handleItemChange"
                    style="flex: 1" />
                </div>
                <el-button v-else-if="item.standardType === 'select'" type="primary" size="small" @click="editStandardOptions(index)">
                  <Icon icon="ep:setting" />
                  编辑选项
                </el-button>
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  {{ getStandardValueHint(item.standardType) }}
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="显示标准">
                <el-switch v-model="item.showStandard" @change="handleItemChange" />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  在表单中显示标准
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="3">
              <el-form-item label="必填">
                <el-switch v-model="item.required" @change="handleItemChange" />
                <div style="font-size: 12px; color: #909399; margin-top: 4px;">
                  此字段是否必填
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="formItems.length === 0" class="empty-state">
        <el-empty description="暂无表单项，点击上方按钮添加">
          <el-button type="primary" @click="() => addItem()">
            <Icon icon="ep:plus" />
            添加第一个项目
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 预览区域 -->
    <div v-if="formItems.length > 0" class="preview-section">
      <el-divider content-position="left">预览效果</el-divider>
      <div class="preview-content">
        <DynamicForm v-model="previewData" :items="dynamicFormItems" :gutter="16" :column-span="12"
          @form-change="handlePreviewChange" />
      </div>
    </div>
  </div>
</template>

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

// 定义Props
interface Props {
  modelValue?: FormBuilderItem[]
  title?: string
  mode?: 'simple' | 'advanced' | 'custom'
  showPreview?: boolean
  allowDrag?: boolean
  customFieldTypes?: FormFieldType[]
}

// 定义Emits
interface Emits {
  (e: 'update:modelValue', value: FormBuilderItem[]): void
  (e: 'change', value: FormBuilderItem[]): void
  (e: 'preview-change', value: Record<string, any>): void
  (e: 'itemAdd', item: FormBuilderItem): void
  (e: 'itemRemove', item: FormBuilderItem): void
  (e: 'itemUpdate', item: FormBuilderItem, index: number): void
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
  title: '表单构建器',
  mode: 'simple',
  showPreview: true,
  allowDrag: true,
  customFieldTypes: () => ['text', 'number', 'select']
})

const emit = defineEmits<Emits>()

// 表单数据
const formItems = ref<FormBuilderItem[]>([...props.modelValue])
const previewData = ref<Record<string, any>>({})
const selectedFieldType = ref<FormFieldType>('text')

// 初始化时确保标准字段有默认值
formItems.value.forEach(item => {
  if (!item.standard) item.standard = ''
  if (!item.standardType) item.standardType = 'text'
  if (!item.standardValue) item.standardValue = ''
  if (!item.standardRange) item.standardRange = { min: 0, max: 100 }
  if (!item.standardOptions) item.standardOptions = []
  if (item.showStandard === undefined) item.showStandard = true
})

// 可用的字段类型
const availableFieldTypes = computed(() => {
  return props.customFieldTypes || ['text', 'number', 'select']
})

// 获取字段类型标签
const getFieldTypeLabel = (type: FormFieldType): string => {
  const labels: Record<FormFieldType, string> = {
    text: '文本',
    number: '数字',
    select: '选择器',
    textarea: '多行文本',
    date: '日期',
    switch: '开关',
    radio: '单选框',
    checkbox: '复选框',
    custom: '自定义',
    time: '时间',
    slider: '滑块'
  }
  return labels[type] || type
}

// 生成唯一ID
const generateId = () => {
  return `item_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
}

// 转换为DynamicFormItem格式
const dynamicFormItems = computed<DynamicFormItem[]>(() => {
  return formItems.value.map(item => ({
    key: item.key,
    label: item.label,
    type: item.type,
    placeholder: item.placeholder || `请输入${item.label}`,
    defaultValue: item.defaultValue,
    required: item.required,
    disabled: item.disabled,
    // 传递质检标准相关属性
    standard: item.standard,
    standardType: item.standardType,
    standardValue: item.standardValue,
    standardRange: item.standardRange,
    standardOptions: item.standardOptions,
    showStandard: item.showStandard,
    // 传递其他属性
    ...(item.type === 'number' && {
      min: item.min,
      max: item.max,
      step: item.step,
      precision: item.precision
    }),
    ...(item.type === 'textarea' && {
      rows: item.rows,
      maxlength: item.maxlength
    }),
    ...(item.type === 'select' && {
      options: item.options || []
    }),
    ...(item.type === 'date' && {
      dateType: item.dateType || 'date',
      format: item.format,
      valueFormat: item.valueFormat
    }),
    ...(item.type === 'switch' && {
      activeText: item.activeText,
      inactiveText: item.inactiveText
    }),
    rules: item.rules
  }))
})

// 添加表单项
const addItem = (type: FormFieldType = 'text') => {
  // 根据字段类型自动设置标准类型
  const standardType = getDefaultStandardType(type)

  const newItem: FormBuilderItem = {
    id: generateId(),
    label: `项目${formItems.value.length + 1}`,
    key: `item_${formItems.value.length + 1}`,
    type,
    defaultValue: getDefaultValueByType(type),
    placeholder: `请输入${type === 'text' ? '文本' : type === 'number' ? '数字' : '内容'}`,
    // text类型特有属性
    ...(type === 'text' && {
      rows: 1,
      maxlength: 100
    }),
    // 初始化标准字段（根据类型自动设置）
    standard: '',
    standardType,
    standardValue: '',
    standardRange: { min: 0, max: 100 },
    standardOptions: [],
    showStandard: true,
    required: false
  }
  formItems.value.push(newItem)
  handleItemChange()
  emit('itemAdd', newItem)
}

// 根据字段类型获取默认标准类型
const getDefaultStandardType = (type: FormFieldType): string => {
  switch (type) {
    case 'text':
      return 'text'
    case 'number':
      return 'range'
    case 'select':
      return 'select'
    default:
      return 'text'
  }
}

// 获取标准类型显示标签
const getStandardTypeLabel = (standardType: string): string => {
  const labels: Record<string, string> = {
    text: '📄 文本标准',
    number: '🔢 数值标准',
    range: '📊 范围标准',
    select: '✅ 选择标准'
  }
  return labels[standardType] || standardType
}

// 获取标准值标签
const getStandardValueLabel = (standardType: string): string => {
  switch (standardType) {
    case 'text':
      return '期望文本'
    case 'range':
      return '数值范围'
    case 'select':
      return '标准选项'
    default:
      return '标准值'
  }
}

// 获取标准值提示
const getStandardValueHint = (standardType: string): string => {
  switch (standardType) {
    case 'text':
      return '输入期望的文本值'
    case 'range':
      return '设置允许的数值范围'
    case 'select':
      return '设置可选的标准选项'
    default:
      return '设置标准值'
  }
}

// 根据类型获取默认值
const getDefaultValueByType = (type: FormFieldType): any => {
  switch (type) {
    case 'number':
      return 0
    case 'switch':
      return false
    case 'select':
    case 'radio':
    case 'checkbox':
      return []
    case 'date':
      return null
    default:
      return ''
  }
}

// 删除表单项
const removeItem = (index: number) => {
  formItems.value.splice(index, 1)
  handleItemChange()
}

// 上移表单项
const moveUp = (index: number) => {
  if (index > 0) {
    const item = formItems.value.splice(index, 1)[0]
    formItems.value.splice(index - 1, 0, item)
    handleItemChange()
  }
}

// 下移表单项
const moveDown = (index: number) => {
  if (index < formItems.value.length - 1) {
    const item = formItems.value.splice(index, 1)[0]
    formItems.value.splice(index + 1, 0, item)
    handleItemChange()
  }
}

// 处理字段类型变化
const handleTypeChange = (index: number, newType: FormFieldType) => {
  const item = formItems.value[index]
  if (item) {
    // 根据新的字段类型自动更新标准类型
    item.standardType = getDefaultStandardType(newType)

    // 重置相关字段的值
    item.standardValue = ''
    item.standardRange = { min: 0, max: 100 }
    item.standardOptions = []

    // 为text类型添加默认属性
    if (newType === 'text') {
      item.rows = item.rows || 1
      item.maxlength = item.maxlength || 100
    }
  }
  handleItemChange()
}

// 处理表单项变化
const handleItemChange = () => {
  // 确保所有标准字段都有值，并根据字段类型自动设置标准类型
  formItems.value.forEach(item => {
    if (!item.standard) item.standard = ''
    if (!item.standardType) {
      // 如果没有标准类型，根据字段类型设置默认值
      item.standardType = getDefaultStandardType(item.type)
    }
    if (!item.standardValue) item.standardValue = ''
    if (!item.standardRange) item.standardRange = { min: 0, max: 100 }
    if (!item.standardOptions) item.standardOptions = []
    if (item.showStandard === undefined) item.showStandard = true
  })

  emit('update:modelValue', [...formItems.value])
  emit('change', [...formItems.value])

  // 更新预览数据
  updatePreviewData()
}

// 更新预览数据
const updatePreviewData = () => {
  const newPreviewData: Record<string, any> = {}
  formItems.value.forEach(item => {
    if (item.defaultValue !== null && item.defaultValue !== undefined && item.defaultValue !== '') {
      newPreviewData[item.key] = item.defaultValue
    }
  })
  previewData.value = newPreviewData
  emit('preview-change', newPreviewData)
}

// 处理预览数据变化
const handlePreviewChange = (value: Record<string, any>) => {
  console.log('FormBuilder预览数据变化:', value)
  previewData.value = value
  emit('preview-change', value)
}

// 监听外部数据变化
watch(() => props.modelValue, (newValue) => {
  formItems.value = [...newValue]
  // 确保标准字段有默认值
  formItems.value.forEach(item => {
    if (!item.standard) item.standard = ''
    if (!item.standardType) item.standardType = 'text'
    if (!item.standardValue) item.standardValue = ''
    if (!item.standardRange) item.standardRange = { min: 0, max: 100 }
    if (!item.standardOptions) item.standardOptions = []
    if (item.showStandard === undefined) item.showStandard = true
  })
  updatePreviewData()
}, { deep: true })

// 暴露方法
const getFormItems = () => {
  return [...formItems.value]
}

const setFormItems = (items: FormBuilderItem[]) => {
  formItems.value = [...items]
  handleItemChange()
}

const clearItems = () => {
  formItems.value = []
  handleItemChange()
}

const addItemWithData = (label: string, key: string, type: FormFieldType = 'text', defaultValue: any = '') => {
  const standardType = getDefaultStandardType(type)

  const newItem: FormBuilderItem = {
    id: generateId(),
    label,
    key,
    type,
    defaultValue,
    // 初始化标准字段
    standard: '',
    standardType,
    standardValue: '',
    standardRange: { min: 0, max: 100 },
    standardOptions: [],
    showStandard: true,
    required: false
  }
  formItems.value.push(newItem)
  handleItemChange()
}

// 编辑标准选项
const editStandardOptions = (index: number) => {
  const item = formItems.value[index]
  if (!item.standardOptions) {
    item.standardOptions = []
  }

  // 构建当前选项的文本
  const currentOptions = item.standardOptions.map(opt => opt.label).join('，')

  // 使用更友好的提示
  const newOptions = prompt(
    `📋 编辑标准选项\n\n当前选项：${currentOptions || '无'}\n\n请输入新的标准选项，用逗号分隔：\n例如：合格,不合格,待定`,
    currentOptions
  )

  if (newOptions !== null) {
    if (newOptions.trim()) {
      // 解析新选项
      const options = newOptions.split(',').map((label, idx) => ({
        label: label.trim(),
        value: `option_${idx + 1}`,
        disabled: false
      })).filter(opt => opt.label) // 过滤空选项

      item.standardOptions = options
      handleItemChange()

      // 显示成功提示
      console.log(`已设置 ${options.length} 个标准选项：${options.map(opt => opt.label).join('，')}`)
    } else {
      // 清空选项
      item.standardOptions = []
      handleItemChange()
    }
  }
}

defineExpose({
  getFormItems,
  setFormItems,
  clearItems,
  addItemWithData
})
</script>

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

.form-builder-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e4e7ed;
}

.header-actions {
  display: flex;
  align-items: center;
}

.form-builder-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.form-items-list {
  margin-bottom: 24px;
}

.form-item-card {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  margin-bottom: 16px;
  background: #fff;
  transition: all 0.3s ease;
}

.form-item-card:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.form-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
}

.item-index {
  font-weight: 500;
  color: #606266;
}

.item-actions {
  display: flex;
  gap: 8px;
}

.form-item-content {
  padding: 16px;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  background: #fafafa;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
}

.preview-section {
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}

.preview-content {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

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

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

:deep(.el-button + .el-button) {
  margin-left: 8px;
}
</style>
