<template>
	<fs-page class="workflow-page">
	<!-- <fs-page> -->
		<fs-crud ref="crudRef" v-bind="crudBinding" />
		<WorkflowDialog v-model:visible="dialogVisible" :editData="editData" :mode="dialogMode" @success="onDialogSuccess" />
	</fs-page>
</template>
<script  lang="ts" setup>
import { ref, onMounted, onBeforeUnmount ,onActivated,onDeactivated} from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import { createCrudOptions } from './curd';
import WorkflowDialog from './WorkflowDialog/index.vue';

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ createCrudOptions });
const dialogVisible = ref(false);
const editData = ref(null);
const dialogMode = ref<'view' | 'edit' | 'add'>('add');
let observer: MutationObserver | null = null;

function onAdd() {
	editData.value = null;
	dialogMode.value = 'add';
	dialogVisible.value = true;
}
function onDialogSuccess() {
	dialogVisible.value = false;
	crudExpose.doRefresh();
}

function onView(e: Event) {
	const ce = e as CustomEvent;
	editData.value = ce.detail;
	dialogMode.value = 'view';
	dialogVisible.value = true;
}
function onEdit(e: Event) {
	const ce = e as CustomEvent;
	editData.value = ce.detail;
	dialogMode.value = 'edit';
	dialogVisible.value = true;
}





onMounted(() => {
	crudExpose.doRefresh();
	// window.addEventListener('workflow-add',onAdd);
	window.addEventListener('workflow-view', onView);
	window.addEventListener('workflow-edit', onEdit);
	const fsActionbarfw = document.querySelector('.workflow-page .fs-actionbar');
	if (!fsActionbarfw) return;
	// 创建借用单按钮
	function insertfwButton() {
		if (fsActionbarfw && !fsActionbarfw.querySelector('.my-create-btn')) {
			const buttonwf = document.createElement('button');
			buttonwf.className = 'el-buttonwf el-button el-button--primary el-button--default my-create-btn';
			buttonwf.innerHTML = '新建审批流程';
			buttonwf.onclick = onAdd;
			fsActionbarfw.append(buttonwf);
		}
	}

	insertfwButton();

	observer = new MutationObserver((_m, obs) => {
		insertfwButton();
		// 插入完毕后停掉 observer
		obs.disconnect();
	});
	observer.observe(fsActionbarfw, { childList: true ,subtree:true});







});
onBeforeUnmount(() => {
	if (observer) {
		observer.disconnect();
		observer = null;
	}
	// window.removeEventListener('workflow-add',onAdd);
	window.removeEventListener('workflow-view', onView);
	window.removeEventListener('workflow-edit', onEdit);
});



// onMounted(async () => {
// 	// 设置列权限
// 	// const newOptions = await handleColumnPermission(GetPermission, crudOptions);
// 	//重置crudBinding
// 	// resetCrudOptions(newOptions);
// 	// 刷新
// 	crudExpose.doRefresh();
// });

</script>

<style  scoped>


</style>
