<template>
	<div class="schema-sidebar">
		<!-- 标签页导航 -->
		<div class="sidebar-tabs">
			<button 
				class="tab-btn" 
				:class="{ active: activeTab === 'field-types' }"
				@click="activeTab = 'field-types'"
			>
				{{ t('Field Types') }}
			</button>
			<button 
				class="tab-btn" 
				:class="{ active: activeTab === 'properties' }"
				@click="activeTab = 'properties'"
			>
				{{ t('Properties') }}
			</button>
			<button 
				class="tab-btn" 
				:class="{ active: activeTab === 'allof' }"
				@click="activeTab = 'allof'"
			>
				{{ t('allOf Conditions') }}
			</button>
		</div>

		<!-- 标签页内容 -->
		<div class="tab-content">
			<!-- 字段类型标签页 -->
			<div v-if="activeTab === 'field-types'" class="field-types-tab">
				<div class="sidebar-section">
					<h4>{{ t('Basic Fields') }}</h4>
					<div class="field-type-list">
						<div 
							v-for="fieldType in basicFieldTypes" 
							:key="fieldType.type"
							class="field-type-item"
							:class="{ 'selected': selectedFieldType === fieldType.type }"
							:draggable="true"
							@dragstart="onDragStart($event, fieldType)"
							@dragend="onDragEnd"
							@click="selectFieldType(fieldType.type)"
							@dblclick="addFieldToCurrentColumn(fieldType.type)"
							:title="t(fieldType.name)"
						>
							<div class="field-type-icon">{{ fieldType.icon }}</div>
							<div class="field-type-content">
								<div class="field-type-name">{{ t(fieldType.name) }}</div>
								<div class="field-type-type">{{ fieldType.type }}</div>
							</div>
						</div>
					</div>
				</div>

				<div class="sidebar-section">
					<h4>{{ t('Advanced Fields') }}</h4>
					<div class="field-type-list">
						<div 
							v-for="fieldType in advancedFieldTypes" 
							:key="fieldType.type"
							class="field-type-item"
							:class="{ 'selected': selectedFieldType === fieldType.type }"
							:draggable="true"
							@dragstart="onDragStart($event, fieldType)"
							@dragend="onDragEnd"
							@click="selectFieldType(fieldType.type)"
							@dblclick="addFieldToCurrentColumn(fieldType.type)"
							:title="t(fieldType.name)"
						>
							<div class="field-type-icon">{{ fieldType.icon }}</div>
							<div class="field-type-content">
								<div class="field-type-name">{{ t(fieldType.name) }}</div>
								<div class="field-type-type">{{ fieldType.type }}</div>
							</div>
						</div>
					</div>
				</div>
			</div>

			<!-- 属性设置标签页 -->
			<div v-if="activeTab === 'properties'" class="properties-tab">
				<div v-if="store.selectedField" class="field-properties">
					<h4>{{ t('Field Properties') }}</h4>
					<div class="property-group">
						<label>{{ t('Field Name') }}</label>
						<input 
							type="text" 
							:value="getFieldById(store.selectedField)?.title || ''"
							@input="updateFieldProperty('title', $event.target.value)"
							placeholder=""
						/>
					</div>
					
					<div class="property-group">
						<label>{{ t('Field Type') }}</label>
						<select 
							:value="getFieldById(store.selectedField)?.type || 'string'"
							@change="updateFieldProperty('type', $event.target.value)"
							class="field-type-select"
						>
							<option value="string">{{ t('String') }} - string</option>
							<option value="number">{{ t('Number') }} - number</option>
							<option value="integer">{{ t('Integer') }} - integer</option>
							<option value="boolean">{{ t('Boolean') }} - boolean</option>
							<option value="array">{{ t('Array') }} - array</option>
							<option value="object">{{ t('Object') }} - object</option>
							<option value="text">{{ t('Long Text') }} - text</option>
							<option value="password">{{ t('Password') }} - password</option>
							<option value="select">{{ t('Select') }} - select</option>
							<option value="radio">{{ t('Radio') }} - radio</option>
							<option value="checkbox">{{ t('Checkbox') }} - checkbox</option>
							<option value="textarea">{{ t('Textarea') }} - textarea</option>
							<option value="email">{{ t('Email') }} - email</option>
							<option value="url">{{ t('URL') }} - url</option>
							<option value="date">{{ t('Date') }} - date</option>
							<option value="datetime">{{ t('Datetime') }} - datetime</option>
							<option value="time">{{ t('Time') }} - time</option>
							<option value="file">{{ t('File') }} - file</option>
							<option value="image">{{ t('Image') }} - image</option>
							<option value="color">{{ t('Color') }} - color</option>
							<option value="range">{{ t('Range') }} - range</option>
							<option value="tel">{{ t('Tel') }} - tel</option>
							<option value="search">{{ t('Search') }} - search</option>
							<option value="hidden">{{ t('Hidden') }} - hidden</option>
							<option value="info">{{ t('Info') }} - info</option>
						</select>
					</div>
					
					<div class="property-group">
						<label>{{ t('Field ID') }}</label>
						<input 
							type="text" 
							:value="store.selectedField"
							@input="updateFieldKey"
							placeholder=""
						/>
					</div>
					
					<div class="property-group">
						<label>{{ t('Field Description') }}</label>
						<textarea 
							:value="getFieldById(store.selectedField)?.description || ''"
							@input="updateFieldProperty('description', $event.target.value)"
							placeholder=""
							rows="3"
						></textarea>
					</div>
					
					<div class="property-group">
						<label>{{ t('Default Value') }}</label>
						<input 
							type="text" 
							:value="getFieldById(store.selectedField)?.default || ''"
							@input="updateFieldProperty('default', $event.target.value)"
							placeholder=""
						/>
					</div>
					
					<!-- 枚举值设置 -->
					<div class="property-group">
						<label>{{ t('Enum Values (enum)') }}</label>
						<textarea 
							:value="getEnumValuesText()"
							@blur="updateEnumValues($event.target.value)"
							rows="4"
							class="enum-textarea"
						></textarea>
						<div class="form-text">{{ t('Enter one enum value per line') }}</div>
					</div>
					
					<div v-if="store.selectedField && hasEnumValues()" class="property-group">
						<label>{{ t('Enum Display Names (enumNames)') }}</label>
						<textarea 
							:value="getEnumNamesText()"
							@blur="updateEnumNames($event.target.value)"
							rows="4"
							class="enum-textarea"
						></textarea>
						<div class="form-text">{{ t('Enter one display name per line, mapping to enum values (optional)') }}</div>
					</div>
					
					<div class="property-group">
						<label>{{ t('Condition Expression') }}</label>
						<textarea 
							:value="getConditionText()"
							@blur="updateCondition($event.target.value)"
							placeholder=""
							rows="3"
							class="condition-textarea"
						></textarea>
						<div class="form-text">
							<div class="help-title">{{ t('Supports JSON condition expressions for controlling field display and hiding, example:') }}</div>
							<div class="help-section">
								<code>{"field_name": "field_value"}</code>
							</div>
						</div>
					</div>
					
					<div class="property-group">
						<label>
							<input 
								type="checkbox" 
								:checked="getFieldById(store.selectedField)?.required || false"
								@change="updateFieldProperty('required', $event.target.checked)"
							/>
								{{ t('Required Field') }}
						</label>
					</div>
					
					<!-- 数组和对象类型的内部结构编辑 -->
					<div v-if="store.selectedField && (getFieldById(store.selectedField)?.type === 'array' || getFieldById(store.selectedField)?.type === 'object')" class="structure-properties">
						<h5><strong>{{ t('Internal Structure Definition') }}</strong></h5>
						
						<!-- 数组类型的items定义 -->
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'array'" class="property-group">
							<label>{{ t('Array Item Type') }} (items)</label>
							<select 
								:value="getArrayItemType()"
								@change="updateArrayItemType($event.target.value)"
								class="format-select"
							>
								<option value="string">{{ t('String') }}</option>
								<option value="number">{{ t('Number') }}</option>
								<option value="boolean">{{ t('Boolean') }}</option>
								<option value="object">{{ t('Object') }}</option>
							</select>
						</div>
						
						<!-- 对象类型的properties定义 -->
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'object'" class="property-group">
							<label>{{ t('Object Property Definition') }}</label>
							<button 
								type="button" 
								class="btn btn-sm btn-outline-primary"
								@click="addObjectProperty()"
							>
								<i class="fa fa-plus"></i> {{ t('Add Property') }}
							</button>
						</div>
						
						<!-- 数组项为对象时的属性定义 -->
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'array' && getArrayItemType() === 'object'" class="array-object-properties">
							<div class="property-group">
								<label>{{ t('Object Property Definition') }}</label>
								<button 
									type="button" 
									class="btn btn-sm btn-outline-primary"
									@click="addArrayObjectProperty()"
								>
									<i class="fa fa-plus"></i> {{ t('Add Property') }}
								</button>
							</div>
							
							<div v-for="(prop, index) in getArrayObjectProperties()" :key="index" class="object-property-item">
								<div class="property-header">
									<input 
										type="text" 
										:value="prop.name"
										@input="updateArrayObjectPropertyName(index, $event.target.value)"
										:placeholder="t('Property Name')"
										class="property-name-input"
									/>
									<select 
										:value="prop.type"
										@change="updateArrayObjectPropertyType(index, $event.target.value)"
										class="property-type-select"
									>
										<option value="string">{{ t('String') }}</option>
										<option value="number">{{ t('Number') }}</option>
										<option value="boolean">{{ t('Boolean') }}</option>
										<option value="select">{{ t('Select') }}</option>
									</select>
									<button 
										type="button" 
										class="btn btn-xs btn-outline-danger"
										@click="removeArrayObjectProperty(index)"
									>
										<i class="fa fa-trash"></i>
									</button>
								</div>
								
								<!-- 选择器类型的枚举设置 -->
								<div v-if="prop.type === 'select'" class="property-enum-settings">
									<textarea 
										:value="getArrayObjectPropertyEnumText(index)"
										@blur="updateArrayObjectPropertyEnum(index, $event.target.value)"
										:placeholder="t('Enter one option per line')"
										rows="3"
										class="enum-textarea"
									></textarea>
								</div>
							</div>
						</div>
					</div>
					
					<!-- 字符串类型、选择器类型、单选框和复选框的高级属性 -->
					<div v-if="store.selectedField && (getFieldById(store.selectedField)?.type === 'string' || getFieldById(store.selectedField)?.type === 'select' || getFieldById(store.selectedField)?.type === 'radio' || getFieldById(store.selectedField)?.type === 'checkbox')" class="advanced-properties">
						<h5><strong>{{ t('Advanced Properties') }}</strong></h5>
						
						<!-- 字符串类型的格式设置 -->
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'string'" class="property-group">
							<label>{{ t('Format') }} (format)</label>
							<select 
								:value="getFieldById(store.selectedField)?.format || ''"
								@change="updateFieldProperty('format', $event.target.value)"
								class="format-select"
							>
								<option value="">{{ t('None') }}</option>
								<option value="textarea">{{ t('Textarea') }}</option>
								<option value="email">{{ t('Email') }}</option>
								<option value="url">{{ t('URL') }}</option>
								<option value="date">{{ t('Date') }}</option>
								<option value="datetime">{{ t('Datetime') }}</option>
								<option value="time">{{ t('Time') }}</option>
								<option value="password">{{ t('Password') }}</option>
								<option value="color">{{ t('Color') }}</option>
								<option value="file">{{ t('File') }}</option>
								<option value="image">{{ t('Image') }}</option>
								<option value="tel">{{ t('Tel') }}</option>
								<option value="search">{{ t('Search') }}</option>
								<option value="info">{{ t('Info') }}</option>
							</select>
						</div>
						
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.format === 'textarea'" class="property-group">
							<label>{{ t('Rows') }} (rows)</label>
							<input 
								type="number" 
								:value="getFieldById(store.selectedField)?.rows || 3"
								@input="updateFieldProperty('rows', parseInt($event.target.value) || 3)"
								min="1"
								max="20"
								class="rows-input"
							/>
						</div>
						
						<div class="property-group">
							<label>{{ t('Minimum Length') }} (minLength)</label>
							<input 
								type="number" 
								:value="getFieldById(store.selectedField)?.minLength || ''"
								@input="updateFieldProperty('minLength', $event.target.value ? parseInt($event.target.value) : undefined)"
								min="0"
								:placeholder="t('No limit')"
								class="length-input"
							/>
						</div>
						
						<div class="property-group">
							<label>{{ t('Maximum Length') }} (maxLength)</label>
							<input 
								type="number" 
								:value="getFieldById(store.selectedField)?.maxLength || ''"
								@input="updateFieldProperty('maxLength', $event.target.value ? parseInt($event.target.value) : undefined)"
								min="1"
								:placeholder="t('No limit')"
								class="length-input"
							/>
						</div>
						
						<div class="property-group">
							<label>{{ t('Regular Expression') }} (pattern)</label>
							<input 
								type="text" 
								:value="getFieldById(store.selectedField)?.pattern || ''"
								@input="updateFieldProperty('pattern', $event.target.value || undefined)"
								:placeholder="t('e.g., ^[a-zA-Z]+$')"
								class="pattern-input"
							/>
						</div>
						
						<div class="property-group">
							<label>{{ t('Placeholder') }} (placeholder)</label>
							<input 
								type="text" 
								:value="getFieldById(store.selectedField)?.placeholder || ''"
								@input="updateFieldProperty('placeholder', $event.target.value || undefined)"
								class="pattern-input"
							/>
						</div>
						
						<!-- Select类型特有设置 -->
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'select'" class="property-group">
							<label>{{ t('Multiple Selection') }} (multiple)</label>
							<label class="checkbox-label">
								<input 
									type="checkbox" 
									:checked="getFieldById(store.selectedField)?.multiple || false"
									@change="updateFieldProperty('multiple', $event.target.checked)"
								/>
									{{ t('Allow multiple selection') }}
							</label>
							<div class="form-text">{{ t('Check to allow users to select multiple options') }}</div>
						</div>
						
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'select'" class="property-group">
							<label>{{ t('Placeholder Text') }} (placeholder)</label>
							<input 
								type="text" 
								:value="getFieldById(store.selectedField)?.placeholder || ''"
								@input="updateFieldProperty('placeholder', $event.target.value || undefined)"
								:placeholder="t('e.g., Please select...')"
								class="pattern-input"
							/>
							<div class="form-text">{{ t('Hint text for the dropdown') }}</div>
						</div>
						
						<!-- Radio和Checkbox类型特有设置 -->
						<div v-if="store.selectedField && (getFieldById(store.selectedField)?.type === 'radio' || getFieldById(store.selectedField)?.type === 'checkbox')" class="property-group">
							<label>{{ t('Layout') }} (layout)</label>
							<select 
								:value="getFieldById(store.selectedField)?.layout || 'horizontal'"
								@change="updateFieldProperty('layout', $event.target.value)"
								class="format-select"
							>
								<option value="horizontal">{{ t('Horizontal') }}</option>
								<option value="vertical">{{ t('Vertical') }}</option>
							</select>
							<div class="form-text">{{ t('Arrangement of options') }}</div>
						</div>
						
						<div v-if="store.selectedField && getFieldById(store.selectedField)?.type === 'checkbox'" class="property-group">
							<label>{{ t('Multiple Selection') }} (multiple)</label>
							<label class="checkbox-label">
								<input 
									type="checkbox" 
									:checked="getFieldById(store.selectedField)?.multiple || false"
									@change="updateFieldProperty('multiple', $event.target.checked)"
								/>
									{{ t('Allow multiple selection') }}
							</label>
							<div class="form-text">{{ t('Check to allow users to select multiple options') }}</div>
						</div>
						
					</div>
					

				</div>
				
				<div v-else class="no-field-selected">
					<p>{{ t('Please select a field to edit properties') }}</p>
				</div>
			</div>

			<!-- allOf条件标签页 -->
			<div v-if="activeTab === 'allof'" class="allof-tab">
				<div class="allof-settings">
					<h4>{{ t('allOf Conditions') }}</h4>
					<p class="allof-description">
						{{ t('allOf conditions are used to set field conditions for display, directly edit the JSON condition.') }}
					</p>
					
					<div class="allof-content">
						<div class="property-group">
							<label>{{ t('allOf Conditions') }} (JSON format)</label>
							<textarea 
								:value="allOfContent"
								@input="updateAllOfContent"
								rows="15"
								class="allof-textarea"
							></textarea>
							<div class="form-text">
								{{ t('Example format:') }}<br>
								[{ "if": { "properties": { "field": { "const": "value" } } }, "then": { "properties": { "newField": { "type": "string" } } } }]
							</div>
						</div>
						

					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup>
import { useSchemaStore } from "../store";
import { ref, watch, onMounted, onUnmounted } from "vue";
import { useMessage } from 'naive-ui';
import { t } from '@/shared/i18n';

const store = useSchemaStore();
const message = useMessage();

// 标签页状态
const activeTab = ref('field-types');
const selectedFieldType = ref(null);

// allOf相关状态
const allOfContent = ref('');
const allOfError = ref('');

// 字段类型数据（名称使用自然英文，通过 t() 翻译展示）
const basicFieldTypes = [
	{ type: "string", name: "String", icon: "📝" },
	{ type: "number", name: "Number", icon: "🔢" },
	{ type: "integer", name: "Integer", icon: "🔢" },
	{ type: "boolean", name: "Boolean", icon: "✅" },
	{ type: "array", name: "Array", icon: "📋" },
	{ type: "object", name: "Object", icon: "📦" },
	{ type: "text", name: "Long Text", icon: "📄" },
	{ type: "password", name: "Password", icon: "🔒" },
	{ type: "select", name: "Select", icon: "📋" },
	{ type: "radio", name: "Radio", icon: "🔘" },
	{ type: "checkbox", name: "Checkbox", icon: "☑️" },
	{ type: "textarea", name: "Textarea", icon: "📝" },
	{ type: "info", name: "Info", icon: "ℹ️" }
];

const advancedFieldTypes = [
	{ type: "email", name: "Email", icon: "📧" },
	{ type: "url", name: "URL", icon: "🔗" },
	{ type: "date", name: "Date", icon: "📅" },
	{ type: "datetime", name: "Datetime", icon: "⏰" },
	{ type: "time", name: "Time", icon: "🕐" },
	{ type: "file", name: "File", icon: "📁" },
	{ type: "image", name: "Image", icon: "🖼️" },
	{ type: "color", name: "Color", icon: "🎨" },
	{ type: "range", name: "Range", icon: "📊" },
	{ type: "tel", name: "Tel", icon: "📞" },
	{ type: "search", name: "Search", icon: "🔍" },
	{ type: "hidden", name: "Hidden", icon: "👻" }
];

// 监听选中字段变化，自动切换到属性设置标签页
watch(() => store.selectedField, (newField) => {
	if (newField) {
		try {
			activeTab.value = 'properties';
		} catch (error) {
			console.error('Error switching to properties tab:', error);
		}
	}
});

// 监听store中Schema的变化，自动加载allOf内容
watch(() => store.schema, (newSchema) => {
	if (newSchema && newSchema.allOf) {
		try {
			allOfContent.value = JSON.stringify(newSchema.allOf, null, 2);
			allOfError.value = '';
		} catch (error) {
			console.error('Error processing schema allOf:', error);
		}
	}
}, { immediate: true });

// 监听activeTab变化，当切换到allOf标签页时自动加载内容
watch(() => activeTab.value, (newTab) => {
	if (newTab === 'allof') {
		// 从store中获取现有的allOf设置
		if (store.schema && store.schema.allOf) {
			try {
				allOfContent.value = JSON.stringify(store.schema.allOf, null, 2);
				allOfError.value = '';
			} catch (error) {
				console.error('Error processing schema allOf in tab change:', error);
			}
		}
	}
});

// allOf内容更新处理
function updateAllOfContent(event) {
	allOfContent.value = event.target.value;
	
	// 如果内容为空或无效JSON，删除allOf字段
	if (!allOfContent.value.trim()) {
		if (store.updateAllOfSchema) {
			try {
				store.updateAllOfSchema(null);
			} catch (error) {
				console.error('Error updating allOf schema:', error);
			}
		}
		return;
	}
	
	try {
		const parsed = JSON.parse(allOfContent.value);
		if (store.updateAllOfSchema) {
			store.updateAllOfSchema(parsed);
		}
		allOfError.value = '';
	} catch (e) {
		// JSON格式错误时不更新store，但不清除内容
		allOfError.value = `JSON格式错误: ${e.message}`;
	}
}


// 选择字段类型
function selectFieldType(type) {
	if (type) {
		selectedFieldType.value = type;
	}
}

// 添加字段到当前列
function addFieldToCurrentColumn(fieldType) {
	// 这里需要获取当前活动的列，暂时使用默认逻辑
	if (store.addProperty) {
		try {
			store.addProperty(fieldType);
		} catch (error) {
			console.error('Error adding field:', error);
		}
	}
}

// 获取字段信息
function getFieldById(fieldId) {
	if (!store.schema || !store.schema.properties) {
		return null;
	}
	return store.schema.properties[fieldId];
}

// 更新字段属性
function updateFieldProperty(property, value) {
	if (store.selectedField && store.updateProperty) {
		try {
			store.updateProperty(store.selectedField, { [property]: value });
		} catch (error) {
			console.error('Error updating field property:', error);
		}
	}
}

// 更新字段ID
function updateFieldKey(event) {
	if (store.updateFieldKey) {
		try {
			store.updateFieldKey(event);
		} catch (error) {
			console.error('Error updating field key:', error);
		}
	}
}

// 更新枚举值
function updateEnumValues(value) {
	if (store.selectedField && store.updateProperty) {
		try {
			const enumValues = value.split('\n').filter(v => v.trim()).map(v => v.trim());
			store.updateProperty(store.selectedField, { enum: enumValues.length > 0 ? enumValues : undefined });
		} catch (error) {
			console.error('Error updating enum values:', error);
		}
	}
}

// 更新枚举显示名称
function updateEnumNames(value) {
	if (store.selectedField && store.updateProperty) {
		try {
			const enumNames = value.split('\n').filter(v => v.trim()).map(v => v.trim());
			store.updateProperty(store.selectedField, { enumNames: enumNames.length > 0 ? enumNames : undefined });
		} catch (error) {
			console.error('Error updating enum names:', error);
		}
	}
}

// 获取枚举值文本
function getEnumValuesText() {
	if (!store.selectedField) return '';
	
	const field = getFieldById(store.selectedField);
	if (field && field.enum && Array.isArray(field.enum)) {
		return field.enum.join('\n');
	}
	return '';
}

// 获取枚举显示名称文本
function getEnumNamesText() {
	if (!store.selectedField) return '';
	
	const field = getFieldById(store.selectedField);
	if (field && field.enumNames && Array.isArray(field.enumNames)) {
		return field.enumNames.join('\n');
	}
	return '';
}

// 判断是否有枚举值
function hasEnumValues() {
	if (!store.selectedField) return false;
	
	const field = getFieldById(store.selectedField);
	return field && field.enum && Array.isArray(field.enum) && field.enum.length > 0;
}

// 获取条件表达式文本
function getConditionText() {
	if (!store.selectedField) return '';
	
	const field = getFieldById(store.selectedField);
	if (field && field.condition) {
		try {
			// 如果是对象，转换为JSON字符串
			if (typeof field.condition === 'object') {
				return JSON.stringify(field.condition, null, 2);
			}
			// 如果是字符串，尝试解析为JSON再格式化
			if (typeof field.condition === 'string') {
				const parsed = JSON.parse(field.condition);
				return JSON.stringify(parsed, null, 2);
			}
			return String(field.condition);
		} catch (error) {
			// 如果解析失败，直接返回原值
			return String(field.condition);
		}
	}
	return '';
}

// 更新条件表达式
function updateCondition(value) {
	if (store.selectedField && store.updateProperty) {
		try {
			// 如果输入为空，删除condition属性
			if (!value.trim()) {
				store.updateProperty(store.selectedField, { condition: undefined });
				return;
			}
			
			// 尝试解析JSON
			const parsed = JSON.parse(value.trim());
			store.updateProperty(store.selectedField, { condition: parsed });
		} catch (error) {
			console.error('Error updating condition:', error);
			// 如果JSON解析失败，可以显示错误提示或保持原值
			// 这里可以选择显示错误信息给用户
		}
	}
}

// 拖拽相关函数（保留原有功能）
function onDragStart(event, type) {
	if (event && type && type.type) {
		try {
			event.dataTransfer.setData('text/plain', type.type);
			event.dataTransfer.setData('source', 'toolbox');
		} catch (error) {
			console.error('Error setting drag data:', error);
		}
	}
}

function onDragEnd(event) {
	// 拖拽结束处理
	try {
		// 可以在这里添加拖拽结束后的清理逻辑
	} catch (error) {
		console.error('Error in drag end:', error);
	}
}

// 数组和对象结构相关函数
function getArrayItemType() {
	if (!store.selectedField) return 'string';
	
	const field = getFieldById(store.selectedField);
	if (field?.items?.type) {
		return field.items.type;
	}
	return 'string';
}

function updateArrayItemType(type) {
	if (store.selectedField && store.updateProperty) {
		try {
			// 更新数组项类型
			const field = getFieldById(store.selectedField);
			const updatedField = { ...field };
			
			if (type === 'object') {
				updatedField.items = {
					type: 'object',
					properties: {}
				};
			} else {
				updatedField.items = {
					type: type
				};
			}
			
			store.updateProperty(store.selectedField, updatedField);
		} catch (error) {
			console.error('Error updating array item type:', error);
		}
	}
}

function getArrayObjectProperties() {
	if (!store.selectedField) return [];
	
	const field = getFieldById(store.selectedField);
	if (field?.items?.properties) {
		return Object.entries(field.items.properties).map(([name, prop]) => ({
			name,
			type: prop.type || 'string',
			title: prop.title || name,
			enum: prop.enum || []
		}));
	}
	return [];
}

function addArrayObjectProperty() {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const updatedField = { ...field };
			
			if (!updatedField.items) {
				updatedField.items = { type: 'object', properties: {} };
			}
			
			if (!updatedField.items.properties) {
				updatedField.items.properties = {};
			}
			
			const newPropName = `property_${Date.now()}`;
			updatedField.items.properties[newPropName] = {
				type: 'string',
				title: '新属性'
			};
			
			store.updateProperty(store.selectedField, updatedField);
		} catch (error) {
			console.error('Error adding array object property:', error);
		}
	}
}

function updateArrayObjectPropertyName(index, newName) {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const properties = getArrayObjectProperties();
			const oldName = properties[index]?.name;
			
			if (oldName && newName && oldName !== newName) {
				const updatedField = { ...field };
				const oldProp = updatedField.items.properties[oldName];
				
				// 删除旧属性，添加新属性
				delete updatedField.items.properties[oldName];
				updatedField.items.properties[newName] = oldProp;
				
				store.updateProperty(store.selectedField, updatedField);
			}
		} catch (error) {
			console.error('Error updating array object property name:', error);
		}
	}
}

function updateArrayObjectPropertyType(index, type) {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const properties = getArrayObjectProperties();
			const propName = properties[index]?.name;
			
			if (propName) {
				const updatedField = { ...field };
				updatedField.items.properties[propName].type = type;
				
				// 如果是选择器类型，初始化枚举
				if (type === 'select') {
					updatedField.items.properties[propName].enum = [];
				}
				
				store.updateProperty(store.selectedField, updatedField);
			}
		} catch (error) {
			console.error('Error updating array object property type:', error);
		}
	}
}

function removeArrayObjectProperty(index) {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const properties = getArrayObjectProperties();
			const propName = properties[index]?.name;
			
			if (propName) {
				const updatedField = { ...field };
				delete updatedField.items.properties[propName];
				
				store.updateProperty(store.selectedField, updatedField);
			}
		} catch (error) {
			console.error('Error removing array object property:', error);
		}
	}
}

function getArrayObjectPropertyEnumText(index) {
	const properties = getArrayObjectProperties();
	const prop = properties[index];
	if (prop?.enum && Array.isArray(prop.enum)) {
		return prop.enum.join('\n');
	}
	return '';
}

function updateArrayObjectPropertyEnum(index, value) {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const properties = getArrayObjectProperties();
			const propName = properties[index]?.name;
			
			if (propName) {
				const updatedField = { ...field };
				const enumValues = value.split('\n').filter(v => v.trim()).map(v => v.trim());
				
				updatedField.items.properties[propName].enum = enumValues.length > 0 ? enumValues : undefined;
				
				store.updateProperty(store.selectedField, updatedField);
			}
		} catch (error) {
			console.error('Error updating array object property enum:', error);
		}
	}
}

function addObjectProperty() {
	if (store.selectedField && store.updateProperty) {
		try {
			const field = getFieldById(store.selectedField);
			const updatedField = { ...field };
			
			if (!updatedField.properties) {
				updatedField.properties = {};
			}
			
			const newPropName = `property_${Date.now()}`;
			updatedField.properties[newPropName] = {
				type: 'string',
				title: '新属性'
			};
			
			store.updateProperty(store.selectedField, updatedField);
		} catch (error) {
			console.error('Error adding object property:', error);
		}
	}
}

// 监听错误事件
function handleError(event) {
	message.error(event.detail.message);
}

onMounted(() => {
	document.addEventListener('schema-builder-error', handleError);
});

onUnmounted(() => {
	document.removeEventListener('schema-builder-error', handleError);
});
</script>

<style lang="scss" scoped>
.schema-sidebar {
	height: 100%;
	display: flex;
	flex-direction: column;
	
	.sidebar-tabs {
		display: flex;
		border-bottom: 1px solid var(--border-color);
		background-color: var(--bg-light-gray);
		
		.tab-btn {
			flex: 1;
			padding: 0.75rem 1rem;
			border: none;
			background: none;
			color: var(--text-muted);
			font-size: var(--text-sm);
			font-weight: 500;
			cursor: pointer;
			transition: all 0.2s;
			border-bottom: 2px solid transparent;
			
			&:hover {
				color: var(--text-color);
				background-color: var(--bg-color);
			}
			
			&.active {
				color: var(--primary-color);
				border-bottom-color: var(--primary-color);
				background-color: var(--bg-color);
			}
		}
	}
	
	.tab-content {
		flex: 1;
		overflow-y: auto;
		padding: 1rem;
		
		// 字段类型标签页样式
		.field-types-tab {
			.sidebar-section {
				margin-bottom: 1.5rem;
				
				h4 {
					margin: 0 0 1rem 0;
					color: var(--heading-color);
					font-size: var(--text-md);
					font-weight: 600;
				}
				
				.field-type-list {
					display: grid;
					grid-template-columns: 1fr 1fr;
					gap: 0.5rem;
					
					.field-type-item {
						display: flex;
						align-items: center;
						padding: 0.5rem;
						background-color: var(--bg-light-gray);
						border-radius: var(--border-radius);
						cursor: pointer;
						border: 1px solid transparent;
						transition: all 0.2s;
						
						&:hover {
							border-color: var(--border-primary);
							background-color: var(--fg-color);
						}
						
						&.selected {
							border-color: var(--primary-color);
							background-color: var(--primary-light);
						}
						
						.field-type-icon {
							font-size: 1.1rem;
							margin-right: 0.5rem;
							flex-shrink: 0;
						}
						
						.field-type-content {
							flex: 1;
							min-width: 0;
							
							.field-type-name {
								font-size: 0.75rem;
								font-weight: 500;
								color: var(--heading-color);
								line-height: 1.2;
								margin-bottom: 0.15rem;
							}
							
							.field-type-type {
								font-size: 0.7rem;
								color: var(--text-muted);
								font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
								line-height: 1.2;
							}
						}
						
						// 拖拽状态样式
						&:active {
							cursor: grabbing;
						}
					}
				}
			}
		}
		
		// 属性设置标签页样式
		.properties-tab {
			.field-properties {
				h4 {
					margin: 0 0 1rem 0;
					color: var(--heading-color);
					font-size: var(--text-md);
					font-weight: 600;
				}
				
				.property-group {
					margin-bottom: 1rem;
					
					label {
						display: block;
						margin-bottom: 0.5rem;
						font-weight: 500;
						color: var(--heading-color);
					}
					
					input:not([type="checkbox"]), textarea, select {
						width: 100%;
						padding: 0.5rem;
						border: 1px solid var(--border-color);
						border-radius: var(--border-radius);
						font-size: var(--text-sm);
						
						&:focus {
							outline: none;
							border-color: var(--primary-color);
						}
					}
					
					.field-type-select {
						background-color: white;
						cursor: pointer;
						font-size: var(--text-sm);
						
						&:hover {
							border-color: var(--border-primary);
						}
						
						option {
							padding: 0.25rem 0.5rem;
							font-size: var(--text-sm);
						}
					}
					
					// 高级属性样式
					.advanced-properties {
						margin-top: 1.5rem;
						padding-top: 1rem;
						border-top: 1px solid var(--border-color);
						
						h5 {
							margin: 0 0 1rem 0;
							color: var(--heading-color);
							font-size: var(--text-sm);
							font-weight: 600;
						}
						
						.format-select {
							background-color: white;
							cursor: pointer;
							
							&:hover {
								border-color: var(--border-primary);
							}
						}
						
						.rows-input, .length-input {
							width: 100%;
							padding: 0.5rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
							
							&:focus {
								outline: none;
								border-color: var(--primary-color);
							}
						}
						
						.pattern-input {
							font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
							font-size: 0.8rem;
						}
						
						.enum-textarea {
							width: 100%;
							padding: 0.5rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
							font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
							resize: vertical;
							line-height: 1.4;
							
							&:focus {
								outline: none;
								border-color: var(--primary-color);
							}
						}
						
						.checkbox-label {
							display: flex !important;
							align-items: center;
							gap: 0.5rem;
							cursor: pointer;
							font-weight: normal;
							margin-bottom: 0.5rem;
							
							input[type="checkbox"] {
								margin: 0;
								width: auto;
								cursor: pointer;
							}
						}
					}
					
					textarea {
						resize: vertical;
						min-height: 80px;
					}
				}
				

			}
			
			.no-field-selected {
				text-align: center;
				padding: 2rem 1rem;
				color: var(--text-muted);
				
				p {
					margin: 0;
					font-size: var(--text-sm);
				}
			}
		}
		
		// allOf条件标签页样式
		.allof-tab {
			.allof-settings {
				h4 {
					margin: 0 0 1rem 0;
					color: var(--heading-color);
					font-size: var(--text-md);
					font-weight: 600;
				}
				
				.allof-description {
					margin: 0 0 1.5rem 0;
					color: var(--text-muted);
					font-size: var(--text-sm);
					line-height: 1.4;
				}
				
				.allof-content {
					.property-group {
						margin-bottom: 1.5rem;
						
						label {
							display: block;
							margin-bottom: 0.5rem;
							font-weight: 500;
							color: var(--heading-color);
						}
						
						.allof-textarea {
							width: 100%;
							padding: 0.75rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
							font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
							resize: vertical;
							line-height: 1.4;
							
							&:focus {
								outline: none;
								border-color: var(--primary-color);
							}
						}
					}
				}
			}
		}
		
		.sidebar-actions {
			h6 {
				margin-bottom: 1rem;
				color: var(--heading-color);
			}
			
			.field-settings {
				.setting-item {
					margin-bottom: 1rem;
					
					label {
						display: block;
						margin-bottom: 0.5rem;
						font-weight: 500;
						color: var(--heading-color);
					}
					
					.form-control {
						width: 100%;
						padding: 0.5rem;
						border: 1px solid var(--border-color);
						border-radius: var(--border-radius);
						font-size: var(--text-sm);
						
						&:focus {
							outline: none;
							border-color: var(--border-primary);
						}
					}
					
					.form-text {
						font-size: var(--text-xs);
						color: var(--text-muted);
						margin-top: 0.25rem;
						display: block;
					}
					
					textarea.form-control {
						resize: vertical;
						min-height: 80px;
					}
				}
			}
		}
		
		// 数组和对象结构编辑样式
		.structure-properties {
			margin-top: 1.5rem;
			padding-top: 1rem;
			border-top: 1px solid var(--border-color);
			
			h5 {
				margin: 0 0 1rem 0;
				color: var(--heading-color);
				font-size: var(--text-sm);
				font-weight: 600;
			}
			
			.array-object-properties {
				margin-top: 1rem;
				
				.object-property-item {
					margin-bottom: 1rem;
					padding: 0.75rem;
					border: 1px solid var(--border-color);
					border-radius: var(--border-radius);
					background-color: var(--bg-light-gray);
					
					.property-header {
						display: flex;
						align-items: center;
						gap: 0.5rem;
						margin-bottom: 0.5rem;
						
						.property-name-input {
							flex: 1;
							padding: 0.25rem 0.5rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
						}
						
						.property-type-select {
							width: 100px;
							padding: 0.25rem 0.5rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
						}
					}
					
					.property-enum-settings {
						margin-top: 0.5rem;
						
						.enum-textarea {
							width: 100%;
							padding: 0.5rem;
							border: 1px solid var(--border-color);
							border-radius: var(--border-radius);
							font-size: var(--text-sm);
							font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
							resize: vertical;
							line-height: 1.4;
							
							&:focus {
								outline: none;
								border-color: var(--primary-color);
							}
						}
					}
				}
			}
		}
	}
}
</style>