<template>
	<div class="schema-tabs">
		<div class="tab-header">
			<div class="tabs">
				<div
					v-for="tab in store.layout.tabs"
					:key="tab.id"
					:class="['tab', store.layout.activeTab === tab.id ? 'active' : '']"
					:draggable="true"
					@click="activateTab(tab)"
					@dragstart="onDragStart($event, tab)"
					@dragend="onDragEnd($event)"
					@dragover="onTabDragOver($event, tab)"
					@drop="onDrop($event, tab)"
				>
					<EditableInput
						:text="tab.label"
						:placeholder="t('Tab Name')"
						@update:modelValue="store.updateTabLabel(tab.id, $event)"
						@click="activateTab(tab)"
					/>
					<button
						v-if="store.layout.tabs.length > 1"
						class="remove-tab-btn"
						@click.stop="removeTab(tab)"
						title="删除标签页"
					>
						×
					</button>
				</div>
			</div>
			<div class="tab-actions">
				<button class="add-tab-btn" @click="addNewTab" :title="t('Add Tab')">
					+ {{ t('Add Tab') }}
				</button>
			</div>
		</div>
		<!-- 所有标签页内容区域，同时渲染但控制可见性 -->
		<div 
			v-for="tab in store.layout.tabs"
			:key="tab.id"
			class="tab-content-area"
			:class="{ 'active': store.layout.activeTab === tab.id }"
			:style="{ display: store.layout.activeTab === tab.id ? 'block' : 'none' }"
		>
			<!-- 这里将渲染 SchemaSections 组件 -->
			<SchemaSections :tab="tab" />
		</div>
	</div>
</template>

<script setup>
import { useSchemaStore } from "../store";
import EditableInput from "./EditableInput.vue";
import SchemaSections from "./SchemaSections.vue";
import { useDialog } from 'naive-ui';
import { t } from '@/shared/i18n';

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

// 全局拖拽状态跟踪
let dragState = {
	isDragging: false,
	draggedTabId: null,
	dragStartTime: 0
};

function addNewTab() {
	store.addTab();
}

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

function activateTab(tab) {
	store.activateTab(tab.id);
}

function onDragStart(event, tab) {
	event.dataTransfer.setData('text/plain', tab.id);
	event.dataTransfer.effectAllowed = 'move';
	event.target.classList.add('dragging');
	
	// 记录拖拽状态
	dragState.isDragging = true;
	dragState.draggedTabId = tab.id;
	dragState.dragStartTime = Date.now();
}

function onDragEnd(event) {
	event.target.classList.remove('dragging');
	
	// 重置拖拽状态
	dragState.isDragging = false;
	dragState.draggedTabId = null;
	dragState.dragStartTime = 0;
}

// 标签页拖拽悬停事件 - 智能判断拖拽类型
function onTabDragOver(event, tab) {
	// 检查是否是标签页拖拽（用于重排序）
	// 使用全局拖拽状态，避免在dragover中调用getData()清空数据
	if (dragState.isDragging && dragState.draggedTabId && dragState.draggedTabId.startsWith('tab_')) {
		// 标签页拖拽 - 处理重排序
		event.preventDefault();
		event.dataTransfer.dropEffect = 'move';
		return;
	}
	
	// 检查是否是字段拖拽（用于激活标签页）
	if (event.dataTransfer.types.includes('application/json') || 
		(event.dataTransfer.types.includes('text/plain') && !dragState.draggedTabId?.startsWith('tab_'))) {
		// 字段拖拽 - 激活标签页
		if (store.layout.activeTab !== tab.id) {
			activateTab(tab);
		}
	}
}

function onDrop(event, targetTab) {
	event.preventDefault();
	const draggedTabId = event.dataTransfer.getData('text/plain');
	
	// 检查是否是标签页拖拽（通过ID前缀判断）
	if (draggedTabId && draggedTabId.startsWith('tab_') && draggedTabId !== targetTab.id) {
		const tabs = store.layout.tabs;
		const draggedIndex = tabs.findIndex(tab => tab.id === draggedTabId);
		const targetIndex = tabs.findIndex(tab => tab.id === targetTab.id);
		
		if (draggedIndex !== -1 && targetIndex !== -1) {
			const draggedTab = tabs.splice(draggedIndex, 1)[0];
			tabs.splice(targetIndex, 0, draggedTab);
			store.markDirty();
		}
		return;
	}
	
	// 处理其他类型的拖拽（字段拖拽等）
	try {
		const fieldData = JSON.parse(event.dataTransfer.getData('application/json'));
		if (fieldData.type === 'field') {
			handleFieldDropToTab(fieldData);
			return;
		}
	} catch (e) {
		// 不是JSON数据，可能是从侧边栏拖拽的新字段
	}
	
	// 从侧边栏拖拽新字段
	const fieldType = event.dataTransfer.getData('text/plain');
	if (fieldType && !fieldType.startsWith('tab_')) {
		store.addPropertyToTab(store.layout.activeTab, fieldType);
	}
}

// 标签页内容区域拖拽处理
function onTabContentDragOver(event) {
	event.preventDefault();
	event.dataTransfer.dropEffect = 'move';
}

function onTabContentDrop(event) {
	event.preventDefault();
	
	// 检查是否是字段拖拽
	try {
		const fieldData = JSON.parse(event.dataTransfer.getData('application/json'));
		if (fieldData.type === 'field') {
			// 字段拖拽到标签页，添加到第一个分组的第一个列
			handleFieldDropToTab(fieldData);
			return;
		}
	} catch (e) {
		// 不是JSON数据，可能是从侧边栏拖拽的新字段
	}
	
	// 从侧边栏拖拽新字段
	const fieldType = event.dataTransfer.getData('text/plain');
	if (fieldType) {
		store.addPropertyToTab(store.layout.activeTab, fieldType);
	}
}

// 处理字段拖拽到标签页
function handleFieldDropToTab(fieldData) {
	const { fieldId, sourceColumnId, sourceSectionId, sourceTabId } = fieldData;
	
	// 从源列移除字段
	if (sourceColumnId && sourceSectionId && sourceTabId) {
		const sourceTab = store.layout.tabs.find(t => t.id === sourceTabId);
		if (sourceTab) {
			const sourceSection = sourceTab.sections.find(s => s.id === sourceSectionId);
			if (sourceSection) {
				const sourceColumn = sourceSection.columns.find(c => c.id === sourceColumnId);
				if (sourceColumn) {
					const fieldIndex = sourceColumn.fields.indexOf(fieldId);
					if (fieldIndex > -1) {
						sourceColumn.fields.splice(fieldIndex, 1);
					}
				}
			}
		}
	}
	
	// 添加到目标标签页的第一个分组的第一个列
	const targetTab = store.layout.tabs.find(t => t.id === store.layout.activeTab);
	if (targetTab && targetTab.sections.length > 0) {
		const firstSection = targetTab.sections[0];
		if (firstSection.columns.length > 0) {
			const firstColumn = firstSection.columns[0];
			// 检查字段是否已经在目标列中
			if (!firstColumn.fields.includes(fieldId)) {
				firstColumn.fields.push(fieldId);
			}
		}
	}
	
	store.markDirty();
}
</script>

<style lang="scss" scoped>
.schema-tabs {
	border-bottom: 1px solid var(--border-color);
	background-color: var(--fg-color);
	margin-top: 0;
	/* 新增：让 tabs 容器占满父容器，便于子元素按 100% 高度计算 */
	display: flex;
	flex-direction: column;
	height: 100%;
	min-height: 0;
}

.tab-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0 1rem;
	min-height: 42px;
	/* 固定头部高度，不参与伸缩 */
	flex: 0 0 auto;
}

.tabs {
	display: flex;
	flex: 1;
	overflow-x: auto;
}

.tab {
	display: flex;
	align-items: center;
	padding: 10px 18px 10px 15px;
	color: var(--text-muted);
	cursor: pointer;
	border-bottom: 2px solid transparent;
	position: relative;
	min-width: max-content;
	transition: all 0.2s ease;
	
	&[draggable="true"] {
		cursor: grab;
		
		&:active {
			cursor: grabbing;
		}
	}
	
	&.dragging {
		opacity: 0.5;
		transform: rotate(5deg);
	}
	
	&:hover {
		color: var(--text-color);
	}
	
	&.active {
		color: var(--text-color);
		font-weight: 600;
		border-bottom-color: var(--border-primary);
	}
}

.remove-tab-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;
	
	&:hover {
		background-color: var(--red-500);
		color: white;
	}
}

.tab-actions {
	margin-left: 1rem;
}

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

.tab-content-area {
	border-top: 1px solid var(--border-color);
	flex: 1 1 auto;
	min-height: 0;
	overflow: auto;
}

.tab-content-drop-zone {
	border: 2px dashed var(--border-color);
	border-radius: var(--border-radius);
	padding: 2rem;
	text-align: center;
	color: var(--text-muted);
	background-color: var(--fg-color);
	transition: all 0.2s ease;
	
	&:hover {
		border-color: var(--primary-color);
		background-color: var(--primary-light);
	}
}
</style>
