<template>
	<el-dialog v-model="state.dialogVisible" draggable title="回复" append-to-body ref="dialogRef" destroy-on-close @close="close">
		<el-form :model="state.ruleForm" label-width="90px" ref="ruleFormRef">
			<el-form-item label="回复内容" class="textarea" prop="replyContent" :rules="[{ required: true, message: '请填写回复内容', trigger: 'blur' }]">
				<el-input
					v-model="state.ruleForm.replyContent"
					type="textarea"
					show-word-limit
					:autosize="{ minRows: 6, maxRows: 20 }"
					placeholder="请填写回复内容"
					:maxlength="200"
				/>
			</el-form-item>
			<el-form-item label="完成时间" prop="completionTime" :rules="[{ required: true, message: '请选择选择完成时间', trigger: 'change' }]">
				<el-date-picker v-model="state.ruleForm.completionTime" type="date" placeholder="请选择选择完成时间" value-format="YYYY-MM-DD" />
			</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 { throttle } from '@/utils/tools';
import { getObservationsReply } from '@/api/business/observations';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['updateList']);
// 定义变量内容
const state = reactive<any>({
	dialogVisible: false,
	ruleForm: {
		replyContent: null, // 回复内容
		completionTime: null, // 完成时间
		id: null,
	},
	loading: false, // 提交按钮loading
});
const ruleFormRef = ref<RefType>();
// 打开弹窗
const openDialog = async (val: any) => {
	state.ruleForm.id = val.id;
	state.dialogVisible = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 提交
const onSubmit = throttle((formEl: FormInstance | undefined) => {
	if (!formEl) return;
	formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		getObservationsReply(state.ruleForm)
			.then(() => {
				ElMessage.success('回复成功');
				state.loading = false;
				state.dialogVisible = false;
				emit('updateList');
			})
			.catch(() => {
				state.loading = false;
				state.dialogVisible = false;
			});
	});
}, 300);
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
