<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"
		name="basic"
		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 requestDept from '../../../api/account/department'
import requestOrg from '../../../api/account/organization'
import { QueryObjectType } from '../../../http/request-model'
import { messageMethod } from '../../../utils/message-util'
import { updateMethod } from '../../../components/form/method'
import fields from './fields'
import { SelectProps } from '../../../components/form-item/props'
import BaseFormItem from '../../../components/form-item/BaseFormItem.vue'
import { AccountDept } from '../../../entity/account/account-dept'

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

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

const formState = reactive<Partial<AccountDept>>({})

/**
 * 如果是编辑，获取数据
 * 请求列表数据
 */
const filedList = ref(fields)
onMounted(async () => {
	// 所属单位
	const orgTypeValue = filedList.value.find(value => value.name == 'fkOrgId')?.typeValue
	if (orgTypeValue) {
		let { data } = await requestOrg.formSelect()
		;(orgTypeValue as SelectProps).options = data
	}

	// 获取部门
	const departmentTypeValue = filedList.value.find(value => value.name == 'fkParentId')?.typeValue
	if (departmentTypeValue) {
		let { data } = await requestDept.formSelect()
		;(departmentTypeValue as SelectProps).options = data
	}

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

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

<style scoped></style>
