<template>
	<fs-page class="borrow-page"> 
		<!-- <fs-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"
			@refresh="crudExpose.doRefresh()"
		/>
		<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,onActivated, 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';
import { useRoute } from 'vue-router';
const route = useRoute();

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;
	// 必须先同步写入 borrowForm，再打开子弹窗；若在 nextTick 中赋值，子组件挂载时仍拿到上一次的查看/编辑数据，会误拉详情并残留在表单中
	borrowForm.value = { ...(record || {}), borrow_type: type, mode };
	if (type === 1) {
		if (mode === 'view') {
			showCollectDialog.value = true;
		} else {
			showClassroomBorrowDialog.value = true;
		}
	} else if (type === 2) {
		if (mode === 'view') {
			showCollectDialog.value = true;
		} else {
			showSpecialBorrowDialog.value = true;
		}
	} else if (type === 0) {
		if (mode === 'view') {
			showCollectDialog.value = true;
		} else {
			showCommonBorrowDialog.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;
	console.log("row:::",row);
	try {
		// 获取申请详情，避免直接使用行内简略数据
		const res: any = await api.GetApplicationDetail(row.id);
		const detail = res?.data || res; // 兼容后端返回结构
		showSettlementDialog.value = true;
		nextTick(() => {
			borrowForm.value = { ...(detail || {}), mode: 'settlement' };
		});
	} catch (error) {
		console.error('获取结算详情失败:', error);
		ElMessage.error('获取结算详情失败');
	}
}

async function handleRenewDevice(e: CustomEvent) {
	const res: any = await api.GetApplicationDetail(e.detail.id);
		if(res.code==2000){
			showSettlementDialog.value = true;
			nextTick(() => {
				borrowForm.value = { ...res.data, mode: 'renew' };
			});
		}else{
			ElMessage.error('获取续借详情失败');
		}
}



let observer: MutationObserver | null = null;

onMounted(() => {
	// 设置列权限
	// const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	//重置crudBinding
	// resetCrudOptions(newOptions);
	// 刷新
	/* crudExpose.doRefresh(); */
	// window.addEventListener('borrow-add', () => {
	// 	showBorrowTypeDialog.value = true
	// });
	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);
	window.addEventListener('renew-device', handleRenewDevice);


	const fsActionbar = document.querySelector('.borrow-page .fs-actionbar');
	if (!fsActionbar) return;
	// 创建借用单按钮
	function insertButton() {
		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 });

	observer = new MutationObserver((_m, obs) => {
		insertButton();
		// 插入完毕后停掉 observer
		obs.disconnect();
	});
	observer.observe(fsActionbar, { childList: true });
	crudExpose.doSearch({
			form: {
				status: Number(route.query.status) || ''
			}
		});

});
onBeforeUnmount(() => {
	if (observer) {
		observer.disconnect();
		observer = null;
	}
	// window.removeEventListener('borrow-add', () => {
	// 	showBorrowTypeDialog.value = false
	// });
	window.removeEventListener('borrow-view', handleView);
	window.removeEventListener('borrow-edit', handleEdit);
	window.removeEventListener('borrow-remove', handleRemove);
	window.removeEventListener('borrow-collect', handleCollect);
	window.removeEventListener('borrow-return', handleReturn);
	window.removeEventListener('borrow-settlement', handleSettlement);
	window.removeEventListener('renew-device', handleRenewDevice);
});

// onActivated(() => {
//   crudExpose.doRefresh();
// });



</script>
<style lang="scss" scoped></style>
