<template>
  <div class="field-designer">
    <!-- 左侧：字段列表 -->
    <div class="field-list-panel">
      <div class="panel-header">
        <h3>字段列表</h3>
        <el-button type="primary" size="small" @click="handleAddField">
          <el-icon><Plus /></el-icon>
          添加字段
        </el-button>
      </div>

      <div class="field-list">
        <draggable
          v-model="localFields"
          item-key="id"
          @end="handleDragEnd"
        >
          <template #item="{ element: field }">
            <div
              class="field-item"
              :class="{ active: selectedFieldId === field.id }"
              @click="handleSelectField(field)"
            >
              <div class="field-info">
                <el-icon class="drag-handle"><Rank /></el-icon>
                <span class="field-label">{{ field.label }}</span>
                <el-tag size="small" class="field-type-tag">{{ getFieldTypeLabel(field.fieldType) }}</el-tag>
              </div>
              <div class="field-actions">
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click.stop="handleEditField(field)"
                >
                  编辑
                </el-button>
                <el-button
                  type="danger"
                  link
                  size="small"
                  @click.stop="handleDeleteField(field)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </template>
        </draggable>
      </div>
    </div>

    <!-- 右侧：字段配置 -->
    <div class="field-config-panel">
      <div class="panel-header">
        <h3>字段配置</h3>
      </div>

      <div v-if="selectedField" class="field-config-form">
        <el-form :model="selectedField" label-width="100px">
          <el-form-item label="字段标识">
            <el-input v-model="selectedField.name" placeholder="请输入字段标识" />
          </el-form-item>

          <el-form-item label="字段名称">
            <el-input v-model="selectedField.label" placeholder="请输入字段名称" />
          </el-form-item>

          <el-form-item label="字段类型">
            <el-select v-model="selectedField.fieldType" placeholder="请选择字段类型">
              <el-option label="单行文本" value="text" />
              <el-option label="多行文本" value="textarea" />
              <el-option label="数字" value="number" />
              <el-option label="日期" value="date" />
              <el-option label="下拉选择" value="select" />
              <el-option label="多选下拉" value="multiselect" />
              <el-option label="开关" value="boolean" />
              <el-option label="树形选择" value="tree" />
            </el-select>
          </el-form-item>

          <el-form-item label="占位符">
            <el-input v-model="selectedField.placeholder" placeholder="请输入占位符" />
          </el-form-item>

          <el-form-item label="是否必填">
            <el-switch v-model="selectedField.required" />
          </el-form-item>

          <el-form-item label="默认值">
            <el-input v-model="selectedField.defaultValue" placeholder="请输入默认值" />
          </el-form-item>

          <el-form-item label="栅格占列">
            <el-slider v-model="selectedField.span" :min="1" :max="24" show-stops />
          </el-form-item>

          <!-- 选项配置（用于select/multiselect） -->
          <template v-if="['select', 'multiselect'].includes(selectedField.fieldType)">
            <el-form-item label="选项配置">
              <div class="options-config">
                <div
                  v-for="(option, index) in selectedField.options"
                  :key="index"
                  class="option-item"
                >
                  <el-input v-model="option.label" placeholder="选项名称" size="small" />
                  <el-input v-model="option.value" placeholder="选项值" size="small" />
                  <el-button
                    type="danger"
                    icon="Delete"
                    size="small"
                    circle
                    @click="handleDeleteOption(index)"
                  />
                </div>
                <el-button
                  type="primary"
                  link
                  size="small"
                  @click="handleAddOption"
                >
                  添加选项
                </el-button>
              </div>
            </el-form-item>
          </template>

          <!-- 验证规则配置 -->
          <el-divider content-position="left">验证规则</el-divider>

          <template v-if="['text', 'textarea'].includes(selectedField.fieldType)">
            <el-form-item label="最小长度">
              <el-input-number v-model="selectedField.validationRules.min" :min="0" />
            </el-form-item>
            <el-form-item label="最大长度">
              <el-input-number v-model="selectedField.validationRules.max" :min="0" />
            </el-form-item>
          </template>

          <template v-if="selectedField.fieldType === 'number'">
            <el-form-item label="最小值">
              <el-input-number v-model="selectedField.validationRules.min" />
            </el-form-item>
            <el-form-item label="最大值">
              <el-input-number v-model="selectedField.validationRules.max" />
            </el-form-item>
          </template>

          <el-form-item label="正则表达式">
            <el-input v-model="selectedField.validationRules.pattern" placeholder="请输入正则表达式" />
          </el-form-item>
        </el-form>

        <div class="form-actions">
          <el-button @click="handleCancelConfig">取消</el-button>
          <el-button type="primary" @click="handleSaveConfig">保存配置</el-button>
        </div>
      </div>

      <div v-else class="empty-state">
        <el-empty description="请选择或添加字段" />
      </div>
    </div>

    <!-- 预览对话框 -->
    <el-dialog v-model="previewVisible" title="字段预览" width="800px">
      <DynamicFieldRenderer
        v-if="previewVisible"
        :fields="localFields"
        :model-value="previewData"
      />
      <template #footer>
        <el-button @click="previewVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Rank } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import DynamicFieldRenderer from './DynamicFieldRenderer.vue'
import type { FieldConfig } from '@/types/form'

interface Props {
  modelValue: FieldConfig[]
  readonly?: boolean
}

interface Emits {
  (e: 'update:modelValue', value: FieldConfig[]): void
  (e: 'preview', fields: FieldConfig[]): void
}

const props = withDefaults(defineProps<Props>(), {
  readonly: false
})

const emit = defineEmits<Emits>()

// 本地字段列表
const localFields = ref<FieldConfig[]>([...props.modelValue])

// 选中的字段ID
const selectedFieldId = ref<string | null>(null)

// 选中的字段
const selectedField = ref<FieldConfig | null>(null)

// 预览可见性
const previewVisible = ref(false)

// 预览数据
const previewData = ref<Record<string, any>>({})

/**
 * 字段类型标签映射
 */
const getFieldTypeLabel = (type: string): string => {
  const labels: Record<string, string> = {
    text: '单行文本',
    textarea: '多行文本',
    number: '数字',
    date: '日期',
    select: '下拉选择',
    multiselect: '多选下拉',
    boolean: '开关',
    tree: '树形选择',
    url: '链接',
    email: '邮箱',
    phone: '手机号'
  }
  return labels[type] || type
}

/**
 * 处理添加字段
 */
const handleAddField = () => {
  const newField: FieldConfig = {
    id: `field_${Date.now()}`,
    name: `field_${localFields.value.length + 1}`,
    label: `新字段${localFields.value.length + 1}`,
    fieldType: 'text',
    required: false,
    span: 24,
    validationRules: {},
    options: []
  }

  localFields.value.push(newField)
  handleSelectField(newField)
  emit('update:modelValue', localFields.value)
}

/**
 * 处理选择字段
 */
const handleSelectField = (field: FieldConfig) => {
  selectedFieldId.value = field.id
  selectedField.value = { ...field }
}

/**
 * 处理编辑字段
 */
const handleEditField = (field: FieldConfig) => {
  handleSelectField(field)
}

/**
 * 处理删除字段
 */
const handleDeleteField = async (field: FieldConfig) => {
  try {
    await ElMessageBox.confirm(`确定要删除字段"${field.label}"吗？`, '提示', {
      type: 'warning'
    })

    const index = localFields.value.findIndex((f) => f.id === field.id)
    if (index > -1) {
      localFields.value.splice(index, 1)
      if (selectedFieldId.value === field.id) {
        selectedFieldId.value = null
        selectedField.value = null
      }
      emit('update:modelValue', localFields.value)
      ElMessage.success('删除成功')
    }
  } catch {
    // 取消删除
  }
}

/**
 * 处理拖拽结束
 */
const handleDragEnd = () => {
  emit('update:modelValue', localFields.value)
}

/**
 * 添加选项
 */
const handleAddOption = () => {
  if (!selectedField.value) return
  if (!selectedField.value.options) {
    selectedField.value.options = []
  }
  selectedField.value.options.push({
    label: `选项${selectedField.value.options.length + 1}`,
    value: `option_${selectedField.value.options.length + 1}`
  })
}

/**
 * 删除选项
 */
const handleDeleteOption = (index: number) => {
  if (!selectedField.value || !selectedField.value.options) return
  selectedField.value.options.splice(index, 1)
}

/**
 * 保存配置
 */
const handleSaveConfig = () => {
  if (!selectedField.value) return

  const index = localFields.value.findIndex((f) => f.id === selectedField.value!.id)
  if (index > -1) {
    localFields.value[index] = { ...selectedField.value }
    emit('update:modelValue', localFields.value)
    ElMessage.success('保存成功')
  }
}

/**
 * 取消配置
 */
const handleCancelConfig = () => {
  if (selectedFieldId.value) {
    const field = localFields.value.find((f) => f.id === selectedFieldId.value)
    if (field) {
      selectedField.value = { ...field }
    }
  }
}

// 监听props变化
watch(
  () => props.modelValue,
  (value) => {
    localFields.value = [...value]
  },
  { deep: true }
)
</script>

<style scoped lang="scss">
.field-designer {
  display: flex;
  height: 100%;
  gap: 20px;

  .field-list-panel,
  .field-config-panel {
    flex: 1;
    background: #fff;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
  }

  .panel-header {
    padding: 16px;
    border-bottom: 1px solid var(--el-border-color);

    h3 {
      margin: 0 0 12px 0;
      font-size: 16px;
      font-weight: 600;
    }
  }

  .field-list {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    .field-item {
      padding: 12px;
      border: 1px solid var(--el-border-color);
      border-radius: 4px;
      margin-bottom: 8px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: var(--el-color-primary);
      }

      &.active {
        border-color: var(--el-color-primary);
        background: var(--el-color-primary-light-9);
      }

      .field-info {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 8px;

        .drag-handle {
          cursor: move;
        }

        .field-label {
          flex: 1;
          font-weight: 500;
        }

        .field-type-tag {
          font-size: 12px;
        }
      }

      .field-actions {
        display: flex;
        gap: 8px;
        justify-content: flex-end;
      }
    }
  }

  .field-config-form {
    flex: 1;
    padding: 16px;
    overflow-y: auto;

    .options-config {
      .option-item {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
        align-items: center;
      }
    }

    .form-actions {
      margin-top: 24px;
      text-align: right;
    }
  }

  .empty-state {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
</style>
