import { defineStore } from "pinia";
import { ref, computed } from "vue";
import { t } from '@/shared/i18n';

export const useSchemaStore = defineStore("schema-builder-store", () => {
	// State
	const schema = ref({
		properties: {},
		required: []
	});
	
	const properties = ref([]);
	const selectedField = ref(null);
	const preview = ref(false);
	const readOnly = ref(false);
	const dirty = ref(false);
	
	// Layout structure for tabs and sections
	const layout = ref({
		tabs: [
			{
				id: 'tab_1',
				label: t('Tab Name'),
				sections: [
					{
						id: 'section_1',
						label: t('Section Name'),
						columns: [
							{
								id: 'column_1',
								fields: []
							}
						]
					}
				]
			}
		],
		activeTab: 'tab_1'
	});
	
	// Getters
	const notUsingInput = computed(() => {
		// 检查是否正在使用输入框
		const activeElement = document.activeElement;
		return !activeElement || 
			activeElement.readOnly || 
			activeElement.disabled ||
			(activeElement.tagName !== "INPUT" && activeElement.tagName !== "TEXTAREA");
	});
	
	// Actions
	function addProperty(type = "string") {
		const key = `field_${Date.now()}`;
		const newProperty = {
			key,
			type,
			title: t("New Field"),
			description: "",
			required: false,
			default: "",
			condition: ""
		};
		
		// 为textarea类型设置默认rows
		if (type === "textarea") {
			newProperty.format = "textarea";
			newProperty.rows = 3;
		}
		
		properties.value.push(newProperty);
		updateSchema();
		selectedField.value = key;
		dirty.value = true;
	}
	
	function removeProperty(key) {
		const index = properties.value.findIndex(p => p.key === key);
		if (index > -1) {
			properties.value.splice(index, 1);
			updateSchema();
			if (selectedField.value === key) {
				selectedField.value = null;
			}
			dirty.value = true;
		}
	}
	
	function updateProperty(key, updatedProperty) {
		const index = properties.value.findIndex(p => p.key === key);
		if (index > -1) {
			properties.value[index] = { ...properties.value[index], ...updatedProperty };
			updateSchema();
			dirty.value = true;
		}
	}
	
	function updateFieldKey(event) {
		// 提取新键名
		const newKey = extractKeyFromEvent(event);
		if (!newKey) return;
		
		const oldKey = selectedField.value;
		if (!oldKey || newKey === oldKey) return;
		
		// 验证新键名
		const validation = validateNewKey(newKey);
		if (!validation.valid) {
			// 触发错误事件，让组件处理
			const errorEvent = new CustomEvent('schema-builder-error', {
				detail: { message: validation.message, type: 'error' }
			});
			document.dispatchEvent(errorEvent);
			return;
		}
		
		// 执行字段重命名
		if (renameField(oldKey, newKey)) {
			// 更新选中字段引用
			selectedField.value = newKey;
			// 设置修改状态
			dirty.value = true;
		}
	}
	
	// 从事件中提取键名
	function extractKeyFromEvent(event) {
		if (typeof event === 'string') {
			return event;
		} else if (event?.target?.value !== undefined) {
			return event.target.value;
		}
		// 静默处理无效参数，不在控制台显示错误
		return null;
	}
	
	// 验证新键名
	function validateNewKey(newKey) {
		// 检查是否已存在
		if (properties.value.find(p => p.key === newKey)) {
			return { valid: false, message: t('Field ID already exists, please use another ID') };
		}
		
		// 检查格式（可选：添加更严格的验证）
		if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(newKey)) {
			return { valid: false, message: t('Field ID must start with letter/underscore and contain only letters, numbers, underscores') };
		}
		
		return { valid: true };
	}
	
	// 重命名字段
	function renameField(oldKey, newKey) {
		try {
			// 找到要更新的字段
			const fieldIndex = properties.value.findIndex(p => p.key === oldKey);
			if (fieldIndex === -1) return false;
			
			// 创建新字段，保持所有属性不变，只更新 key
			const oldField = properties.value[fieldIndex];
			const newField = { ...oldField, key: newKey };
			
			// 替换旧字段
			properties.value[fieldIndex] = newField;
			
			// 更新布局中的字段引用
			updateLayoutFieldReferences(oldKey, newKey);
			
			// 更新 schema
			updateSchema();
			
			return true;
		} catch (error) {
			return false;
		}
	}
	
	function updateLayoutFieldReferences(oldKey, newKey) {
		// 更新布局中所有对旧键名的引用
		layout.value.tabs.forEach(tab => {
			tab.sections.forEach(section => {
				section.columns.forEach(column => {
					const fieldIndex = column.fields.indexOf(oldKey);
					if (fieldIndex > -1) {
						column.fields[fieldIndex] = newKey;
					}
				});
			});
		});
	}
	
	function updateSchema() {
		// 更新 schema 对象
		schema.value.properties = {};
		schema.value.required = [];
		
		properties.value.forEach(prop => {
			schema.value.properties[prop.key] = {
				type: prop.type,
				title: prop.title,
				description: prop.description
			};
			
			// 添加默认值（如果存在且不为空）
			if (prop.default !== undefined && prop.default !== "") {
				schema.value.properties[prop.key].default = prop.default;
			}
			
			// 添加条件表达式（如果存在且不为空）
			if (prop.condition && typeof prop.condition === 'string' && prop.condition.trim()) {
				try {
					schema.value.properties[prop.key].condition = JSON.parse(prop.condition.trim());
				} catch (e) {
					schema.value.properties[prop.key].condition = prop.condition;
				}
			} else if (prop.condition) {
				// 如果不是字符串，直接保存
				schema.value.properties[prop.key].condition = prop.condition;
			}
			
			// 添加高级属性（只保存非空值）
			if (prop.format && typeof prop.format === 'string' && prop.format.trim()) {
				schema.value.properties[prop.key].format = prop.format;
			}
			
			// 保存数组和对象的内部结构
			if (prop.items) {
				schema.value.properties[prop.key].items = prop.items;
			}
			
			if (prop.properties) {
				schema.value.properties[prop.key].properties = prop.properties;
			}
			
			// 保存数组的默认值和其他属性
			if (prop.default !== undefined && prop.default !== "") {
				schema.value.properties[prop.key].default = prop.default;
			}
			
			if (prop.minItems !== undefined) {
				schema.value.properties[prop.key].minItems = prop.minItems;
			}
			
			if (prop.maxItems !== undefined) {
				schema.value.properties[prop.key].maxItems = prop.maxItems;
			}
			
			if (prop.rows && prop.rows > 0) {
				schema.value.properties[prop.key].rows = prop.rows;
			} else if (prop.format === 'textarea') {
				schema.value.properties[prop.key].rows = 3;
			}
			
			if (prop.minLength !== undefined && prop.minLength !== null && prop.minLength !== '') {
				schema.value.properties[prop.key].minLength = prop.minLength;
			}
			
			if (prop.maxLength !== undefined && prop.maxLength !== null && prop.maxLength !== '') {
				schema.value.properties[prop.key].maxLength = prop.maxLength;
			}
			
			if (prop.pattern && typeof prop.pattern === 'string' && prop.pattern.trim()) {
				schema.value.properties[prop.key].pattern = prop.pattern;
			}
			
			if (prop.placeholder && typeof prop.placeholder === 'string' && prop.placeholder.trim()) {
				schema.value.properties[prop.key].placeholder = prop.placeholder;
			}
			
			// 添加枚举相关属性
			if (prop.enum && Array.isArray(prop.enum) && prop.enum.length > 0) {
				schema.value.properties[prop.key].enum = prop.enum;
			}
			
			if (prop.enumNames && Array.isArray(prop.enumNames) && prop.enumNames.length > 0) {
				schema.value.properties[prop.key].enumNames = prop.enumNames;
			}
			
			// 添加选择器相关属性
			if (prop.multiple !== undefined) {
				schema.value.properties[prop.key].multiple = prop.multiple;
			}
			
			// 添加布局相关属性
			if (prop.layout && typeof prop.layout === 'string' && prop.layout.trim()) {
				schema.value.properties[prop.key].layout = prop.layout;
			}
			
			if (prop.required) {
				schema.value.required.push(prop.key);
			}
		});
		
		// 保存布局信息到 schema 中
		schema.value._layout = {
			tabs: layout.value.tabs,
			activeTab: layout.value.activeTab
		};
		
		// 保持allOf字段（如果存在）
		if (schema.value.allOf) {
			// allOf字段保持不变，由专门的函数更新
		}
	}
	
	function togglePreview() {
		preview.value = !preview.value;
	}
	
	function saveSchema() {
		// 触发保存事件
		dirty.value = false;
		// 这里可以触发父组件的保存事件
	}
	
	function loadSchema(schemaData) {
		if (typeof schemaData === "string") {
			try {
				schemaData = JSON.parse(schemaData);
			} catch (e) {
				return;
			}
		
		}
		
		// 重置状态
		schema.value = { ...schemaData };
		properties.value = [];
		
		// 加载字段属性
		if (schemaData.properties) {
			Object.entries(schemaData.properties).forEach(([key, prop]) => {
				properties.value.push({
					key,
					type: prop.type || "string",
					title: prop.title || key,
					description: prop.description || "",
					required: schemaData.required?.includes(key) || false,
					default: prop.default || "",
					condition: prop.condition || "",
					format: prop.format || undefined,
					rows: prop.rows || undefined,
					minLength: prop.minLength || undefined,
					maxLength: prop.maxLength || undefined,
					pattern: prop.pattern || undefined,
					placeholder: prop.placeholder || undefined,
					// 加载枚举相关属性
					enum: prop.enum || undefined,
					enumNames: prop.enumNames || undefined,
					// 加载选择器相关属性
					multiple: prop.multiple !== undefined ? prop.multiple : undefined,
					// 加载布局相关属性
					layout: prop.layout || undefined,
					// 加载数组和对象结构
					items: prop.items || undefined,
					properties: prop.properties || undefined,
					minItems: prop.minItems || undefined,
					maxItems: prop.maxItems || undefined
				});
			});
		}
		
		// 恢复布局信息
		if (schemaData._layout) {
			layout.value.tabs = schemaData._layout.tabs || [];
			layout.value.activeTab = schemaData._layout.activeTab || 'tab_1';
			
			// 如果没有布局信息，创建默认布局
			if (layout.value.tabs.length === 0) {
				layout.value.tabs = [
					{
						id: 'tab_1',
						label: t('Tab Name'),
						sections: [
							{
								id: 'section_1',
								label: t('Section Name'),
								columns: [
									{
										id: 'column_1',
										fields: []
									}
								]
							}
						]
					}
				];
				layout.value.activeTab = 'tab_1';
			}
		} else {
			// 如果没有布局信息，创建默认布局
			layout.value.tabs = [
				{
					id: 'tab_1',
					label: t('Tab Name'),
					sections: [
						{
							id: 'section_1',
							label: t('Section Name'),
							columns: [
								{
									id: 'column_1',
									fields: []
								}
							]
						}
					]
				}
			];
			layout.value.activeTab = 'tab_1';
		}
		

		
		dirty.value = false;
	}
	
	function setSelectedField(key) {
		selectedField.value = key;
	}
	
	// Tab and Section management
	function addTab() {
		const tabId = `tab_${Date.now()}`;
		const newTab = {
			id: tabId,
			label: t('New Tab'),
			sections: [
				{
					id: `section_${Date.now()}`,
					label: t('Section Name'),
					columns: [
						{
							id: `column_${Date.now()}`,
							fields: []
						}
					]
				}
			]
		};
		layout.value.tabs.push(newTab);
		layout.value.activeTab = tabId;
		dirty.value = true;
	}
	
	function removeTab(tabId) {
		const index = layout.value.tabs.findIndex(tab => tab.id === tabId);
		if (index > -1 && layout.value.tabs.length > 1) {
			layout.value.tabs.splice(index, 1);
			if (layout.value.activeTab === tabId) {
				layout.value.activeTab = layout.value.tabs[0].id;
			}
			dirty.value = true;
		}
	}
	
	function activateTab(tabId) {
		layout.value.activeTab = tabId;
	}
	
	function updateTabLabel(tabId, newLabel) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			tab.label = newLabel;
			dirty.value = true;
		}
	}
	
	function updateSectionLabel(tabId, sectionId, newLabel) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			const section = tab.sections.find(s => s.id === sectionId);
			if (section) {
				section.label = newLabel;
				dirty.value = true;
			}
		}
	}
	
	function updateColumnLabel(tabId, sectionId, columnId, newLabel) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			const section = tab.sections.find(s => s.id === sectionId);
			if (section) {
				const column = section.columns.find(c => c.id === columnId);
				if (column) {
					column.label = newLabel;
					dirty.value = true;
				}
			}
		}
	}
	
	function addSection(tabId) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			const newSection = {
				id: `section_${Date.now()}`,
				label: '',
				columns: [
					{
						id: `column_${Date.now()}`,
						fields: []
					}
				]
			};
			tab.sections.push(newSection);
			dirty.value = true;
		}
	}
	
	function removeSection(tabId, sectionId) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab && tab.sections.length > 1) {
			const index = tab.sections.findIndex(s => s.id === sectionId);
			if (index > -1) {
				tab.sections.splice(index, 1);
				dirty.value = true;
			}
		}
	}
	
	function getCurrentTab() {
		return layout.value.tabs.find(tab => tab.id === layout.value.activeTab);
	}
	
	function addColumn(tabId, sectionId) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			const section = tab.sections.find(s => s.id === sectionId);
			if (section) {
				const newColumn = {
					id: `column_${Date.now()}`,
					fields: []
				};
				section.columns.push(newColumn);
				dirty.value = true;
			}
		}
	}
	
	function removeColumn(tabId, sectionId, columnId) {
		const tab = layout.value.tabs.find(t => t.id === tabId);
		if (tab) {
			const section = tab.sections.find(s => s.id === sectionId);
			if (section && section.columns.length > 1) {
				const index = section.columns.findIndex(c => c.id === columnId);
				if (index > -1) {
					section.columns.splice(index, 1);
					dirty.value = true;
				}
			}
		}
	}
	
	// 移动分组到其他标签页
	function moveSection(sectionId, fromTabId, toTabId) {
		const fromTab = layout.value.tabs.find(t => t.id === fromTabId);
		const toTab = layout.value.tabs.find(t => t.id === toTabId);
		
		if (fromTab && toTab) {
			const sectionIndex = fromTab.sections.findIndex(s => s.id === sectionId);
			if (sectionIndex > -1) {
				const section = fromTab.sections.splice(sectionIndex, 1)[0];
				section.tabId = toTabId;
				toTab.sections.push(section);
				dirty.value = true;
			}
		}
	}
	
	// 移动列到其他分组
	function moveColumn(columnId, fromSectionId, toSectionId, fromTabId, toTabId) {
		const fromTab = layout.value.tabs.find(t => t.id === fromTabId);
		const toTab = layout.value.tabs.find(t => t.id === toTabId);
		
		if (fromTab && toTab) {
			const fromSection = fromTab.sections.find(s => s.id === fromSectionId);
			const toSection = toTab.sections.find(s => s.id === toSectionId);
			
			if (fromSection && toSection) {
				const columnIndex = fromSection.columns.findIndex(c => c.id === columnId);
				if (columnIndex > -1) {
					const column = fromSection.columns.splice(columnIndex, 1)[0];
					column.sectionId = toSectionId;
					column.tabId = toTabId;
					toSection.columns.push(column);
					dirty.value = true;
				}
			}
		}
	}
	
	function addPropertyToColumn(columnId, fieldType) {
		const key = `field_${Date.now()}`;
		const newProperty = {
			key,
			type: fieldType,
			title: "新字段",
			description: "",
			required: false,
			default: "",
			columnId: columnId
		};
		
		// 为textarea类型设置默认rows
		if (fieldType === "textarea") {
			newProperty.format = "textarea";
			newProperty.rows = 3;
		}
		
		// 检查是否已经存在相同的字段（防止重复添加）
		const existingProperty = properties.value.find(p => 
			p.type === fieldType && p.title === "新属性" && p.columnId === columnId
		);
		if (existingProperty) {
			return;
		}
		
		properties.value.push(newProperty);
		
		// 添加到指定列
		const currentTab = getCurrentTab();
		if (currentTab) {
			for (const section of currentTab.sections) {
				for (const column of section.columns) {
					if (column.id === columnId) {
						column.fields.push(key);
						break;
					}
				}
			}
		}
		
		updateSchema();
		selectedField.value = key;
		dirty.value = true;
	}
	
	function addPropertyToSection(sectionId, fieldType) {
		const key = `field_${Date.now()}`;
		const newProperty = {
			key,
			type: fieldType,
			title: "新字段",
			description: "",
			required: false,
			default: "",
			sectionId: sectionId
		};
		
		// 检查是否已经存在相同的字段（防止重复添加）
		const existingProperty = properties.value.find(p => 
			p.type === fieldType && p.title === "新属性" && p.sectionId === sectionId
		);
		if (existingProperty) {
			return;
		}
		
		properties.value.push(newProperty);
		
		// 添加到指定分组的第一个列
		const currentTab = getCurrentTab();
		if (currentTab) {
			for (const section of currentTab.sections) {
				if (section.id === sectionId && section.columns.length > 0) {
					// 找到第一个空的列，或者第一个列
					let targetColumn = section.columns[0];
					for (const column of section.columns) {
						if (column.fields.length === 0) {
							targetColumn = column;
							break;
						}
					}
					targetColumn.fields.push(key);
					break;
				}
			}
		}
		
		updateSchema();
		selectedField.value = key;
		dirty.value = true;
	}
	
	// 标记数据已更改
	function markDirty() {
		dirty.value = true;
		updateSchema();
	}
	
	// 添加字段到指定标签页
	function addPropertyToTab(tabId, fieldType) {
		const key = `field_${Date.now()}`;
		const newProperty = {
			key,
			type: fieldType,
			title: "新字段",
			description: "",
			required: false,
			default: "",
			tabId: tabId
		};
		
		// 检查是否已经存在相同的字段（防止重复添加）
		const existingProperty = properties.value.find(p => 
			p.type === fieldType && p.title === "新属性" && p.tabId === tabId
		);
		if (existingProperty) {
			return;
		}
		
		properties.value.push(newProperty);
		
		// 添加到指定标签页的第一个分组的第一个列
		const targetTab = layout.value.tabs.find(t => t.id === tabId);
		if (targetTab && targetTab.sections.length > 0) {
			const firstSection = targetTab.sections[0];
			if (firstSection.columns.length > 0) {
				const firstColumn = firstSection.columns[0];
				firstColumn.fields.push(key);
			}
		}
		
		updateSchema();
		selectedField.value = key;
		dirty.value = true;
	}

	// 更新allOf字段
	function updateAllOfSchema(allOfData) {
		if (allOfData && Array.isArray(allOfData) && allOfData.length > 0) {
			schema.value.allOf = allOfData;
		} else {
			delete schema.value.allOf;
		}
		dirty.value = true;
	}

	// 获取当前Schema（用于allOf编辑）
	function getCurrentSchema() {
		return schema.value;
	}

	return {
		// State
		schema,
		properties,
		selectedField,
		preview,
		readOnly,
		dirty,
		layout,
		
		// Getters
		notUsingInput,
		
		// Actions
		addProperty,
		removeProperty,
		updateProperty,
		updateFieldKey,
		updateSchema,
		togglePreview,
		saveSchema,
		loadSchema,
		setSelectedField,
		addTab,
		removeTab,
		activateTab,
		updateTabLabel,
		updateSectionLabel,
		updateColumnLabel,
		addSection,
		removeSection,
		getCurrentTab,
		addColumn,
		removeColumn,
		addPropertyToColumn,
		addPropertyToSection,
		addPropertyToTab,
		markDirty,
		moveSection,
		moveColumn,
		updateAllOfSchema,
		getCurrentSchema
	};
});