<template>
	<div>
		<form-render
			v-model="formData"
			:config="{
				layout: 'vertical',
				colon: true,
				hideRequiredMark: false,
				labelAlign: 'right',
				labelType: 'fixed',
				scrollToFirstError: false,
				validateOnRuleChange: true,
				labelCol: {},
			}"
			:hidden-fields="hiddenFields"
			:items="formItems"
		>
			<template v-if="formItem.type === FormItemTypeEnum.TRANSFER" #before-oneWay>
				<a-form-item label="数据源">
					<data-source-table
						:data-source="formItem.properties.dataSource || []"
						@update:data-source="dataSourceChange"
					></data-source-table>
				</a-form-item>
			</template>
			<template v-if="formItem.type === FormItemTypeEnum.TREE_SELECT" #after-size>
				<a-form-item label="数据源">
					<tree-data-table
						:tree-data="formItem.properties.treeData || []"
						@update:tree-data="treeDataChange"
					></tree-data-table>
				</a-form-item>
			</template>
		</form-render>
		<option-table
			v-if="showOptionsTable"
			:options="formItem.properties.options"
			:tree="tree"
			@update:options="optionsChange"
		></option-table>
	</div>
</template>
<script lang="ts" setup>
	import { DataSource, FormItem, FormItemTypeEnum, Option } from '@/components/form-render/form-render-types'
	import { TreeDataNode } from 'ant-design-vue/es/vc-tree-select/interface'

	const props = defineProps({
		formItem: {
			type: Object as PropType<FormItem>,
			required: true,
		},
	})
	const { formItem } = toRefs(props)

	const tree = computed(() => {
		return formItem.value.type === FormItemTypeEnum.CASCADER
	})

	const showOptionsTable = computed(() => {
		return (
			formItem.value.type === FormItemTypeEnum.RADIO ||
			formItem.value.type === FormItemTypeEnum.SELECT ||
			formItem.value.type === FormItemTypeEnum.AUTO_COMPLETE ||
			formItem.value.type === FormItemTypeEnum.MENTION ||
			formItem.value.type === FormItemTypeEnum.CHECKBOX ||
			formItem.value.type === FormItemTypeEnum.CASCADER
		)
	})
	const formItems = computed(() => {
		return formItem.value.propertyConfigFormComponents ?? []
	})

	const hiddenFields = computed(() => {
		if (formItem.value.hiddenFieldsFun) {
			return formItem.value.hiddenFieldsFun(formData.value)
		}
		return []
	})

	const emit = defineEmits<{
		'update:form-item': [item: FormItem]
	}>()

	const optionsChange = (_options: Option[]) => {
		formItem.value.properties.options = _options
		emit('update:form-item', formItem.value)
	}

	const dataSourceChange = (_dataSource: DataSource[]) => {
		formItem.value.properties.dataSource = _dataSource
		emit('update:form-item', formItem.value)
	}

	const treeDataChange = (_treeData: TreeDataNode[]) => {
		formItem.value.properties.treeData = _treeData
		emit('update:form-item', formItem.value)
	}

	const formData = computed({
		get: () => {
			return formItem.value.properties
		},
		set: (val) => {
			formItem.value.properties = val
			emit('update:form-item', formItem.value)
		},
	})
</script>
