<template>
	<el-dialog title="修改外部市民信息" v-model="state.dialogVisible" width="500px" draggable @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px" v-loading="state.loading">
			<el-form-item label="市民名称" prop="name" :rules="[{ required: true, message: '请填写市民名称', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.name" placeholder="请填写市民名称" clearable></el-input>
			</el-form-item>
			<el-form-item label="市民电话" prop="phoneNum" :rules="[{ required: true, message: '请填写市民电话', trigger: 'blur' }]">
				<el-input v-model="state.ruleForm.phoneNum" placeholder="请填写市民电话" clearable></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="state.loading">确 定 </el-button>
			</span>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { externalCitizenUpdate } from '@/api/auxiliary/externalCitizen';
import Other from '@/utils/other';

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

// 定义变量内容
const ruleFormRef = ref<FormInstance>();
const state = reactive<any>({
	dialogVisible: false, // 弹窗显示隐藏
	ruleForm: {
		name: null, // 市民名称
		phoneNum:null // 市民电话
	},
	loading: false, // 确定按钮loading
});
// 打开弹窗
const openDialog = async (val:any) => {
	state.dialogVisible = true;
	state.ruleForm = Other.deepClone(val);
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 修改
const onSubmit = (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		externalCitizenUpdate(state.ruleForm)
			.then(() => {
				emit('updateList');
				closeDialog(); // 关闭弹窗
				ElMessage.success('操作成功');
				state.loading = false;
			})
			.catch(() => {
				emit('updateList');
				state.loading = false;
				closeDialog();
			});
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
