<!-- DynamicForm.vue -->
<template>
	<a-card :bordered="false">
		<a-form ref="searchFormRef" name="advanced_search" :model="formState" class="ant-advanced-search-form">
			<a-row :gutter="24">
				<a-col v-for="(field, index) in fields" :key="index" :span="6" v-show="!field.advanced || advanced">
					<a-form-item :label="field.label" :name="field.name">
						<component
							:is="getComponent(field)"
							v-model:value="formState[field.name]"
							:placeholder="field.placeholder"
							:options="field.options"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="6">
					<a-button type="primary" @click="onSearch">查询</a-button>
					<a-button style="margin: 0 8px" @click="reset">重置</a-button>
					<a @click="toggleAdvanced" style="margin-left: 8px">
						{{ advanced ? '收起' : '展开' }}
						<component :is="advanced ? 'up-outlined' : 'down-outlined'" />
					</a>
				</a-col>
			</a-row>
		</a-form>
	</a-card>
</template>

<script setup>
	import { ref, defineProps, defineEmits, onMounted, onUpdated, onUnmounted, watch } from 'vue'

	const props = defineProps({
		fields: {
			type: Array,
			required: true,
			default: () => []
		}
	})

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

	const searchFormRef = ref(null)
	const formState = ref({})
	const advanced = ref(false)

	const reset = () => {
		formState.value = { ...props.modelValue }
		emit('update:modelValue', formState.value)
	}

	const onSearch = () => {
		emit('search', formState.value)
	}

	const toggleAdvanced = () => {
		advanced.value = !advanced.value
	}

	const getComponent = (field) => {
		switch (field.type) {
			case 'input':
				return 'a-input'
			case 'select':
				return 'a-select'
			default:
				return 'a-input'
		}
	}

	// 生命周期钩子
	onMounted(() => {
		console.log('Component mounted')
	})

	onUpdated(() => {
		console.log('Component updated')
	})

	onUnmounted(() => {
		console.log('Component unmounted')
	})

	const extractNamesAsObject = (fields) => {
		return fields.reduce((acc, field) => {
			acc[field.name] = field // 将 field.name 作为键，field 作为值
			return acc
		}, {})
	}

	watch(
		() => props.fields,
		(newVal) => {
			formState.value = { ...extractNamesAsObject(newVal) }
		}
	)
</script>

<style scoped></style>
