<template>
	<xn-form-container title="完善用户信息" :width="500" v-model:open="open" :destroy-on-close="true" @close="onClose">
		<a-form
			ref="formRef"
			:model="formData"
			:rules="formRules"
			layout="inline"
			:label-col="{ style: { width: '80px', justifyContent: 'end' } }"
		>
			<a-form-item label="真实姓名" name="name">
				<a-input v-model:value="formData.name" placeholder="请输入真实姓名" allow-clear />
			</a-form-item>
			<a-form-item label="用户昵称" name="nickName">
				<a-input v-model:value="formData.nickName" disabled allow-clear />
			</a-form-item>

			<a-form-item label="选择组织" name="createOrg">
				<a-select
					ref="select"
					v-model:value="formData.createOrg"
					:options="options"
					allowClear
					style="width: 100%"
					placeholder="请选择您要绑定的组织"
					:field-names="{ label: 'name', value: 'id' }"
				/>
			</a-form-item>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="onClose">关闭</a-button>
			<a-button type="primary" @click="onSubmit" :loading="submitLoading">保存</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import { cloneDeep } from 'lodash-es'

	import { required } from '@/utils/formRules'
	import orgApi from '@/api/sys/orgApi.js'
	import alarmUserApi from '@/api/coldchain/alarmUserApi'
	const options = ref([]) //机构数据
	// 抽屉状态
	const open = ref(false)
	const emit = defineEmits({ successful: null })
	const formRef = ref()
	// 表单数据
	const formData = ref({})
	const submitLoading = ref(false)

	// 打开抽屉
	const onOpen = (record) => {
		getOrg()
		open.value = true
		if (record) {
			let recordData = cloneDeep(record)
			formData.value = Object.assign({}, recordData)
			if (formData.value.createOrg == -1) {
				formData.value.createOrg = null
			}
		}
	}

	// 获取机构信息
	const getOrg = () => {
		orgApi.orgList().then((res) => {
			options.value = res || []
		})
	}

	// 关闭抽屉
	const onClose = () => {
		formRef.value.resetFields()
		formData.value = {}
		open.value = false
	}
	// 默认要校验的
	const formRules = {
		name: [required('请输入真实姓名')],
		createOrg: [required('请选择组织')]
	}
	// 验证并提交数据
	const onSubmit = () => {
		formRef.value
			.validate()
			.then(() => {
				submitLoading.value = true
				const formDataParam = cloneDeep(formData.value)
				alarmUserApi
					.alarmUserSubmitForm(formDataParam, formDataParam.id)
					.then(() => {
						onClose()
						emit('successful')
					})
					.finally(() => {
						submitLoading.value = false
					})
			})
			.catch(() => {})
	}
	// 抛出函数
	defineExpose({
		onOpen
	})
</script>

<style lang="less" scoped>
	:deep(.ant-form-item) {
		width: 100%;
		margin-bottom: 10px;
		.ant-form-item-control {
			flex: 1;
		}
	}
</style>
