<template>
  <div class="dynamic-form-example">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>动态表单示例</span>
          <div class="actions">
            <el-button @click="handlePreview">预览</el-button>
            <el-button type="primary" @click="handleSubmit">提交</el-button>
          </div>
        </div>
      </template>

      <DynamicFieldRenderer
        ref="formRendererRef"
        v-model="formData"
        :fields="fields"
        :dependencies="dependencies"
        @field-change="handleFieldChange"
        @validation-change="handleValidationChange"
      />
    </el-card>

    <!-- 表单数据显示 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <span>表单数据</span>
      </template>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </el-card>

    <!-- 字段配置显示 -->
    <el-card style="margin-top: 20px">
      <template #header>
        <span>字段配置</span>
      </template>
      <pre>{{ JSON.stringify(fields, null, 2) }}</pre>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import DynamicFieldRenderer from '@/components/form/DynamicFieldRenderer.vue'
import type { FieldConfig, FieldDependency, FormData } from '@/types/form'

// 表单引用
const formRendererRef = ref()

// 表单数据
const formData = ref<FormData>({
  assetName: '',
  deviceType: '',
  cpu: '',
  memory: '',
  purchaseDate: '',
  hasWarranty: false,
  tags: []
})

// 字段配置
const fields = ref<FieldConfig[]>([
  {
    id: '1',
    name: 'assetName',
    label: '资产名称',
    fieldType: 'text',
    required: true,
    placeholder: '请输入资产名称',
    span: 12,
    validationRules: {
      min: 2,
      max: 50
    }
  },
  {
    id: '2',
    name: 'deviceType',
    label: '设备类型',
    fieldType: 'select',
    required: true,
    placeholder: '请选择设备类型',
    span: 12,
    options: [
      { label: '台式机', value: 'desktop' },
      { label: '笔记本', value: 'laptop' },
      { label: '服务器', value: 'server' },
      { label: '打印机', value: 'printer' }
    ]
  },
  {
    id: '3',
    name: 'cpu',
    label: 'CPU型号',
    fieldType: 'text',
    required: true,
    placeholder: '例如: Intel i5-10400',
    span: 12,
    // 只有选择设备类型后才显示
    visible: (data) => !!data.deviceType
  },
  {
    id: '4',
    name: 'memory',
    label: '内存容量',
    fieldType: 'select',
    required: true,
    placeholder: '请选择内存容量',
    span: 12,
    options: [
      { label: '8GB', value: '8' },
      { label: '16GB', value: '16' },
      { label: '32GB', value: '32' },
      { label: '64GB', value: '64' }
    ],
    visible: (data) => !!data.deviceType
  },
  {
    id: '5',
    name: 'purchaseDate',
    label: '采购日期',
    fieldType: 'date',
    required: true,
    placeholder: '请选择采购日期',
    span: 12
  },
  {
    id: '6',
    name: 'hasWarranty',
    label: '是否有保修',
    fieldType: 'boolean',
    defaultValue: false,
    span: 12
  },
  {
    id: '7',
    name: 'description',
    label: '资产描述',
    fieldType: 'textarea',
    placeholder: '请输入资产描述',
    span: 24,
    rows: 4,
    validationRules: {
      max: 500
    }
  },
  {
    id: '8',
    name: 'tags',
    label: '标签',
    fieldType: 'multiselect',
    placeholder: '请选择标签',
    span: 12,
    options: [
      { label: '重要资产', value: 'important' },
      { label: '易损资产', value: 'fragile' },
      { label: '贵重资产', value: 'valuable' }
    ]
  },
  {
    id: '9',
    name: 'quantity',
    label: '数量',
    fieldType: 'number',
    defaultValue: 1,
    span: 12,
    validationRules: {
      min: 1,
      max: 100
    }
  }
])

// 字段联动配置
const dependencies = ref<FieldDependency[]>([
  // 示例：当设备类型变化时，清空CPU和内存的值
  {
    sourceField: 'deviceType',
    targetField: 'cpu',
    type: 'setValue',
    condition: (sourceValue) => true, // 总是触发
    action: () => undefined // 清空值
  }
])

/**
 * 处理字段变化
 */
const handleFieldChange = (event: any) => {
  console.log('字段变化:', event)
}

/**
 * 处理验证变化
 */
const handleValidationChange = (state: any) => {
  console.log('验证状态:', state)
}

/**
 * 处理预览
 */
const handlePreview = () => {
  console.log('表单数据:', formData.value)
}

/**
 * 处理提交
 */
const handleSubmit = async () => {
  try {
    const valid = await formRendererRef.value?.validateForm()
    if (valid) {
      console.log('提交表单数据:', formData.value)
      ElMessage.success('提交成功')
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}
</script>

<style scoped lang="scss">
.dynamic-form-example {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .actions {
      display: flex;
      gap: 10px;
    }
  }

  pre {
    background: #f5f5f5;
    padding: 16px;
    border-radius: 4px;
    overflow-x: auto;
  }
}
</style>
