<template>
	<dc-drawer-header v-if="props.id" :detail="formState" />

	<a-form
		ref="formRef"
		:label-col="useUpdateMethod.formLabelCol"
		:model="formState"
		:wrapper-col="useUpdateMethod.formWrapperCol"
		autocomplete="off"
		name="basic"
		@finish="onFinish"
		@finishFailed="useUpdateMethod.formFail"
	>
		<base-form-item v-for="item of fieldList" :key="item.name" v-model:value="formState[item.name]" v-bind="item" />
		<a-form-item :wrapper-col="useUpdateMethod.formActionCol">
			<a-button html-type="submit" type="primary">确定</a-button>
			<a-button class="formButton" @click="useUpdateMethod.handleCancel()">取消</a-button>
		</a-form-item>
	</a-form>
</template>

<script lang="ts" setup>
import { messageMethod } from '../../../utils/message-util'
import { onMounted, ref } from 'vue'
import requestMethod from '../../../api/system/dictionary'
import { updateMethod } from '../../../components/form/method'
import { DictionaryManageFormDTO } from '../../../entity/system/dictionary-manage'
import { QueryObjectType } from '../../../http/request-model'
import BaseFormItem from '../../../components/form-item/BaseFormItem.vue'
import fields from '../../../views/system/dictionary/fields'
import { FieldProps, SelectProps } from '../../../components/form-item/field-props'

// 操作页面的公用方法
const useUpdateMethod = updateMethod()

// 父对象传来的值
const props = defineProps<{
	id?: string
	rfRootCode: string
	itemName?: string
}>()
defineEmits<{ (e: 'cancel'): void; (e: 'refresh'): void }>()

// 实例化 表单
const formState = ref<DictionaryManageFormDTO>({
	itemName: '',
	rfRootCode: props.rfRootCode
})

/**
 * 添加下拉框
 */
const fieldList = ref(fields)
onMounted(async () => {
	if (props.id) {
		const { data } = await requestMethod.getById(props.id)
		formState.value = data
	}

	if (props.rfRootCode) {
		const { data } = await requestMethod.getListRootCode(props.rfRootCode)
		// 挂载筛选数据
		const typeValue = fieldList.value.find(value => value.name == 'fkParentId')?.typeValue
		if (typeValue) {
			const temp = typeValue as SelectProps
			temp.options = data
		}

		// 判断当前的id是否存在, 如果不存在则置空
		if (formState.value.fkParentId) {
			let findId = data.some(value => value.id == formState.value.fkParentId)
			if (!findId) formState.value.fkParentId = ''
		}
	}
})

/**
 * 提交表单
 * @param params
 */
const onFinish = async (params: DictionaryManageFormDTO) => {
	const data = {
		...(params as unknown as QueryObjectType),
		version: formState.value.version || 0
	}
	if (props.id) {
		let { message } = await requestMethod.update({
			...data,
			id: props.id
		})
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	} else {
		const resultModel = await requestMethod.add(data)
		messageMethod.success(resultModel.message)
		useUpdateMethod.handleSave()
	}
}
</script>

<style scoped>
.formButton {
	margin-left: 0.625rem;
}
</style>
