<template>
	<a-form
		:label-align="useUpdateMethod.formLabelAlign"
		: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 fields" :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 style="margin-left: 10px" @click="useUpdateMethod.handleCancel()">取消</a-button>
		</a-form-item>
	</a-form>
</template>

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

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

/**
 *  获取父组件参数
 */
const props = defineProps<{ id?: string }>()

const formState = ref<SystemParameterFormDTO>({})

onMounted(async () => {
	if (props.id) {
		const { data } = await requestMethod.getById(props.id)

		formState.value = { ...data }
	}
})

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

<style scoped></style>
