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

	<a-form
		:label-align="useUpdateMethod.formLabelAlign"
		:label-col="useUpdateMethod.formLabelCol"
		:model="formState"
		:wrapper-col="useUpdateMethod.formWrapperCol"
		scrollToFirstError
		@finish="onFinish"
		@finishFailed="useUpdateMethod.formFail"
	>
		<base-form-item v-for="item of filedList" :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, reactive, ref } from 'vue'
import requestOrg from '../../../api/account/organization'
import { AccountOrg } from '../../../entity/account/account-org'
import { QueryObjectType } from '../../../http/request-model'
import { messageMethod } from '../../../utils/message-util'
import { updateMethod } from '../../../components/form/method'
import BaseFormItem from '../../../components/form-item/BaseFormItem.vue'
import fields from './fields'
import { SelectProps } from '../../../components/form-item/props'

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

// 获取父组件参数
const props = defineProps<{ id?: string }>()
defineEmits<{ (e: 'cancel'): void; (e: 'refresh'): void }>()

const formState = reactive<Partial<AccountOrg>>({
	orgCode: '',
	orgName: ''
})

/**
 * 如果是编辑，获取数据
 * 请求列表数据
 */
const filedList = ref(fields)
onMounted(async () => {
	// 挂载筛选数据
	const typeValue = filedList.value.find(value => value.name == 'fkParentId')?.typeValue
	if (typeValue) {
		const temp = typeValue as SelectProps

		let { data } = await requestOrg.formSelect()
		temp.options = data
	}

	if (props.id) {
		const { data } = await requestOrg.getById(props.id)
		Object.assign(formState, data)
	}
})

/**
 * 提交表单
 * @param value
 */
const onFinish = async (value: AccountOrg) => {
	// 处理一下图标
	if (props.id) {
		// 如果有id， 说明是更新
		value.id = props.id
		value.version = formState.version
		const { message } = await requestOrg.update({ ...(value as unknown as QueryObjectType) })
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	} else {
		const { message } = await requestOrg.add({ ...(value as unknown as QueryObjectType) })
		messageMethod.success(message)
		useUpdateMethod.handleSave()
	}
}
</script>

<style scoped></style>
