<template>
	<div class="system-menu-container">
		<el-dialog v-model="state.isShowDialog" width="469px" center>
			<template #header>
				<div style="font-size: large" v-drag="['.app-container .el-dialog', '.app-container .el-dialog__header']">{{ title }}</div>
			</template>
			<el-form label-position="top" :model="state.ruleForm" :rules="state.ruleRules" ref="ruleFormRef" label-width="80px">
				<el-form-item label="" prop="name">
					<el-input v-model="state.ruleForm.name" placeholder="请输入文件名" />
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel">取 消</el-button>
					<el-button type="primary" @click="onSubmit" :loading="state.loading">保 存</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup>
import { reactive, ref, unref, getCurrentInstance } from 'vue';
import { add, update } from '@/api/files/list';
import { ElMessage } from 'element-plus';

const props = defineProps({
	title: {
		type: String,
		default: () => '',
	},
	currentId: {
		type: Number,
		default: () => 0,
	},
});

const { proxy } = getCurrentInstance() as any;
const ruleFormRef = ref<HTMLElement | null>(null);
const state = reactive({
	// 是否显示弹出层
	isShowDialog: false,
	loading: false,
	// 表单参数对象
	ruleForm: {
		name: '',
		id: undefined,
		parentId: 0,
	},
	// 类型数据配置参数
	methodOptions: [],
	// 表单校验
	ruleRules: {
		name: [{ required: true, message: '文件名不能为空', trigger: 'blur' }],
	},
});
// 打开弹窗
const openDialog = (row: any) => {
	const rowData = JSON.parse(JSON.stringify(row));
	state.ruleForm = {
		...state.ruleForm,
		name: rowData.file_name,
		id: rowData.id,
	};
	state.isShowDialog = true;
	state.loading = false;
};

// 关闭弹窗
const closeDialog = (row?: object) => {
	proxy.mittBus.emit('onEditApiModule', row);
	state.isShowDialog = false;
};
// 取消
const onCancel = () => {
	state.isShowDialog = false;
};

// 保存
const onSubmit = () => {
	const formWrap = unref(ruleFormRef) as any;
	if (!formWrap) return;
	formWrap.validate((valid: boolean) => {
		if (valid) {
			state.loading = true;
			if (state.ruleForm.id != undefined && state.ruleForm.id != 0) {
				update({ name: state.ruleForm.name, id: state.ruleForm.id }).then((res) => {
					if (res) {
						ElMessage.success('修改成功');
						closeDialog(state.ruleForm); // 关闭弹窗
					}
					state.loading = false;
				});
			} else {
				const params = {
					name: state.ruleForm.name,
					isCatalogue: 1,
					isPublic: 1,
					parentId: props.currentId,
				};
				add(params).then((res: any) => {
					if (res) {
						ElMessage.success('新增成功');
						closeDialog(state.ruleForm); // 关闭弹窗
					}
					state.loading = false;
				});
			}
		}
	});
};

defineExpose({
	openDialog,
});
</script>
