<template>
	<el-dialog v-model="state.dialogVisible" width="800px" draggable title="编辑特殊号码" @close="close" append-to-body destroy-on-close>
		<el-form :model="state.ruleForm" label-width="100px" ref="ruleFormRef" :disabled="loading">
			<el-form-item label="电话号码" prop="phoneNumber" :rules="[{ required: true, message: '请填写电话号码', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.phoneNumber" placeholder="请填写电话号码" clearable></el-input>
			</el-form-item>
			<el-form-item label="备注" prop="notes" :rules="[{ required: true, message: '请填写备注', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.notes" placeholder="请填写备注" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="closeDialog" class="default-button">取 消</el-button>
				<el-button type="primary" @click="onSubmit(ruleFormRef)" :loading="loading">确 定</el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { throttle } from '@/utils/tools';
import { getSpecialNumberDetail, updateSpecialNumber } from '@/api/auxiliary/specialNumber';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		phoneNumber: null, // 电话号码
		notes: null, // 备注
	},
});
let loading = ref<boolean>(false); // 加载状态
// 打开弹窗
const ruleFormRef = ref<RefType>();
const openDialog = async (Id: string) => {
	state.dialogVisible = true;
	try {
		const { result } = await getSpecialNumberDetail({ Id });
		state.ruleForm = result;
	} catch (error) {
		console.log(error);
	}
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.resetFields();
	ruleFormRef.value?.resetFields();
};
// 新增
const onSubmit = throttle(async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		loading.value = true;
		const request = {
			...state.ruleForm,
		};
		updateSpecialNumber(request)
			.then(() => {
				ElMessage({
					message: '修改成功',
					type: 'success',
				});
				loading.value = false;
				closeDialog();
				emit('updateList');
			})
			.catch(() => {
				// 新增失败
				loading.value = false;
				closeDialog();
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
