<template>
	<a-form
		: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 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/message'
import { updateMethod } from '../../../components/form/method'
import { MessageManageFormDTO } from '../../../entity/system/message-manage'
import { QueryObjectType } from '../../../http/request-model'
import BaseFormItem from '../../../components/form-item/BaseFormItem.vue'
import fields from '../../../views/system/message/fields'

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

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

// 实例化 表单
const formState = ref<MessageManageFormDTO>({
	templateCode: '',
	templateContent: '',
	templateName: ''
})
/**
 * 信息初始化表单
 */
onMounted(async () => {
	if (props.id) {
		const { data } = await requestMethod.getById(props.id)
		// 挂载筛选数据
		formState.value = data
		formState.value.templateListData = data.templateType.split(',')
	}
})

/**
 * 提交表单
 * @param params
 */
const onFinish = async (params: MessageManageFormDTO) => {
	if (params.templateListData) {
		if (params.templateListData.length > 0) params.templateType = params.templateListData.join(',')
	}
	const data = {
		...(params as unknown as QueryObjectType)
	}
	if (!props.id) {
		const resultModel = await requestMethod.add(data)
		messageMethod.success(resultModel.message)
		useUpdateMethod.handleSave()
	} else {
		let { message } = await requestMethod.update({
			...data,
			id: props.id
		})
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	}
}
</script>

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