<template>
	<div class="schema-sections">
		<draggable
			v-model="tab.sections"
			:group="{ name: 'sections', pull: true, put: true }"
			:animation="200"
			item-key="id"
			handle=".section-header"
			@change="onSectionsReorder"
		>
			<template #item="{ element: section }">
				<div
					class="schema-section"
					:data-section-id="section.id"
					@drop="onSectionDrop($event, section)"
					@dragover="onSectionDragOver($event)"
					@dragleave="onSectionDragLeave($event)"
				>
					<div class="section-header">
						<h6 class="section-title">
							<EditableInput
								:text="section.label || ''"
								:placeholder="t('Section Name')"
								@update:modelValue="store.updateSectionLabel(tab.id, section.id, $event)"
							/>
						</h6>
						<button
							v-if="tab?.sections.length > 1"
							class="remove-section-btn"
							@click="removeSection(section)"
							:title="t('Delete Section')"
						>
							×
						</button>
					</div>
					<div class="section-content">
						<draggable
							v-model="section.columns"
							:group="{ name: 'columns', pull: true, put: true }"
							:animation="200"
							item-key="id"
							handle=".column-header"
							@change="onColumnsReorder(section, $event)"
							tag="div"
							class="section-columns"
						>
							<template #item="{ element: column }">
								<div
									class="section-column"
									:data-column-id="column.id"
									@drop="onColumnDrop($event, column)"
									@dragover="onColumnDragOver($event)"
									@dragleave="onColumnDragLeave($event)"
									@dragstart="onColumnDragStart($event, column)"
								>
									<div class="column-header">
										<EditableInput
											:text="column.label || ''"
											:placeholder="t('Column Name')"
											@update:modelValue="store.updateColumnLabel(tab.id, section.id, column.id, $event)"
										/>
										<button
											v-if="section.columns.length > 1"
											class="remove-column-btn"
											@click="removeColumn(section, column)"
											:title="t('Delete Column')"
										>
											×
										</button>
									</div>
									<div class="column-fields">
										<draggable
											v-model="column.fields"
											:group="{ name: 'fields', pull: true, put: true }"
											:animation="200"
											item-key="id"
											class="fields-container"
											@change="onFieldChange"
											@start="onFieldDragStart"
										>
											<template #item="{ element: fieldId }">
												<div
													class="field-item"
													:class="{ 'selected': store.selectedField === fieldId }"
													@click="store.setSelectedField(fieldId)"
												>
													<!-- 字段内容 -->
													<div class="field-content">
														<div class="field-header">
															<span class="field-title">{{ getFieldById(fieldId)?.title || fieldId }}</span>
															<button 
																class="remove-field-btn"
																@click.stop="removeField(fieldId, column)"
																:title="t('Delete Field')"
															>
																×
															</button>
														</div>
														<div class="field-meta">
															<span class="field-id">{{ fieldId }}</span>
															<span class="field-type-badge">{{ getFieldById(fieldId)?.type || 'string' }}</span>
														</div>
														<div class="field-description" v-if="getFieldById(fieldId)?.description">
															{{ getFieldById(fieldId)?.description }}
														</div>
													</div>
												</div>
											</template>
										</draggable>
										<div class="column-drop-zone" v-if="column.fields.length === 0">
											{{ t('Drag fields here') }}
										</div>
									</div>
								</div>
							</template>
						</draggable>
						<div class="section-actions">
							<button class="add-column-btn" @click="addColumn(section)">
								+ {{ t('Add Column') }}
							</button>
						</div>
					</div>
				</div>
			</template>
		</draggable>
		<div class="add-section-area">
			<button class="add-section-btn" @click="addNewSection">
				+ {{ t('Add Section') }}
			</button>
		</div>
	</div>
</template>

<script setup>
import { useSchemaStore } from "../store";
import { computed, onMounted, onUnmounted } from "vue";
import EditableInput from "./EditableInput.vue";
import draggable from "vuedraggable";
import { useDialog } from 'naive-ui';
import { t } from '@/shared/i18n';

const props = defineProps({
	tab: {
		type: Object,
		required: true
	}
});

const store = useSchemaStore();
const dialog = useDialog();

// 拖拽类型判断辅助函数
function getDragType(event) {
	// 优先检查 application/json 格式的数据
	try {
		const jsonData = event.dataTransfer.getData('application/json');
		if (jsonData) {
			const data = JSON.parse(jsonData);
			return {
				type: data.type,
				data: data,
				isValid: true
			};
		}
	} catch (e) {
		// JSON 解析失败，忽略
	}
	
	// 检查工具箱拖拽
	const source = event.dataTransfer.getData('source');
	const fieldType = event.dataTransfer.getData('text/plain');
	if (source === 'toolbox' && fieldType) {
		return {
			type: 'field',
			data: { source: 'toolbox', fieldType },
			isValid: true
		};
	}
	
	// 检查其他可能的拖拽类型
	const htmlData = event.dataTransfer.getData('text/html');
	if (htmlData) {
		// 可以在这里添加对HTML内容的解析逻辑
		return {
			type: 'unknown',
			data: { htmlData },
			isValid: false
		};
	}
	
	return {
		type: 'unknown',
		data: null,
		isValid: false
	};
}

// 判断拖拽源类型
function getDragSourceType(event) {
	const dragType = getDragType(event);
	
	if (!dragType.isValid) {
		return 'unknown';
	}
	
	switch (dragType.type) {
		case 'field':
			return 'field';
		case 'column':
			return 'column';
		case 'section':
			return 'section';
		default:
			return 'unknown';
	}
}

// 判断拖拽目标类型
function getDragTargetType(targetElement) {
	if (!targetElement) return 'unknown';
	
	if (targetElement.classList.contains('field-item')) {
		return 'field';
	}
	
	if (targetElement.classList.contains('section-column')) {
		return 'column';
	}
	
	if (targetElement.classList.contains('schema-section')) {
		return 'section';
	}
	
	// 检查父级元素
	const parentColumn = targetElement.closest('.section-column');
	if (parentColumn) {
		return 'column';
	}
	
	const parentSection = targetElement.closest('.schema-section');
	if (parentSection) {
		return 'section';
	}
	
	return 'unknown';
}

// 添加拖拽状态跟踪
const dragState = {
	isDragging: false,
	dragSource: null,
	dragTarget: null,
	dragStartTime: 0,
	lastDropTarget: null
};

// 添加全局拖拽事件监听器
onMounted(() => {
	// 监听拖拽开始
	document.addEventListener('dragstart', (e) => {
		dragState.isDragging = true;
		dragState.dragStartTime = Date.now();
		dragState.dragSource = e.target;
		dragState.dragTarget = null;
		dragState.lastDropTarget = null;
	});
	
	// 监听拖拽悬停
	document.addEventListener('dragover', (e) => {
		if (dragState.isDragging) {
			const target = e.target.closest('.section-column, .schema-section');
			if (target) {
				dragState.dragTarget = target;
			}
		}
	});
	
	// 监听拖拽释放
	document.addEventListener('drop', (e) => {
		// 记录最后的拖拽目标
		const dropTarget = e.target.closest('.section-column, .schema-section');
		if (dropTarget) {
			dragState.lastDropTarget = dropTarget;
			
			// 如果拖拽目标是列，记录更详细的信息
			if (dropTarget.classList.contains('section-column')) {
				dragState.lastDropTarget = {
					element: dropTarget,
					type: 'column',
					columnId: dropTarget.dataset.columnId,
					sectionId: dropTarget.closest('.schema-section')?.dataset.sectionId
				};
			} else if (dropTarget.classList.contains('schema-section')) {
				dragState.lastDropTarget = {
					element: dropTarget,
					type: 'section',
					sectionId: dropTarget.dataset.sectionId
				};
			}
		}
		
		// 延迟重置拖拽状态，确保组件内的拖拽事件先处理
		setTimeout(() => {
			dragState.isDragging = false;
			dragState.dragSource = null;
			dragState.dragTarget = null;
		}, 200);
	});
	
	// 监听拖拽结束
	document.addEventListener('dragend', (e) => {
		// 拖拽状态重置在drop事件中处理
	});
});

onUnmounted(() => {
	// 清理事件监听器
	document.removeEventListener('dragstart', () => {});
	document.removeEventListener('dragover', () => {});
	document.removeEventListener('drop', () => {});
	document.removeEventListener('dragend', () => {});
});

function getColumnFields(column) {
	return column.fields.map(fieldId => {
		return store.properties.find(p => p.key === fieldId);
	}).filter(Boolean);
}

function getFieldById(fieldId) {
	return store.properties.find(p => p.key === fieldId);
}

function onFieldDragStart(event) {
	const fieldId = event.item?.getAttribute('data-field-id');
	
	if (fieldId && event.dataTransfer) {
		// 设置拖拽数据
		event.dataTransfer.setData('application/json', JSON.stringify({
			type: 'field',
			fieldId: fieldId,
			sourceTabId: props.tab.id,
			sourceSectionId: getFieldSectionId(fieldId),
			sourceColumnId: getFieldColumnId(fieldId)
		}));
		
		// 设置拖拽效果
		event.dataTransfer.effectAllowed = 'move';
	}
}

// 添加列拖拽开始事件
function onColumnDragStart(event, column) {
	if (event.dataTransfer) {
		event.dataTransfer.setData('application/json', JSON.stringify({
			type: 'column',
			columnId: column.id,
			columnLabel: column.label,
			sourceSectionId: column.sectionId || props.tab.id,
			sourceTabId: props.tab.id,
			fields: column.fields || []
		}));
		
		// 设置拖拽效果
		event.dataTransfer.effectAllowed = 'move';
	}
}

function onFieldChange(event) {
	if (event.added || event.removed || event.moved) {
		store.markDirty();
	}
}

function removeField(fieldId, column) {
	const field = store.properties.find(p => p.key === fieldId);
	const fieldTitle = field?.title || fieldId;
	
	dialog.error({
		title: '确认删除',
		content: `确定要删除字段 "${fieldTitle}" 吗？此操作不可恢复。`,
		positiveText: '删除',
		negativeText: '取消',
		onPositiveClick: () => {
			store.removeProperty(fieldId);

			const fieldIndex = column.fields.indexOf(fieldId);
			if (fieldIndex > -1) {
				column.fields.splice(fieldIndex, 1);
			}

			store.markDirty();
		}
	});
}

function addNewSection() {
	if (props.tab) {
		store.addSection(props.tab.id);
	}
}

function removeSection(section) {
	const totalFields = section.columns.reduce((count, column) => count + column.fields.length, 0);
	
	// 如果没有字段，直接删除，不需要确认
	if (totalFields === 0) {
		if (props.tab) {
			store.removeSection(props.tab.id, section.id);
		}
		return;
	}
	
	// 有字段时才显示确认对话框
	dialog.error({
		title: '确认删除',
		content: `确定要删除分组 "${section.label}" 吗？这将同时删除分组内的 ${totalFields} 个字段，此操作不可恢复。`,
		positiveText: '删除',
		negativeText: '取消',
		onPositiveClick: () => {
			if (props.tab) {
				section.columns.forEach(column => {
					column.fields.forEach(fieldId => {
						store.removeProperty(fieldId);
					});
				});
				
				store.removeSection(props.tab.id, section.id);
				store.markDirty();
			}
		}
	});
}

function addColumn(section) {
	if (props.tab) {
		store.addColumn(props.tab.id, section.id);
	}
}

function removeColumn(section, column) {
	if (props.tab && section.columns.length > 1) {
		const fieldCount = column.fields.length;
		
		// 如果没有字段，直接删除，不需要确认
		if (fieldCount === 0) {
			store.removeColumn(props.tab.id, section.id, column.id);
			return;
		}
		
		// 有字段时才显示确认对话框
	dialog.error({
		title: '确认删除',
		content: `确定要删除列 "${column.label}" 吗？这将同时删除列内的 ${fieldCount} 个字段，此操作不可恢复。`,
		positiveText: '删除',
		negativeText: '取消',
		onPositiveClick: () => {
			column.fields.forEach(fieldId => {
				store.removeProperty(fieldId);
			});
			
			store.removeColumn(props.tab.id, section.id, column.id);
			store.markDirty();
		}
	});
	}
}

function onColumnDrop(event, column) {
	event.preventDefault();
	event.stopPropagation();
	
	// 清理拖拽样式
	const columnElement = event.target.closest('.section-column');
	if (columnElement) {
		columnElement.classList.remove('drag-over');
	}
	
	// 使用新的拖拽类型判断系统
	const dragType = getDragType(event);
	
	if (!dragType.isValid) {
		return;
	}
	
	switch (dragType.type) {
		case 'field':
			handleFieldDrop(event, column, dragType.data);
			break;
		case 'column':
			// 列拖拽由 onColumnsReorder 处理
			break;
		case 'section':
			// 分组拖拽由 onSectionsReorder 处理
			break;
		default:
			// 处理工具箱拖拽
			if (dragType.data.source === 'toolbox' && dragType.data.fieldType) {
				store.addPropertyToColumn(column.id, dragType.data.fieldType);
			}
			break;
	}
}

// 处理字段拖拽到列
function handleFieldDrop(event, targetColumn, fieldData) {
	// 如果是从工具箱拖拽的新字段
	if (fieldData.source === 'toolbox' && fieldData.fieldType) {
		store.addPropertyToColumn(targetColumn.id, fieldData.fieldType);
		return;
	}
	
	// 如果是从其他列拖拽的字段
	if (fieldData.fieldId) {
		// 检查是否是跨列拖拽
		if (fieldData.sourceColumnId && fieldData.sourceColumnId !== targetColumn.id) {
			// 从源列移除字段
			const sourceColumn = findColumnById(fieldData.sourceColumnId);
			if (sourceColumn) {
				const fieldIndex = sourceColumn.fields.indexOf(fieldData.fieldId);
				if (fieldIndex > -1) {
					sourceColumn.fields.splice(fieldIndex, 1);
				}
			}
			
			// 添加到目标列
			if (!targetColumn.fields.includes(fieldData.fieldId)) {
				targetColumn.fields.push(fieldData.fieldId);
			}
			
			store.markDirty();
		}
	}
}

// 根据列ID查找列对象
function findColumnById(columnId) {
	if (!props.tab?.sections) return null;
	
	for (const section of props.tab.sections) {
		if (section.columns) {
			const column = section.columns.find(col => col.id === columnId);
			if (column) {
				return column;
			}
		}
	}
	return null;
}

// 获取字段所在的分组ID
function getFieldSectionId(fieldId) {
	if (!props.tab?.sections) return null;
	
	for (const section of props.tab.sections) {
		if (section.columns) {
			for (const column of section.columns) {
				if (column.fields && column.fields.includes(fieldId)) {
					return section.id;
				}
			}
		}
	}
	return null;
}

// 获取字段所在的列ID
function getFieldColumnId(fieldId) {
	if (!props.tab?.sections) return null;
	
	for (const section of props.tab.sections) {
		if (section.columns) {
			for (const column of section.columns) {
				if (column.fields && column.fields.includes(fieldId)) {
					return column.id;
				}
			}
		}
	}
	return null;
}

function onColumnDragOver(event) {
	event.preventDefault();
	event.dataTransfer.dropEffect = 'copy';
	const columnElement = event.target.closest('.section-column');
	if (columnElement) {
		columnElement.classList.add('drag-over');
	}
}

function onColumnDragLeave(event) {
	const columnElement = event.target.closest('.section-column');
	if (columnElement) {
		columnElement.classList.remove('drag-over');
	}
}

function onSectionDrop(event, section) {
	event.preventDefault();
	const sectionElement = event.target.closest('.schema-section');
	if (sectionElement) {
		sectionElement.classList.remove('drag-over');
	}
	
	// 使用新的拖拽类型判断系统
	const dragType = getDragType(event);
	
	if (!dragType.isValid) {
		return;
	}
	
	switch (dragType.type) {
		case 'field':
			// 字段拖拽到分组，自动创建新列
			handleFieldDropToSection(event, section, dragType.data);
			break;
		case 'column':
			// 列拖拽到分组
			handleColumnDropToSection(event, section, dragType.data);
			break;
		case 'section':
			// 分组拖拽由 onSectionsReorder 处理
			break;
		default:
			// 处理工具箱拖拽
			if (dragType.data.source === 'toolbox' && dragType.data.fieldType) {
				store.addPropertyToSection(section.id, dragType.data.fieldType);
			}
			break;
	}
}

// 处理字段拖拽到分组
function handleFieldDropToSection(event, targetSection, fieldData) {
	// 如果是从工具箱拖拽的新字段
	if (fieldData.source === 'toolbox' && fieldData.fieldType) {
		store.addPropertyToSection(targetSection.id, fieldData.fieldType);
		return;
	}
	
	// 如果是从其他列拖拽的字段，创建新列来接收
	if (fieldData.fieldId) {
		// 确保分组有列结构
		if (!targetSection.columns || targetSection.columns.length === 0) {
			targetSection.columns = [];
		}
		
		// 创建新列
		const newColumn = {
			id: `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
			label: `列 ${targetSection.columns.length + 1}`,
			fields: [fieldData.fieldId]
		};
		
		targetSection.columns.push(newColumn);
		
		// 从源列移除字段
		if (fieldData.sourceColumnId) {
			const sourceColumn = findColumnById(fieldData.sourceColumnId);
			if (sourceColumn) {
				const fieldIndex = sourceColumn.fields.indexOf(fieldData.fieldId);
				if (fieldIndex > -1) {
					sourceColumn.fields.splice(fieldIndex, 1);
				}
			}
		}
		
		store.markDirty();
	}
}

// 处理列拖拽到分组
function handleColumnDropToSection(event, targetSection, columnData) {
	// 如果列来自其他分组，则在新分组中创建新列
	if (columnData.sourceSectionId !== targetSection.id) {
		// 确保分组有列结构
		if (!targetSection.columns || targetSection.columns.length === 0) {
			targetSection.columns = [];
		}
		
		// 添加新列
		const newColumn = {
			id: `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
			label: columnData.columnLabel || '',
			fields: columnData.fields || []
		};
		
		targetSection.columns.push(newColumn);
		store.markDirty();
	}
}

function onSectionDragOver(event) {
	event.preventDefault();
	event.dataTransfer.dropEffect = 'copy';
	const sectionElement = event.target.closest('.schema-section');
	if (sectionElement) {
		sectionElement.classList.add('drag-over');
	}
}

function onSectionDragLeave(event) {
	const sectionElement = event.target.closest('.schema-section');
	if (sectionElement) {
		sectionElement.classList.remove('drag-over');
	}
}

function onSectionsReorder(event) {
	if (event && event.added) {
		// 处理跨标签拖拽分组
		const { newIndex, element } = event.added;
		const section = element;
		
		// 如果分组来自其他标签页，需要更新其所属的标签页ID
		if (section.tabId && section.tabId !== props.tab.id) {
			// 调用store的移动函数
			store.moveSection(section.id, section.tabId, props.tab.id);
		}
		
		// 确保分组有唯一的ID
		if (!section.id || section.id.startsWith('section_')) {
			section.id = `section_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
		}
	}
	
	store.markDirty();
}

function onColumnsReorder(section, event) {
	// 处理列被添加到新分组的情况
	if (event && event.added) {
		const { newIndex, element } = event.added;
		const column = element;
		
		// 如果列来自其他分组或标签页，需要调用store的移动函数
		if ((column.sectionId && column.sectionId !== section.id) || 
			(column.tabId && column.tabId !== props.tab.id)) {
			store.moveColumn(
				column.id, 
				column.sectionId || section.id, 
				section.id, 
				column.tabId || props.tab.id, 
				props.tab.id
			);
		}
		
		// 确保列有唯一的ID
		if (!column.id || column.id.startsWith('column_')) {
			column.id = `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
		}
		
		// 检查是否需要为新拖拽的列创建新的列容器
		// 如果拖拽目标是已有列，则创建新列来避免嵌套
		if (dragState.lastDropTarget && dragState.lastDropTarget.type === 'column') {
			const targetColumnId = dragState.lastDropTarget.columnId;
			const targetColumn = section.columns.find(col => col.id === targetColumnId);
			
			if (targetColumn && targetColumn !== column) {
						// 创建新列来接收拖拽的列
		const newColumn = {
			id: `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
			label: '',
			fields: []
		};
				
				// 将拖拽列的内容复制到新列
				if (column.fields && Array.isArray(column.fields)) {
					newColumn.fields = [...column.fields];
				}
				
				// 将新列添加到分组中
				section.columns.push(newColumn);
				
				// 从原位置移除拖拽的列
				const originalSection = findOriginalSection(column.id);
				if (originalSection) {
					const originalColumnIndex = originalSection.columns.findIndex(col => col.id === column.id);
					if (originalColumnIndex > -1) {
						originalSection.columns.splice(originalColumnIndex, 1);
					}
				}
				
				// 标记数据已更改
				store.markDirty();
				return; // 提前返回，避免后续处理
			}
		}
		
		// 规范化新分组的列结构
		normalizeSectionStructure(section);
	}
	
	// 处理列被移除的情况（可能是拖拽到空白区域）
	if (event && event.removed && !event.added) {
		const { oldIndex, element } = event.removed;
		const removedColumn = element;
		
		// 检查是否真的拖拽到了空白区域
		// 如果拖拽目标是有效的分组或列，则不创建新分组
		if (dragState.lastDropTarget && 
			(dragState.lastDropTarget.type === 'column' || dragState.lastDropTarget.type === 'section')) {
			// 拖拽到有效目标，跳过创建新分组
		} else {
			// 拖拽到空白区域，准备创建新分组
			setTimeout(() => {
				checkAndCreateNewSectionForOrphanedColumn(removedColumn);
			}, 100);
		}
	}
	
	// 清理无效的空分组
	cleanupEmptySections();
	
	store.markDirty();
}

// 规范化分组结构，确保与手动创建的分组一致
function normalizeSectionStructure(section) {
	// 确保分组有基本的列结构
	if (!section.columns || section.columns.length === 0) {
		section.columns = [{
			id: `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
			label: '',
			fields: []
		}];
	}
	
	// 不再强制设置列标签，允许空白
	section.columns.forEach((column, index) => {
		// 只确保label属性存在，不强制设置默认值
		if (column.label === undefined) {
			column.label = '';
		}
	});
}

// 为拖拽到空白区域的列创建新分组
function createNewSectionForColumn(column) {
	if (!props.tab?.sections) {
		return;
	}
	
	// 创建新分组
	const newSection = {
		id: `section_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
		label: '',
		columns: []
	};
	
	// 创建新列来接收拖拽的列
	const newColumn = {
		id: `column_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
		label: '',
		fields: []
	};
	
	// 将原列的内容复制到新列
	if (column.fields && Array.isArray(column.fields)) {
		newColumn.fields = [...column.fields];
	}
	
	// 将新列添加到新分组
	newSection.columns.push(newColumn);
	
	// 将新分组添加到标签页
	props.tab.sections.push(newSection);
	
	// 标记数据已更改
	store.markDirty();
}

// 检查并创建新分组（用于处理真正拖拽到空白区域的列）
function checkAndCreateNewSectionForOrphanedColumn(column) {
	// 检查列是否真的存在于任何分组中
	let columnExists = false;
	
	if (props.tab?.sections) {
		for (const section of props.tab.sections) {
			if (section.columns && Array.isArray(section.columns)) {
				const foundColumn = section.columns.find(col => col.id === column.id);
				if (foundColumn) {
					columnExists = true;
					break;
				}
			}
		}
	}
	
	// 只有当列真的不存在于任何分组中时，才创建新分组
	if (!columnExists) {
		createNewSectionForColumn(column);
	}
}

// 查找列原来所在的分组
function findOriginalSection(columnId) {
	if (!props.tab?.sections) {
		return null;
	}
	
	for (const section of props.tab.sections) {
		if (section.columns && Array.isArray(section.columns)) {
			const foundColumn = section.columns.find(col => col.id === columnId);
			if (foundColumn) {
				return section;
			}
		}
	}
	return null;
}

// 清理无效的空分组
function cleanupEmptySections() {
	if (!props.tab?.sections) {
		return;
	}
	
	// 过滤掉无效的空分组
	const validSections = props.tab.sections.filter(section => {
		// 检查分组是否有效
		if (!section || !section.id || !section.columns) {
			return false;
		}
		
		// 检查列是否有效
		if (!Array.isArray(section.columns)) {
			return false;
		}
		
		// 过滤掉无效的列
		section.columns = section.columns.filter(column => {
			if (!column || !column.id) {
				return false;
			}
			return true;
		});
		
		// 如果分组没有有效列，标记为无效
		if (section.columns.length === 0) {
			return false;
		}
		
		return true;
	});
	
	// 更新分组数据
	if (validSections.length !== props.tab.sections.length) {
		// 强制更新数据
		props.tab.sections.splice(0, props.tab.sections.length, ...validSections);
		store.markDirty();
	}
}
</script>

<style lang="scss" scoped>
.schema-sections {
	padding: 1rem;
}

.schema-section {
	background-color: var(--gray-100);
	border: 1px solid var(--border-color);
	border-radius: 8px;
	margin-bottom: 1rem;
	transition: all 0.2s ease;
	
	&.drag-over {
		border-color: var(--primary-color);
		background-color: var(--primary-light);
		box-shadow: 0 0 10px rgba(59, 130, 246, 0.3);
	}
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0.75rem 1rem;
	background-color: var(--fg-color);
	border-bottom: 1px solid var(--border-color);
}

.section-title {
	margin: 0;
	font-size: var(--text-sm);
	font-weight: 600;
	color: var(--heading-color);
}

.remove-section-btn {
	background: none;
	border: none;
	color: var(--text-muted);
	cursor: pointer;
	padding: 2px 4px;
	border-radius: 50%;
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	line-height: 1;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: var(--red-100);
		color: var(--red-600);
	}
	
	&:active {
		background-color: var(--red-200);
		color: var(--red-700);
	}
}

.section-content {
	padding: 1rem;
}

.section-columns {
	display: flex;
	gap: 1rem;
	margin-bottom: 1rem;
}

.section-column {
	flex: 1;
	min-height: 100px;
	border: 1px dashed var(--border-color);
	border-radius: var(--border-radius);
	padding: 0.5rem;
	background-color: var(--fg-color);
	transition: all 0.2s ease;
	
	&:hover {
		border-color: var(--primary-color);
		background-color: var(--light-bg-color);
	}
	
	&.drag-over {
		background-color: var(--primary-light);
		border: 2px dashed var(--primary-color);
	}
}

.column-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 0.5rem;
	padding-bottom: 0.5rem;
	border-bottom: 1px solid var(--border-color);
}

.remove-column-btn {
	background: none;
	border: none;
	color: var(--text-muted);
	cursor: pointer;
	padding: 2px 4px;
	border-radius: 50%;
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	line-height: 1;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: var(--red-100);
		color: var(--red-600);
	}
	
	&:active {
		background-color: var(--red-200);
		color: var(--red-700);
	}
}

.column-fields {
	min-height: 50px;
}

.fields-container {
	min-height: 50px;
}

.field-item {
	background-color: var(--bg-light-gray);
	border: 1px solid var(--border-color);
	border-radius: var(--border-radius-sm);
	padding: 0.5rem;
	margin-bottom: 0.5rem;
	cursor: pointer;
	transition: all 0.2s ease;
	position: relative;
	
	&:hover {
		background-color: var(--fg-color);
		border-color: var(--border-primary);
	}
	
	&.selected {
		background-color: var(--primary-light);
		border-color: var(--primary-color);
		box-shadow: 0 0 5px rgba(0, 123, 255, 0.3);
	}
}

.field-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 0.25rem;
}

.field-title {
	font-weight: 500;
	color: var(--heading-color);
	font-size: var(--text-sm);
	padding: 0 0.4rem;
}

.field-meta {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.field-id {
	font-size: var(--text-xs);
	color: var(--text-muted);
	padding: 0 0.4rem;
}

.field-description {
	font-size: var(--text-xs);
	color: var(--text-muted);
	margin-bottom: 0.5rem;
}

.remove-field-btn {
	background: none;
	border: none;
	color: var(--text-muted);
	cursor: pointer;
	padding: 2px 4px;
	border-radius: 50%;
	width: 20px;
	height: 20px;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 14px;
	line-height: 1;
	transition: all 0.2s ease;
	
	&:hover {
		background-color: var(--red-100);
		color: var(--red-600);
	}
	
	&:active {
		background-color: var(--red-200);
		color: var(--red-700);
	}
}

.field-type-badge {
	color: var(--text-muted);
	font-size: var(--text-xs);
	font-weight: 500;
	background-color: var(--gray-100);
	padding: 0.1rem 0.4rem;
	border-radius: var(--border-radius-sm);
}

.column-drop-zone {
	border: 2px dashed var(--border-color);
	border-radius: var(--border-radius-sm);
	padding: 2rem;
	text-align: center;
	color: var(--text-muted);
	background-color: var(--bg-light-gray);
	margin: 0.5rem 0;
	
	&:hover {
		border-color: var(--primary-color);
		background-color: var(--primary-light);
	}
}

.section-actions {
	display: flex;
	justify-content: center;
	margin-top: 1rem;
}

.add-column-btn {
	background-color: var(--control-bg);
	border: 1px solid var(--border-color);
	color: var(--text-color);
	padding: 0.5rem 1rem;
	border-radius: var(--border-radius);
	cursor: pointer;
	font-size: var(--text-sm);
	
	&:hover {
		background-color: var(--btn-default-hover-bg);
	}
}

.add-section-area {
	text-align: center;
	padding: 1rem;
}

.add-section-btn {
	background-color: var(--control-bg);
	border: 1px solid var(--border-color);
	color: var(--text-color);
	padding: 0.5rem 1rem;
	border-radius: var(--border-radius);
	cursor: pointer;
	font-size: var(--text-sm);
	
	&:hover {
		background-color: var(--btn-default-hover-bg);
	}
}
</style>

