<template>
	<el-dialog :title="dialogTitle" v-model="state.dialogVisible" width="30%" draggable append-to-body destroy-on-close @close="close">
		<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="80px" v-loading="state.loading">
			<el-form-item :label="textTip" prop="content" :rules="[{ required: true, message: '请填写'+textTip, trigger: 'blur' }]">
				<el-input
					v-model="state.ruleForm.content"
					type="textarea"
					:autosize="{ minRows: 6, maxRows: 10 }"
					:placeholder="'请填写'+textTip"
				>
				</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 { computed, reactive, ref } from 'vue';
import { ElMessage, FormInstance } from 'element-plus';
import { editPlanAudit, planDelAudit } from '@/api/plan';

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

// 定义变量内容
const state = reactive<any>({
	dialogVisible: false, // 弹窗
	ruleForm: {
		name: '', // 类型名称
		sort: 0, // 排序
		parentId: '', // 上级类型
	},
	loading: false, // 加载
	planInfo:{}, // 预案详情内容
});
const planType = ref('update');
const dialogTitle = computed(()=>{
	if(planType.value==='update'){
		return '更新预案'
	}else if(planType.value==='delete'){
		return '删除预案'
	}
})
const textTip = computed(()=>{
	if(planType.value==='update'){
		return '更新说明'
	}else if(planType.value==='delete'){
		return '删除说明'
	}
})
// 打开弹窗
const ruleFormRef = ref<any>(); // 表单ref
const openDialog = (row:any,type='update') => {
	state.planInfo = row;
	planType.value = type;
	state.dialogVisible = true;
};
const close = () => {
	ruleFormRef.value?.clearValidate();
	ruleFormRef.value?.resetFields();
};
// 关闭弹窗
const closeDialog = () => {
	state.dialogVisible = false;
};
// 新增
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate((valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		if(planType.value==='update'){ // 更新提交审核
			editPlanAudit({
				...state.planInfo,
				applyReason:state.ruleForm.content,
			})
				.then(() => {
					emit('updateList');
					closeDialog(); // 关闭弹窗
					ElMessage.success('更新审核提交成功');
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		}else{ // 删除提交审核
			planDelAudit({
				id:state.planInfo.id,
				applyReason:state.ruleForm.content,
			})
				.then(() => {
					emit('updateList');
					closeDialog(); // 关闭弹窗
					ElMessage.success('删除审核提交成功');
					state.loading = false;
				})
				.catch(() => {
					state.loading = false;
				});
		}
	});
};
// 暴露变量
defineExpose({
	openDialog,
	closeDialog,
});
</script>
