<script setup>
import { ref, computed, watch, nextTick, onBeforeUnmount, watchEffect } from 'vue';
import { getNodeSchemaFields } from '@/shared/api/nodes';

const props = defineProps({
  schema: {
    type: Object,
    required: true,
    validator: (value) => {
      return value && typeof value === 'object' && value.properties;
    }
  },
  modelValue: {
    type: Object,
    default: () => ({}),
    validator: (value) => {
      return value === null || typeof value === 'object';
    }
  },
  flowStore: {
    type: Object,
    required: true
  }
});

const emit = defineEmits(['update:modelValue', 'error']);

// 本地数据
const formData = ref({});
const isUpdatingFromProps = ref(false);
const initializationComplete = ref(false);

// 深度比较函数 - 性能优化版本
function deepEqual(obj1, obj2) {
  if (obj1 === obj2) return true;
  
  if (obj1 == null || obj2 == null) return false;
  
  if (typeof obj1 !== typeof obj2) return false;
  
  if (typeof obj1 !== 'object') return obj1 === obj2;
  
  const keys1 = Object.keys(obj1);
  const keys2 = Object.keys(obj2);
  
  if (keys1.length !== keys2.length) return false;
  
  for (let key of keys1) {
    if (!keys2.includes(key)) return false;
    if (!deepEqual(obj1[key], obj2[key])) return false;
  }
  
  return true;
}

// 安全的数据拷贝
function safeClone(obj) {
  if (obj === null || typeof obj !== 'object') return obj;
  
  try {
    return JSON.parse(JSON.stringify(obj));
  } catch (error) {
    console.warn('[SchemaFormRenderer] 数据克隆失败，使用浅拷贝:', error);
    return { ...obj };
  }
}

// 处理输入变化
function handleInputChange(fieldName, value) {
  // 使用Vue的响应式API确保变化被检测到
  const newFormData = {
    ...formData.value,
    [fieldName]: value
  };
  
  formData.value = newFormData;
}

// 对象字段操作
function addObjectProperty(fieldName) {
  const newKey = 'input_' + Date.now();
  const currentValue = formData.value[fieldName] || {};
  const newValue = {
    ...currentValue,
    [newKey]: { from: '', field: '' }
  };
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

// 获取当前流程中的所有节点
function getAvailableNodes() {
  try {
    return props.flowStore.nodes.map(node => ({
      id: node.id,
      label: node.data?.label || node.id,
      type: node.type
    }));
  } catch (error) {
    console.warn('[SchemaFormRenderer] 获取节点列表失败:', error);
    return [];
  }
}

function removeObjectProperty(fieldName, key) {
  const currentValue = formData.value[fieldName] || {};
  const newValue = { ...currentValue };
  delete newValue[key];
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

function updateObjectPropertyKey(fieldName, oldKey, newKey) {
  if (oldKey === newKey || !newKey) return;
  
  const currentValue = formData.value[fieldName] || {};
  const value = currentValue[oldKey];
  
  const newValue = { ...currentValue };
  newValue[newKey] = value;
  delete newValue[oldKey];
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

function updateObjectPropertyValue(fieldName, key, property, value) {
  const currentValue = formData.value[fieldName] || {};
  const itemValue = currentValue[key] || {};
  
  const newValue = {
    ...currentValue,
    [key]: {
      ...itemValue,
      [property]: value
    }
  };
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

// 获取数组字段标题
function getArrayFieldTitle(fieldId) {
  const field = allFields.value[fieldId];
  if (!field) return '配置项';
  
  // 根据字段标题动态判断
  if (field.title?.includes('过滤') || field.title?.includes('条件')) {
    return '过滤条件';
  }
  if (field.title?.includes('映射')) {
    return '映射配置';
  }
  return field.title || '配置项';
}

// 获取数组添加按钮文本
function getArrayAddButtonText(fieldId) {
  const field = allFields.value[fieldId];
  if (!field) return '添加项';
  
  // 根据字段标题动态判断
  if (field.title?.includes('过滤') || field.title?.includes('条件')) {
    return '添加条件';
  }
  if (field.title?.includes('映射')) {
    return '添加映射';
  }
  return '添加项';
}

// 数组字段操作
function addArrayItem(fieldName) {
  const currentValue = formData.value[fieldName] || [];
  const field = allFields.value[fieldName];
  
  // 根据字段类型创建默认项
  let newItem = {};
  if (field?.items?.properties) {
    // 使用schema定义的默认值
    Object.keys(field.items.properties).forEach(key => {
      const prop = field.items.properties[key];
      newItem[key] = prop.default !== undefined ? prop.default : '';
    });
  } else {
    // 如果没有schema定义，创建空对象
    newItem = {};
  }
  
  const newValue = [...currentValue, newItem];
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

function removeArrayItem(fieldName, index) {
  const currentValue = formData.value[fieldName] || [];
  const newValue = currentValue.filter((_, i) => i !== index);
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

function updateArrayItem(fieldName, index, property, value) {
  const currentValue = formData.value[fieldName] || [];
  const newValue = [...currentValue];
  
  if (newValue[index]) {
    newValue[index] = {
      ...newValue[index],
      [property]: value
    };
  }
  
  formData.value = {
    ...formData.value,
    [fieldName]: newValue
  };
}

// 获取字段的默认值
function getDefaultValue(property) {
  if (!property || typeof property !== 'object') {
    console.warn('[SchemaFormRenderer] 无效的属性定义:', property);
    return null;
  }
  
  if (property.default !== undefined) {
    return property.default;
  }
  
  switch (property.type) {
    case 'string':
      return '';
    case 'number':
    case 'integer':
      return property.minimum || 0;
    case 'boolean':
      return false;
    case 'array':
      return [];
    case 'object':
      return {};
    default:
      return null;
  }
}

// 验证字段值
function validateFieldValue(value, property) {
  if (!property) return true;
  
  try {
    switch (property.type) {
      case 'string':
        if (property.minLength && value.length < property.minLength) return false;
        if (property.maxLength && value.length > property.maxLength) return false;
        if (property.pattern && !new RegExp(property.pattern).test(value)) return false;
        break;
      case 'number':
      case 'integer':
        if (property.minimum !== undefined && value < property.minimum) return false;
        if (property.maximum !== undefined && value > property.maximum) return false;
        break;
    }
    return true;
  } catch (error) {
    console.warn('[SchemaFormRenderer] 字段验证错误:', error);
    return true;
  }
}

// 初始化表单数据
function initFormData() {
  if (!props.schema) {
    console.warn('[SchemaFormRenderer] Schema无效');
    return;
  }
  
  try {
    const initialData = safeClone(props.modelValue || {});
    
    // 处理基础字段
    if (props.schema.properties) {
      Object.entries(props.schema.properties).forEach(([fieldName, property]) => {
        // 只有当字段值真正为undefined时才设置默认值
        // 区分undefined和其他falsy值（如空字符串、false等）
        if (initialData[fieldName] === undefined) {
          initialData[fieldName] = getDefaultValue(property);
        }
      });
    }
    
    // 处理条件字段的默认值（来自 allOf）
    Object.entries(conditionalFields.value).forEach(([fieldName, property]) => {
      if (initialData[fieldName] === undefined) {
        initialData[fieldName] = getDefaultValue(property);
      }
    });
    
    formData.value = initialData;
    initializationComplete.value = true;
    
  } catch (error) {
    console.error('[SchemaFormRenderer] 初始化失败:', error);
    emit('error', { type: 'initialization', message: error.message });
  }
}

// 监听props变化
const stopWatchingProps = watch(() => props.modelValue, (newVal, oldVal) => {
  if (!initializationComplete.value) {
    return;
  }
  
  // 深度比较，如果数据实际上没有变化则不更新
  if (deepEqual(newVal, oldVal)) {
    return;
  }
  
  try {
    // 防止循环更新
    isUpdatingFromProps.value = true;
    formData.value = safeClone(newVal || {});
    
    // 确保所有必需字段都有默认值
    if (props.schema?.properties) {
      Object.entries(props.schema.properties).forEach(([fieldName, property]) => {
        if (formData.value[fieldName] === undefined) {
          formData.value[fieldName] = getDefaultValue(property);
        }
      });
    }
    
    // 确保条件字段也有默认值
    Object.entries(conditionalFields.value).forEach(([fieldName, property]) => {
      if (formData.value[fieldName] === undefined) {
        formData.value[fieldName] = getDefaultValue(property);
      }
    });
    
    // 下一个tick后重置标志
    nextTick(() => {
      isUpdatingFromProps.value = false;
    });
  } catch (error) {
    console.error('[SchemaFormRenderer] Props更新失败:', error);
    emit('error', { type: 'props-update', message: error.message });
  }
}, { deep: true });

// 监听本地数据变化并发出事件
const stopWatchingFormData = watch(formData, (newVal, oldVal) => {
  if (!initializationComplete.value) {
    return;
  }
  
  // 如果正在从props更新，则不发出事件
  if (isUpdatingFromProps.value) {
    return;
  }
  
  // 避免不必要的事件发出
  if (deepEqual(newVal, oldVal)) {
    return;
  }
  
  try {
    emit('update:modelValue', safeClone(newVal));
  } catch (error) {
    console.error('[SchemaFormRenderer] 数据更新失败:', error);
    emit('error', { type: 'data-update', message: error.message });
  }
}, { deep: true });

// 解析 allOf 条件字段
const conditionalFields = computed(() => {
  if (!props.schema?.allOf) return {};
  
  const conditionalFieldsMap = {};
  
  try {
    props.schema.allOf.forEach(condition => {
      if (condition.if && condition.then) {
        // 提取条件
        const ifConditions = extractConditions(condition.if);
        
        // 提取条件为真时的字段
        if (condition.then.properties) {
          Object.entries(condition.then.properties).forEach(([fieldName, fieldDef]) => {
            conditionalFieldsMap[fieldName] = {
              ...fieldDef,
              _condition: ifConditions
            };
          });
        }
      }
    });
  } catch (error) {
    console.warn('[SchemaFormRenderer] allOf 解析错误:', error);
  }
  
  return conditionalFieldsMap;
});

// 提取条件对象
function extractConditions(ifClause) {
  const conditions = {};
  
  if (ifClause.properties) {
    Object.entries(ifClause.properties).forEach(([key, value]) => {
      if (value.const !== undefined) {
        conditions[key] = value.const;
      } else if (value.enum && value.enum.length === 1) {
        conditions[key] = value.enum[0];
      } else if (Array.isArray(value.enum)) {
        conditions[key] = value.enum; // 支持多值匹配
      }
    });
  }
  
  return conditions;
}

// 检查条件是否满足
function checkCondition(conditions, formData) {
  if (!conditions || Object.keys(conditions).length === 0) return true;
  
  return Object.entries(conditions).every(([key, expectedValue]) => {
    const actualValue = formData[key];
    
    if (Array.isArray(expectedValue)) {
      // 支持多值匹配 (enum)
      return expectedValue.includes(actualValue);
    } else {
      // 精确匹配
      return actualValue === expectedValue;
    }
  });
}

// 检查传统条件属性（支持反向条件）
function checkTraditionalCondition(condition, formData) {
  if (!condition || Object.keys(condition).length === 0) return true;
  
  return Object.entries(condition).every(([key, expectedValue]) => {
    const actualValue = formData[key];
    
    // 支持多种反向条件语法
    if (typeof expectedValue === 'object' && expectedValue !== null && !Array.isArray(expectedValue)) {
      // 对象形式的条件，支持多种操作符
      
      // MongoDB 风格 ($ne, $in, $nin)
      if (expectedValue.$ne !== undefined) {
        if (Array.isArray(expectedValue.$ne)) {
          return !expectedValue.$ne.includes(actualValue);
        } else {
          return actualValue !== expectedValue.$ne;
        }
      }
      
      if (expectedValue.$in !== undefined) {
        return Array.isArray(expectedValue.$in) && expectedValue.$in.includes(actualValue);
      }
      
      if (expectedValue.$nin !== undefined) {
        return Array.isArray(expectedValue.$nin) && !expectedValue.$nin.includes(actualValue);
      }
      
      // 简化 not 语法
      if (expectedValue.not !== undefined) {
        if (Array.isArray(expectedValue.not)) {
          return !expectedValue.not.includes(actualValue);
        } else {
          return actualValue !== expectedValue.not;
        }
      }
      
      // 操作符风格 (!=, in, !in)
      if (expectedValue['!='] !== undefined) {
        if (Array.isArray(expectedValue['!='])) {
          return !expectedValue['!='].includes(actualValue);
        } else {
          return actualValue !== expectedValue['!='];
        }
      }
      
      if (expectedValue.in !== undefined) {
        return Array.isArray(expectedValue.in) && expectedValue.in.includes(actualValue);
      }
      
      if (expectedValue['!in'] !== undefined) {
        return Array.isArray(expectedValue['!in']) && !expectedValue['!in'].includes(actualValue);
      }
      
      // 默认处理
      return true;
    }
    
    // 传统的精确匹配或数组匹配
    if (Array.isArray(expectedValue)) {
      return expectedValue.includes(actualValue);
    } else {
      return actualValue === expectedValue;
    }
  });
}

// 激活标签页
function activateTab(tabId) {
  if (props.schema?._layout) {
    props.schema._layout.activeTab = tabId;
  }
}

// 合并所有字段（基础字段 + 条件字段）
const allFields = computed(() => {
  const baseFields = props.schema?.properties || {};
  const conditionalFieldsMap = conditionalFields.value;
  
  // 合并字段，条件字段优先级更高
  return { ...baseFields, ...conditionalFieldsMap };
});

// 字段是否应该显示
const isFieldVisible = computed(() => (fieldName, property) => {
  try {
    // 1. 检查传统的 condition 属性（向后兼容）
    if (property.condition) {
      const traditionalConditionMet = checkTraditionalCondition(property.condition, formData.value);
      if (!traditionalConditionMet) return false;
    }
    
    // 2. 检查 allOf 中的条件（JSON Schema 标准）
    if (property._condition) {
      const allOfConditionMet = checkCondition(property._condition, formData.value);
      if (!allOfConditionMet) return false;
    }
    
    return true;
  } catch (error) {
    return true;
  }
});

// 计算每个section是否有可见字段（缓存结果，避免重复计算）
const sectionVisibility = computed(() => {
  const visibility = {};
  if (props.schema?._layout?.tabs) {
    props.schema._layout.tabs.forEach(tab => {
      tab.sections?.forEach(section => {
        visibility[section.id] = section.columns?.some(col => 
          col.fields?.some(fieldId => isFieldVisible.value(fieldId, allFields.value[fieldId]))
        ) || false;
      });
    });
  }
  return visibility;
});

// 组件初始化
watchEffect(() => {
  if (!initializationComplete.value) {
    initFormData();
  }
});

// 清理资源
onBeforeUnmount(() => {
  stopWatchingProps?.();
  stopWatchingFormData?.();
});

// 获取指定节点的可用字段
async function getNodeFields(nodeId) {
  try {
    const node = props.flowStore.nodes.find(n => n.id === nodeId);
    if (!node) return [];
    
    const nodeType = node.type;
    
    // 使用统一的API函数
    return await getNodeSchemaFields(nodeType);
  } catch (error) {
    console.warn('[SchemaFormRenderer] 获取节点字段失败:', error);
    return [];
  }
}
</script>

<template>
  <div class="schema-form-renderer">
    <div v-if="!schema?.properties" class="error-state">
      <div class="alert alert-warning">
        <i class="fa fa-exclamation-triangle"></i>
        Schema配置无效或缺少字段定义
      </div>
    </div>
    
    <div v-else>
      <!-- 支持带布局的Schema (tabs, sections, columns) -->
      <div v-if="schema._layout && schema._layout.tabs" class="schema-with-layout">
        <!-- Tabs 导航 -->
        <div class="schema-tabs">
          <div class="tab-header">
            <div class="tabs">
              <div
                v-for="tab in schema._layout.tabs"
                :key="tab.id"
                :class="['tab', schema._layout.activeTab === tab.id ? 'active' : '']"
                @click="activateTab(tab.id)"
              >
                {{ tab.label }}
              </div>
            </div>
          </div>
        </div>
        
        <!-- Tab 内容 -->
        <div 
          v-for="tab in schema._layout.tabs"
          :key="tab.id"
          class="tab-content"
          :class="{ 'active': schema._layout.activeTab === tab.id }"
          :style="{ display: schema._layout.activeTab === tab.id ? 'block' : 'none' }"
        >
          <!-- Sections (分组) -->
          <div 
            v-for="section in tab.sections"
            :key="section.id"
            v-show="sectionVisibility[section.id]"
            class="schema-section"
          >
            <div class="section-header">
              <h6 class="section-title">{{ section.label }}</h6>
            </div>
            
            <div class="section-content">
              <!-- Columns (分列) -->
              <div class="section-columns">
                <div 
                  v-for="column in section.columns"
                  :key="column.id"
                  class="section-column"
                  :style="{ flex: column.fields.length > 0 ? '1' : 'auto' }"
                >
                  <div v-if="column.label" class="column-header">
                    <span class="column-label">{{ column.label }}</span>
                  </div>
                  
                  <div class="column-fields">
                    <!-- 字段渲染 -->
                    <div 
                      v-for="fieldId in column.fields"
                      :key="fieldId"
                      v-show="isFieldVisible(fieldId, allFields[fieldId])"
                      class="form-group"
                    >
                      <label :for="`field-${fieldId}`">
                        {{ allFields[fieldId]?.title || fieldId }}
                        <span v-if="allFields[fieldId]?.required || schema.required?.includes(fieldId)" class="required">*</span>
                      </label>
                      
                      <!-- 字符串枚举类型 -->
                      <select 
                        v-if="allFields[fieldId]?.type === 'string' && allFields[fieldId]?.enum" 
                        :id="'field-' + fieldId"
                        :value="formData[fieldId]"
                        :class="{ 'is-invalid': !validateFieldValue(formData[fieldId], allFields[fieldId]) }"
                        @change="handleInputChange(fieldId, $event.target.value)"
                      >
                        <option value="">请选择...</option>
                        <option 
                          v-for="(option, index) in allFields[fieldId].enum" 
                          :key="option" 
                          :value="option"
                        >
                          {{ allFields[fieldId].enumNames?.[index] || option }}
                        </option>
                      </select>
                      
                        <!-- 信息展示字段 -->
                        <div
                          v-else-if="allFields[fieldId]?.type === 'string' && allFields[fieldId]?.format === 'info'"
                          class="info-display-field"
                        >
                          <div class="info-box">
                            <i class="fa fa-info-circle"></i>
                            <span>{{ formData[fieldId] || allFields[fieldId]?.default || '' }}</span>
                          </div>
                        </div>
                        
                        <!-- 普通字符串输入 -->
                        <input
                          v-else-if="allFields[fieldId]?.type === 'string' && allFields[fieldId]?.format !== 'textarea'"
                          :id="'field-' + fieldId"
                          :value="formData[fieldId]"
                          type="text"
                          :placeholder="allFields[fieldId]?.placeholder || ''"
                          :maxlength="allFields[fieldId]?.maxLength"
                          :class="{ 'is-invalid': !validateFieldValue(formData[fieldId], allFields[fieldId]) }"
                          @input="handleInputChange(fieldId, $event.target.value)"
                        />
                      
                      <!-- 文本域 -->
                      <textarea
                        v-else-if="allFields[fieldId]?.type === 'string' && allFields[fieldId]?.format === 'textarea'"
                        :id="'field-' + fieldId"
                        :value="formData[fieldId]"
                        :rows="allFields[fieldId]?.rows || 3"
                        :placeholder="allFields[fieldId]?.placeholder || ''"
                        :maxlength="allFields[fieldId]?.maxLength"
                        :class="{ 'is-invalid': !validateFieldValue(formData[fieldId], allFields[fieldId]) }"
                        @input="handleInputChange(fieldId, $event.target.value)"
                      ></textarea>
                      
                      <!-- 数字类型 -->
                      <input
                        v-else-if="allFields[fieldId]?.type === 'number' || allFields[fieldId]?.type === 'integer'"
                        :id="'field-' + fieldId"
                        :value="formData[fieldId]"
                        type="number"
                        :min="allFields[fieldId]?.minimum"
                        :max="allFields[fieldId]?.maximum"
                        :step="allFields[fieldId]?.type === 'integer' ? 1 : (allFields[fieldId]?.step || 0.1)"
                        :class="{ 'is-invalid': !validateFieldValue(formData[fieldId], allFields[fieldId]) }"
                        @input="handleInputChange(fieldId, parseFloat($event.target.value) || 0)"
                      />
                      
                      <!-- 布尔类型 -->
                      <div v-else-if="allFields[fieldId]?.type === 'boolean'" class="checkbox-wrapper">
                        <input
                          :id="'field-' + fieldId"
                          :checked="formData[fieldId]"
                          type="checkbox"
                          class="checkbox-input"
                          @change="handleInputChange(fieldId, $event.target.checked)"
                        />
                        <label :for="'field-' + fieldId" class="checkbox-label">
                          {{ allFields[fieldId]?.checkboxLabel || '启用' }}
                        </label>
                      </div>
                      
                      <!-- 对象类型 -->
                      <div v-else-if="allFields[fieldId]?.type === 'object'" class="object-field-container">
                        <div class="object-field-header">
                          <span class="object-field-title">动态属性配置</span>
                          <button 
                            type="button" 
                            class="btn btn-sm btn-outline-primary"
                            @click="addObjectProperty(fieldId)"
                          >
                            <i class="fa fa-plus"></i> 添加属性
                          </button>
                        </div>
                        
                        <div class="object-field-content">
                          <div 
                            v-for="(value, key) in (formData[fieldId] || {})" 
                            :key="key"
                            class="object-property"
                          >
                            <!-- 隐藏动态生成的ID字段，只显示节点ID和字段名 -->
                            <div class="property-value">
                              <div class="field-group">
                                <label class="field-label-sm">节点ID</label>
                                <select
                                  class="form-control form-control-sm"
                                  :value="value.from || ''"
                                  @change="updateObjectPropertyValue(fieldId, key, 'from', $event.target.value)"
                                >
                                  <option value="">请选择节点</option>
                                  <option 
                                    v-for="node in getAvailableNodes()" 
                                    :key="node.id" 
                                    :value="node.id"
                                  >
                                    {{ node.label }}
                                  </option>
                                </select>
                              </div>
                              <div class="field-group">
                                <label class="field-label-sm">字段名</label>
                                <div class="field-input-group">
                                  <input
                                    type="text"
                                    class="form-control form-control-sm"
                                    :value="value.field || ''"
                                    @input="updateObjectPropertyValue(fieldId, key, 'field', $event.target.value)"
                                    placeholder="输入或选择字段名"
                                  />
                                  <select
                                    class="form-control form-control-sm field-select"
                                    @change="updateObjectPropertyValue(fieldId, key, 'field', $event.target.value)"
                                  >
                                    <option value="">选择字段</option>
                                    <option 
                                      v-for="field in getNodeFields(value.from)" 
                                      :key="field.name" 
                                      :value="field.name"
                                      :title="field.label"
                                    >
                                      {{ field.label }}
                                    </option>
                                  </select>
                                </div>
                              </div>
                            </div>
                            <div class="property-actions">
                              <button 
                                type="button" 
                                class="btn btn-sm btn-outline-danger"
                                @click="removeObjectProperty(fieldId, key)"
                              >
                                <i class="fa fa-trash"></i>
                              </button>
                            </div>
                          </div>
                          
                          <div v-if="!formData[fieldId] || Object.keys(formData[fieldId]).length === 0" class="empty-state">
                            <i class="fa fa-info-circle"></i>
                            <span>暂无配置项，点击"添加属性"开始配置</span>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 数组类型 -->
                      <div v-else-if="allFields[fieldId]?.type === 'array'" class="array-field-container">
                        <div class="array-field-header">
                          <span class="array-field-title">{{ getArrayFieldTitle(fieldId) }}</span>
                          <button 
                            type="button" 
                            class="btn btn-sm btn-outline-primary"
                            @click="addArrayItem(fieldId)"
                          >
                            <i class="fa fa-plus"></i> {{ getArrayAddButtonText(fieldId) }}
                          </button>
                        </div>
                        
                        <div class="array-field-content">
                          <div 
                            v-for="(item, index) in (formData[fieldId] || [])" 
                            :key="index"
                            class="array-item"
                          >
                            <div class="item-fields">
                              <!-- 动态渲染数组项字段 -->
                              <template v-for="(propName, propKey) in allFields[fieldId]?.items?.properties" :key="propKey">
                                <div class="field-group">
                                  <label class="field-label-sm">{{ propName.title || propKey }}</label>
                                  
                                  <!-- 字符串枚举类型 -->
                                  <select 
                                    v-if="propName.type === 'string' && propName.enum"
                                    class="form-control form-control-sm"
                                    :value="item[propKey] || propName.default || ''"
                                    @change="updateArrayItem(fieldId, index, propKey, $event.target.value)"
                                  >
                                    <option value="">请选择...</option>
                                    <option 
                                      v-for="(option, optIndex) in propName.enum" 
                                      :key="option" 
                                      :value="option"
                                    >
                                      {{ propName.enumNames?.[optIndex] || option }}
                                    </option>
                                  </select>
                                  
                                  <!-- 普通字符串输入 -->
                                  <input
                                    v-else
                                    type="text"
                                    class="form-control form-control-sm"
                                    :value="item[propKey] || ''"
                                    @input="updateArrayItem(fieldId, index, propKey, $event.target.value)"
                                    :placeholder="propName.description || ''"
                                  />
                                </div>
                              </template>
                            </div>
                            <div class="item-actions">
                              <button 
                                type="button" 
                                class="btn btn-sm btn-outline-danger"
                                @click="removeArrayItem(fieldId, index)"
                              >
                                <i class="fa fa-trash"></i>
                              </button>
                            </div>
                          </div>
                          
                          <div v-if="!formData[fieldId] || formData[fieldId].length === 0" class="empty-state">
                            <i class="fa fa-info-circle"></i>
                            <span>暂无{{ getArrayFieldTitle(fieldId) }}，点击"{{ getArrayAddButtonText(fieldId) }}"开始配置</span>
                          </div>
                        </div>
                      </div>
                      
                      <!-- 不支持的类型 -->
                      <div v-else class="unsupported-field">
                        <span class="text-muted">不支持的字段类型: {{ allFields[fieldId]?.type }}</span>
                      </div>
                      
                      <!-- 验证错误提示 -->
                      <div 
                        v-if="!validateFieldValue(formData[fieldId], allFields[fieldId])" 
                        class="field-error"
                      >
                        字段值不符合要求
                      </div>
                      
                      <!-- 字段描述 -->
                      <div v-if="allFields[fieldId]?.description" class="field-description">
                        {{ allFields[fieldId].description }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 传统简单Schema (无布局) -->
      <div v-else class="schema-simple">
        <div 
          v-for="(property, fieldName) in allFields" 
          :key="fieldName"
          v-show="isFieldVisible(fieldName, property)"
          class="form-group"
        >
          <label :for="`fieldName}`">
            {{ property.title || fieldName }}
            <span v-if="property.required || schema.required?.includes(fieldName)" class="required">*</span>
          </label>
          
          <!-- 字符串枚举类型 -->
          <select 
            v-if="property.type === 'string' && property.enum" 
            :id="'field-' + fieldName"
            :value="formData[fieldName]"
            :class="{ 'is-invalid': !validateFieldValue(formData[fieldName], property) }"
            @change="handleInputChange(fieldName, $event.target.value)"
          >
            <option value="">请选择...</option>
            <option 
              v-for="(option, index) in property.enum" 
              :key="option" 
              :value="option"
            >
              {{ property.enumNames?.[index] || option }}
            </option>
          </select>
          
          <!-- 信息展示字段 -->
          <div
            v-else-if="property.type === 'string' && property.format === 'info'"
            class="info-display-field"
          >
            <div class="info-box">
              <i class="fa fa-info-circle"></i>
              <span>{{ formData[fieldName] || property.default || '' }}</span>
            </div>
          </div>
          
          <!-- 普通字符串输入 -->
          <input
            v-else-if="property.type === 'string' && property.format !== 'textarea'"
            :id="'field-' + fieldName"
            :value="formData[fieldName]"
            type="text"
            :placeholder="property.placeholder || ''"
            :maxlength="property.maxLength"
            :class="{ 'is-invalid': !validateFieldValue(formData[fieldName], property) }"
            @input="handleInputChange(fieldName, $event.target.value)"
          />
          
          <!-- 文本域 -->
          <textarea
            v-else-if="property.type === 'string' && property.format === 'textarea'"
            :id="'field-' + fieldName"
            :value="formData[fieldName]"
            :rows="property.rows || 3"
            :placeholder="property.placeholder || ''"
            :maxlength="property.maxLength"
            :class="{ 'is-invalid': !validateFieldValue(formData[fieldName], property) }"
            @input="handleInputChange(fieldName, $event.target.value)"
          ></textarea>
          
          <!-- 数字类型 -->
          <input
            v-else-if="property.type === 'number' || property.type === 'integer'"
            :id="'field-' + fieldName"
            :value="formData[fieldName]"
            type="number"
            :min="property.minimum"
            :max="property.maximum"
            :step="property.type === 'integer' ? 1 : (property.step || 0.1)"
            :class="{ 'is-invalid': !validateFieldValue(formData[fieldName], property) }"
            @input="handleInputChange(fieldName, parseFloat($event.target.value) || 0)"
          />
          
          <!-- 布尔类型 -->
          <div v-else-if="property.type === 'boolean'" class="checkbox-wrapper">
            <input
              :id="'field-' + fieldName"
              :checked="formData[fieldName]"
              type="checkbox"
              class="checkbox-input"
              @change="handleInputChange(fieldName, $event.target.checked)"
            />
            <label :for="'field-' + fieldName" class="checkbox-label">
              {{ property.checkboxLabel || '启用' }}
            </label>
          </div>
          
          <!-- 不支持的类型 -->
          <div v-else class="unsupported-field">
            <span class="text-muted">不支持的字段类型: {{ property.type }}</span>
          </div>
          
          <!-- 验证错误提示 -->
          <div 
            v-if="!validateFieldValue(formData[fieldName], property)" 
            class="field-error"
          >
            字段值不符合要求
          </div>
          
          <!-- 字段描述 -->
          <div v-if="property.description" class="field-description">
            {{ property.description }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>



<style scoped>

.form-group {
  margin-bottom: 0;
}

.form-group label {
  display: block;
  margin-bottom: 4px;
  font-weight: 500;
  color: #374151;
}

.required {
  color: #ef4444;
  margin-left: 2px;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 3px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.2s, box-shadow 0.2s;
}

.form-group select {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 12px center;
  background-repeat: no-repeat;
  background-size: 16px 12px;
  padding-right: 40px;
  appearance: none;
}

.form-group input:focus,
.form-group select:focus,
.form-group textarea:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.is-invalid {
  border-color: #ef4444 !important;
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1) !important;
}

.checkbox-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.checkbox-input {
  width: auto !important;
  margin: 0;
}

.checkbox-label {
  margin: 0;
  font-weight: normal;
  cursor: pointer;
}

.field-description {
  margin-top: 4px;
  font-size: 0.875rem;
  color: #6b7280;
  line-height: 1.4;
}

.field-error {
  margin-top: 4px;
  font-size: 0.875rem;
  color: #ef4444;
}

.error-state {
  padding: 16px;
}

.alert {
  padding: 12px 16px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.alert-warning {
  background-color: #fef3c7;
  border: 1px solid #f59e0b;
  color: #92400e;
}

.unsupported-field {
  padding: 8px;
  background-color: #f3f4f6;
  border-radius: 4px;
  color: #6b7280;
  font-style: italic;
}

.text-muted {
  color: #6b7280;
}

/* 新增的布局样式 */
.schema-with-layout {
  width: 100%;
}

.schema-tabs {
  margin-bottom: 20px;
  border-bottom: 1px solid #e5e7eb;
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

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

.tabs {
  display: flex;
  gap: 0;
}

.tab {
  padding: 12px 20px;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  color: #6b7280;
  font-weight: 500;
  transition: all 0.2s;
  user-select: none;
}

.tab:hover {
  color: #374151;
  background-color: #f9fafb;
}

.tab.active {
  color: #3b82f6;
  border-bottom-color: #3b82f6;
  background-color: #eff6ff;
}

.tab-content {
  display: none;
}

.tab-content.active {
  display: block;
}

.schema-section {
  margin-bottom: 24px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.section-header {
  background-color: #f9fafb;
  padding: 12px 16px;
  border-bottom: 1px solid #e5e7eb;
}

.section-title {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.section-content {
  padding: 16px;
}

.section-columns {
  display: flex;
  gap: 16px;
}

.section-column {
  flex: 1;
  min-width: 0;
}

.column-header {
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #f3f4f6;
}

.column-label {
  font-size: 13px;
  font-weight: 500;
  color: #6b7280;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.column-fields {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .section-columns {
    flex-direction: column;
    gap: 20px;
  }
  
  .tabs {
    overflow-x: auto;
    white-space: nowrap;
  }
  
  .tab {
    padding: 10px 16px;
    font-size: 14px;
  }
}

/* 复杂字段样式 */
.object-field-container,
.array-field-container {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: #fff;
  overflow: hidden;
}

.object-field-header,
.array-field-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-bottom: 1px solid #e5e7eb;
}

.object-field-title,
.array-field-title {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
}

.object-field-content,
.array-field-content {
  padding: 16px;
}

.object-property,
.array-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #f9fafb;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  margin-bottom: 12px;
  transition: all 0.2s ease;
}

.object-property:hover,
.array-item:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.property-key,
.item-fields {
  flex: 1;
  display: flex;
  gap: 8px;
}

.property-value {
  flex: 2;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.property-actions,
.item-actions {
  flex-shrink: 0;
}

.field-group {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 6px;
  min-width: 150px;
}

.field-input-group {
  display: flex;
  gap: 8px;
  align-items: center;
}

.field-input-group input {
  flex: 1;
  min-width: 0;
}

.field-input-group .field-select {
  width: 120px;
  flex-shrink: 0;
}

.field-label-sm {
  font-size: 12px;
  font-weight: 600;
  color: #374151;
  margin: 0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 24px;
  color: #9ca3af;
  font-size: 14px;
  background: #f9fafb;
  border: 2px dashed #d1d5db;
  border-radius: 6px;
}

.empty-state i {
  font-size: 16px;
}

.btn {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 6px 12px;
  border: 1px solid;
  border-radius: 6px;
  font-size: 12px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  text-decoration: none;
  background: none;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 11px;
}

.btn-outline-primary {
  color: #3b82f6;
  border-color: #3b82f6;
  background: transparent;
}

.btn-outline-primary:hover {
  color: #fff;
  background: #3b82f6;
}

.btn-outline-danger {
  color: #ef4444;
  border-color: #ef4444;
  background: transparent;
}

.btn-outline-danger:hover {
  color: #fff;
  background: #ef4444;
}

.form-control-sm {
  padding: 8px 12px;
  font-size: 13px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  background: #fff;
  transition: all 0.2s ease;
  width: 100%;
  box-sizing: border-box;
}

.form-control-sm:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.form-control-sm:hover {
  border-color: #9ca3af;
}

/* 下拉选择框特殊样式 */
select.form-control-sm {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
  background-position: right 8px center;
  background-repeat: no-repeat;
  background-size: 16px;
  padding-right: 32px;
  appearance: none;
  cursor: pointer;
}

select.form-control-sm:focus {
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%233b82f6' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='m6 8 4 4 4-4'/%3e%3c/svg%3e");
}

/* 信息展示字段样式 */
.info-display-field {
  margin-bottom: 16px;
}

.info-box {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 6px;
  color: #0369a1;
  font-size: 13px;
  line-height: 1.5;
}

.info-box i {
  color: #0284c7;
  font-size: 14px;
  margin-top: 1px;
  flex-shrink: 0;
}

.info-box span {
  flex: 1;
}
</style>