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

const { crudBinding, crudRef, crudExpose } = 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();
	// 动态追加“新建审批流程”按钮
	function insertfwButton() {
		const fsActionbarfw= document.querySelector('.workflow-page .fs-actionbar');
		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();

	// 监听 DOM 变化，确保 actionbar 出现时插入按钮
	observer = new MutationObserver(() => {
		setTimeout(() => {
		insertfwButton();
		}, 30); 

		// insertfwButton();
	});
	observer.observe(document.body, { childList: true, subtree: true });
	window.addEventListener('workflow-view', onView);
	window.addEventListener('workflow-edit', onEdit);
});
onBeforeUnmount(() => {
	if (observer) {
		observer.disconnect();
		observer = null;
	}
	window.removeEventListener('workflow-view', onView);
	window.removeEventListener('workflow-edit', onEdit);
});
</script>
