<template>
	<fs-page class="borrow-page"> 
		<fs-crud ref="crudRef" v-bind="crudBinding" />
		<BorrowTypeSelect v-model:visible="showBorrowTypeDialog" @select="onBorrowTypeSelected" />
		<!-- <CommonBorrow v-if="showCommonBorrowDialog" v-model:visible="showCommonBorrowDialog" :modelValue="borrowForm" @submit="handleBorrowSubmit" /> -->
		<ClassroomBorrow
			v-if="showClassroomBorrowDialog"
			v-model:visible="showClassroomBorrowDialog"
			:modelValue="borrowForm"
			:lastFormSnapshot="lastFormSnapshot"
			@update:lastFormSnapshot="val => lastFormSnapshot = val"
			@submit="handleBorrowSubmit"
		/>
		<SpecialBorrow v-if="showSpecialBorrowDialog" v-model:visible="showSpecialBorrowDialog" :modelValue="borrowForm" @submit="handleBorrowSubmit" />
		<CollectEquipmentDialog  v-model:visible="showCollectDialog" :modelValue="borrowForm" @submit="handleCollectSubmit" />
		<SettlementDialog  v-model:visible="showSettlementDialog" :modelValue="borrowForm" />
	</fs-page>
</template>
<script lang="ts" setup name="borrow">
import { ref, onMounted, onBeforeUnmount,nextTick ,provide } from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import { createCrudOptions } from './crud';
// import { GetPermission } from './api';
// import { handleColumnPermission } from '/@/utils/columnPermission';
import BorrowTypeSelect from './component/BorrowTypeSelect/index.vue';
// import CommonBorrow from './component/CommonBorrow/index.vue';
import ClassroomBorrow from './component/ClassroomBorrow/index.vue';
import SpecialBorrow from './component/SpecialBorrow/index.vue';
import CollectEquipmentDialog from './component/CollectEquipment/index.vue';
import SettlementDialog from './component/CollectEquipment/SettlementDialog.vue';
import * as api from './api';
import { ElMessage } from 'element-plus';

const { crudBinding, crudRef, crudExpose } = useFs({ createCrudOptions });
const showBorrowTypeDialog = ref(false);
// const showCommonBorrowDialog = ref(false);
const showClassroomBorrowDialog = ref(false);
const showSpecialBorrowDialog = ref(false);
const showCollectDialog = ref(false);
const borrowForm = ref({});
const showSettlementDialog = ref(false);	





const lastFormSnapshot = ref({});
// provide('lastFormSnapshot', lastFormSnapshot);


function onBorrowTypeSelected(type: number, mode: 'view' | 'edit' | 'add' |'collect',record?: any) {
	showBorrowTypeDialog.value = false;
	nextTick(() => {
		borrowForm.value = { ...(record || {}), borrow_type: type, mode };
	});
	if (type === 1) {
		showClassroomBorrowDialog.value = true;
	} else if (type === 2) {
		showSpecialBorrowDialog.value = true;
	} else if (type === 0) {
		showCollectDialog.value = true;
	}
}

async function handleBorrowSubmit(formData: any) {
	try {
		if (formData.mode === 'edit') {
			await api.UpdateObj(formData);
			ElMessage.success('编辑成功');
		} else {
			await api.AddObj(formData);
			ElMessage.success('添加成功');
		}
		
		// 刷新列表
		crudRef.value && crudRef.value.doRefresh && crudRef.value.doRefresh();	
		crudExpose.doRefresh();

	} catch (e) {
		// 错误处理
		console.error(formData.mode === 'edit' ? '编辑失败' : '提交失败', e);
		ElMessage.error(formData.mode === 'edit' ? '编辑失败' : '提交失败');
	}
}

async function handleCollectSubmit(formData: any) {
	 try {
		crudExpose.doRefresh();
	 } catch (e) {
		console.error('提交失败', e);
	}
}

async function handleCollect(e: CustomEvent) {
	const row = e.detail;
	console.log("row:::",row);
	showCollectDialog.value = true;
	console.log("showCollectDialog:::",showCollectDialog.value);
	nextTick(() => {
		borrowForm.value = { ...row, mode: 'collect' };
	});
}


async function handleReturn(e: CustomEvent) {
	const row = e.detail;
	console.log("row:::",row);
	showCollectDialog.value = true;
	nextTick(() => {
		borrowForm.value = { ...row, mode: 'return' };
	});
	console.log("showReturnDialog:::",showCollectDialog.value);
}

async function handleView(e: CustomEvent) {
	const row = e.detail;
	onBorrowTypeSelected(row.borrow_type, 'view',row);
}
async function handleEdit(e: CustomEvent) {
	const row = e.detail;
	onBorrowTypeSelected(row.borrow_type, 'edit',row);
}
async function handleRemove(e: CustomEvent) {
	const row = e.detail;
	onBorrowTypeSelected(row.borrow_type);
}
async function handleSettlement(e: CustomEvent) {
	const row = e.detail;
	showSettlementDialog.value = true;
	nextTick(() => {
		borrowForm.value = { ...row, mode: 'settlement' };
	});
}
let observer: MutationObserver | null = null;

onMounted(() => {
	// 设置列权限
	// const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	//重置crudBinding
	// resetCrudOptions(newOptions);
	// 刷新
	crudExpose.doRefresh();
	window.addEventListener('borrow-view', handleView);
	window.addEventListener('borrow-edit', handleEdit);
	window.addEventListener('borrow-remove', handleRemove);
	window.addEventListener('borrow-collect', handleCollect);
	window.addEventListener('borrow-return', handleReturn);
	window.addEventListener('borrow-settlement', handleSettlement);
	// 创建借用单按钮
	function insertButton() {
		const fsActionbar = document.querySelector('.borrow-page .fs-actionbar');
		if (fsActionbar && !fsActionbar.querySelector('.my-create-btn')) {
			const button = document.createElement('button');
			button.className = 'el-button el-button--primary el-button--default my-create-btn';
			button.innerHTML = '创建借用单';
			button.onclick = () => {
				showBorrowTypeDialog.value = true;
			};
			fsActionbar.append(button);
		}
	}

	// 先尝试插入一次
	// insertButton();

	// 监听 DOM 变化，确保 actionbar 出现时插入按钮
	observer = new MutationObserver(() => {
		insertButton();
	});
	observer.observe(document.body, { childList: true, subtree: true });
});
onBeforeUnmount(() => {
	if (observer) {
		observer.disconnect();
		observer = null;
	}
	window.removeEventListener('borrow-view', handleView);
	window.removeEventListener('borrow-collect', handleCollect);
	window.removeEventListener('borrow-return', handleReturn);
	window.removeEventListener('borrow-settlement', handleSettlement);
});
</script>
<style lang="scss" scoped></style>
