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

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

/**
 * 定义传入参数
 */
const props = defineProps<{
	id?: string
}>()

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

const formState = ref<DictionaryDTO>({
	id: '',
	itemName: '',
	itemCode: '',
	memo: ''
})

// 页面载入事件
onMounted(async () => {
	if (props.id) {
		const { data } = await requestMethod.getById(props.id)
		formState.value = { ...data }
	}
})

// 提交
const onFinish = async (params: DictionaryDTO) => {
	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 {
		let { message } = await requestMethod.add(data)
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	}
}
</script>

<style scoped>
.cancel {
	margin-left: 10px;
}
</style>
