<template>
	<fs-page>
		<div class="job-application-container">
			<div class="sidebar">
				<div class="tree-container">
					
					<!-- 职位分类 -->
					<div class="category-title" @click="togglePositionList">
						<el-icon><Briefcase /></el-icon>
						<span>职位</span>
						<el-icon class="expand-icon" :class="{ 'is-expanded': showPositionList }">
							<ArrowRight />
						</el-icon>
					</div>
					
					<!-- 职位列表 -->
					<div v-if="showPositionList" class="position-list">
						<!-- 全部职位 -->
						<div class="tree-item" :class="{ active: activeNode === 'position-all' }" @click="handleNodeClick({ type: 'all', id: 'position-all' })">
							<div class="item-content">
								<span>全部</span>
							</div>
						</div>
						
						<!-- 职位列表项 -->
						<div 
							v-for="position in positions" 
							:key="'position-' + position.id" 
							class="tree-item" 
							:class="{ active: activeNode === 'position-' + position.id }"
							@click="handleNodeClick({ type: 'position', value: position.title, id: 'position-' + position.id })"
						>
							<div class="item-content">
								<el-icon><ArrowRight /></el-icon>
								<span>{{ position.title }}</span>
							</div>
							<div class="item-count" v-if="position.count">{{ position.count }}</div>
						</div>
					</div>
					<!-- 全部 -->
					<div class="tree-item" :class="{ active: activeNode === 'all' }" @click="handleNodeClick({ type: 'all' })">
						<div class="item-content">
							<el-icon><Grid /></el-icon>
							<span>全部</span>
						</div>
						<div class="item-count">{{ totalCount }}</div>
					</div>
					
					<!-- 试用期 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-1' }" @click="handleNodeClick({ type: 'status', value: 1, id: 'status-1' })">
						<div class="item-content">
							<el-icon><Clock /></el-icon>
							<span>试用期</span>
							<el-icon class="expand-icon" :class="{ 'is-expanded': showProbationSubMenu }" @click="toggleProbationSubMenu">
								<ArrowRight />
							</el-icon>
						</div>
						<div class="item-count" v-if="statusCounts['1']">{{ statusCounts['1'] }}</div>
					</div>
					
					<!-- 试用期子菜单 -->
					<div v-if="showProbationSubMenu" class="submenu">
						<div class="tree-item" :class="{ active: activeNode === 'status-1-1' }" @click="handleNodeClick({ type: 'status', value: '1-1', id: 'status-1-1' })">
							<div class="item-content">
								<span>通过考核</span>
							</div>
							<div class="item-count" v-if="statusCounts['1-1']">{{ statusCounts['1-1'] }}</div>
						</div>
						<div class="tree-item" :class="{ active: activeNode === 'status-1-2' }" @click="handleNodeClick({ type: 'status', value: '1-2', id: 'status-1-2' })">
							<div class="item-content">
								<span>未通过考核</span>
							</div>
							<div class="item-count" v-if="statusCounts['1-2']">{{ statusCounts['1-2'] }}</div>
						</div>
						<div class="tree-item" :class="{ active: activeNode === 'status-1-3' }" @click="handleNodeClick({ type: 'status', value: '1-3', id: 'status-1-3' })">
							<div class="item-content">
								<span>尚未考核</span>
							</div>
							<div class="item-count" v-if="statusCounts['1-3']">{{ statusCounts['1-3'] }}</div>
						</div>
					</div>
					
					<!-- 考察期 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-2' }" @click="handleNodeClick({ type: 'status', value: 2, id: 'status-2' })">
						<div class="item-content">
							<el-icon><ArrowRight /></el-icon>
							<span>考察期</span>
						</div>
						<div class="item-count" v-if="statusCounts['2']">{{ statusCounts['2'] }}</div>
					</div>
					
					<!-- 正式员工 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-3' }" @click="handleNodeClick({ type: 'status', value: 3, id: 'status-3' })">
						<div class="item-content">
							<el-icon><Check /></el-icon>
							<span>正式员工</span>
							<el-icon class="expand-icon" :class="{ 'is-expanded': showFormalSubMenu }" @click="toggleFormalSubMenu">
								<ArrowRight />
							</el-icon>
						</div>
						<div class="item-count" v-if="statusCounts['3']">{{ statusCounts['3'] }}</div>
					</div>
					
					<!-- 正式员工子菜单 -->
					<div v-if="showFormalSubMenu" class="submenu">
						<div class="tree-item" :class="{ active: activeNode === 'status-3-1' }" @click="handleNodeClick({ type: 'status', value: '5', id: 'status-3-1' })">
							<div class="item-content">
								<span>已盘点</span>
							</div>
							<div class="item-count" v-if="statusCounts['3-1']">{{ statusCounts['3-1'] }}</div>
						</div>
					</div>
					
					<!-- 已离职 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-4' }" @click="handleNodeClick({ type: 'status', value: 4, id: 'status-4' })">
						<div class="item-content">
							<el-icon><RefreshRight /></el-icon>
							<span>已离职</span>
						</div>
						<div class="item-count" v-if="statusCounts['4']">{{ statusCounts['4'] }}</div>
					</div>
					
				</div>
			</div>
			<div class="content">
				<fs-crud ref="crudRef" v-bind="crudBinding">
					<!-- 可以添加自定义插槽，如果需要 -->
				</fs-crud>
				<div class="show-resigned-checkbox">
					<el-checkbox v-model="showResigned" @change="handleShowResignedChange">
						显示已离职员工
					</el-checkbox>
				</div>
			</div>
		</div>
		<BatchTagsDialog ref="batchTagsDialogRef" :crudExpose="crudExpose" />
		<BatchStatusDialog ref="batchStatusDialogRef" :crudExpose="crudExpose" @success="handleBatchStatusSuccess" />
	</fs-page>
</template>

<script lang="ts" setup name="areas">
import { onMounted, ref, reactive } from 'vue';
import { useFs } from '@fast-crud/fast-crud';
import { createCrudOptions } from './crud';
import { GetPermission } from './api';
import { handleColumnPermission } from '/@/utils/columnPermission';
import { Grid, Clock, ArrowRight, Check, RefreshRight, Briefcase } from '@element-plus/icons-vue';
import BatchTagsDialog from './components/BatchTagsDialog.vue';
import BatchStatusDialog from './components/BatchStatusDialog.vue';
import { getApplicationStatusSummary } from './api';
import { Session } from '/@/utils/storage';

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ 
	createCrudOptions,
	context: {
		openBatchTagsDialog: (selection: any) => {
			batchTagsDialogRef.value.open(selection);
		},
		openBatchStatusDialog: (selection: any) => {
			batchStatusDialogRef.value.open(selection);
		},
		selectedRows: ref([]) // 修改为响应式引用
	}
});

const batchTagsDialogRef = ref();
const batchStatusDialogRef = ref();

// 子菜单展开状态
const showProbationSubMenu = ref(false);
const showFormalSubMenu = ref(false);

// 显示已离职员工勾选框状态
const showResigned = ref(false);

// 状态计数
const totalCount = ref(0);
const statusCounts = reactive<Record<string, number>>({
	'1': 0,      // 试用期
	'1-1': 0,    // 通过考核
	'1-2': 0,    // 未通过考核
	'1-3': 0,    // 尚未考核
	'3': 0,      // 正式员工
	'3-1': 0,    // 已盘点
	'3-2': 0,    // 未盘点
	'2': 0,      // 考察期
	'4': 0       // 已离职
});

// 职位列表
const showPositionList = ref(true);
const positions = ref<Array<{id: number|string, title: string, count?: number}>>([]);

// 获取职位列表
const fetchPositions = async () => {
	try {
		const res = await fetch(`${import.meta.env.VITE_API_URL}/api/system/job/list?page=1&limit=100&tenant_id=${Session.get('tenant_id')}`);
		const data = await res.json();
		
		if (data.code === 2000 && data.data ) {
			positions.value = data.data.map((item: any) => ({
				id: item.id,
				title: item.title || item.name || item.job_name,
				count: 0
			}));
		} else {
			console.error('获取职位列表失败:', data.msg || '未知错误');
		}
	} catch (error) {
		console.error('获取职位列表异常:', error);
		// 设置默认职位，以防接口失败
		positions.value = [{ id: 1, title: '流水线操作工', count: 0 }];
	}
};

// 获取申请状态统计数据
const fetchStatusSummary = async () => {
	try {
		const res = await getApplicationStatusSummary();
		const data = res;
		console.log(data)
		if (data.code === 2000 && data.data) {
			/* totalCount.value = data.data.total || 0; */
			
			// 更新状态计数
			if (data.data.status_data && Array.isArray(data.data.status_data)) {
				// 重置总数
				totalCount.value = 0;

				data.data.status_data.forEach((item: any) => {
					// 注意：API返回的status可能与前端定义的不完全一致，需要映射
					const statusMap: Record<number, number> = {
						1: 1, // API中的0对应前端的1（待面试）
						2: 2, // 已面试
						3: 3, // 已录用
						4: 4  // 已拒绝
					};
					
					const frontendStatus = statusMap[item.status];
					if (frontendStatus && frontendStatus in statusCounts) {
						statusCounts[frontendStatus] = item.count;
						// 累加到总数中
						totalCount.value += item.count;
					}
				});
			} else {
				// 如果没有status_data，则使用单独的字段并计算总数
				const pending = data.data.pending || 0;
				const interviewed = data.data.interviewed || 0;
				const hired = data.data.hired || 0;
				const rejected = data.data.rejected || 0;
				
				statusCounts[1] = pending;
				statusCounts[2] = interviewed;
				statusCounts[3] = hired;
				statusCounts[4] = rejected;
				
				// 计算总数
				totalCount.value = pending + interviewed + hired + rejected;
				statusCounts['3'] = data.data.hired || 0;
				statusCounts['4'] = data.data.rejected || 0;
			}
		} else {
			console.error('获取申请状态统计失败:', data.message || '未知错误');
		}
	} catch (error) {
		console.error('获取申请状态统计异常:', error);
	}
};

// 切换职位列表显示
const togglePositionList = () => {
	showPositionList.value = !showPositionList.value;
};

// 当前激活的节点
const activeNode = ref('all');

// 处理树节点点击
const handleNodeClick = (data: any) => {
	activeNode.value = data.id || 'all';
	
	if (data.type === 'all') {
		try {
			// 尝试重置表单，如果方法存在的话
			const searchRef = crudExpose.getSearchRef();
			if (searchRef && typeof searchRef.resetFields === 'function') {
				searchRef.resetFields();
			}
		} catch (error) {
			console.warn('重置表单失败:', error);
		}
		
		// 点击"全部"时也只显示状态为1,2,3,4,5的数据
		crudExpose.doSearch({
			form: {
				status: '1, 2, 3, 4, 5' // 试用期、考察期、在职、已离职、在职已盘点
			}
		});
	} else if (data.type === 'status') {
		// 按状态筛选
		crudExpose.doSearch({
			form: {
				status: data.value
			}
		});
	} else if (data.type === 'position') {
		// 按职位筛选
		crudExpose.doSearch({
			form: {
				title: data.value
			}
		});
	}
};

// 更新计数
const updateCounts = (data: any) => {
	if (!data || !data.records) return;
	
	// 统计各职位数量
	// 重置职位计数
	positions.value.forEach(position => {
		position.count = 0;
	});
	
	// 统计职位数量
	data.records.forEach((record: any) => {
		if (record.position_title) {
			const position = positions.value.find(p => p.title === record.position_title);
			if (position) {
				position.count = (position.count || 0) + 1;
			}
		}
	});
};

// 处理批量状态修改成功
const handleBatchStatusSuccess = () => {
	// 刷新数据和状态统计
	crudExpose.doRefresh();
	fetchStatusSummary();
};

// 切换子菜单显示
const toggleProbationSubMenu = (event: Event) => {
	event.stopPropagation();
	showProbationSubMenu.value = !showProbationSubMenu.value;
};

const toggleFormalSubMenu = (event: Event) => {
	event.stopPropagation();
	showFormalSubMenu.value = !showFormalSubMenu.value;
};

// 处理显示已离职员工勾选框变化
const handleShowResignedChange = (value: boolean) => {
	if (value) {
		// 显示已离职员工
		crudExpose.doSearch({
			form: {
				status: 4 // 已离职状态
			}
		});
	} else {
		// 重置搜索，只显示状态为1,2,3,4,5的员工
		crudExpose.doSearch({
			form: {
				status: '1, 2, 3, 4, 5' // 试用期、考察期、在职、已离职、在职已盘点
			}
		});
	}
};

// 页面打开后获取列表数据
onMounted(async () => {
	// 获取职位列表
	await fetchPositions();
	
	// 获取申请状态统计
	await fetchStatusSummary();
	
	// 设置列权限
	const newOptions = await handleColumnPermission(GetPermission, crudOptions);
	
	// 添加数据加载后的回调，用于更新职位计数
	if (newOptions && newOptions.crudOptions && newOptions.crudOptions.request) {
		const originalPageRequest = newOptions.crudOptions.request.pageRequest;
		newOptions.crudOptions.request.pageRequest = async (query: any) => {
			const res = await originalPageRequest(query);
			updateCounts(res.data);
			return res;
		};
	}
	
	// 重置crudBinding
	resetCrudOptions(newOptions);
	
	// 初始化时只显示状态为1,2,3,4,5的数据（排除状态7：转入在外人才库）
	crudExpose.doSearch({
		form: {
			status: '1, 2, 3, 4, 5' // 试用期、考察期、在职、已离职、在职已盘点
		}
	});
});
</script>

<style scoped>
.job-application-container {
	display: flex;
	height: 100%;
}

.sidebar {
	overflow: auto;
	margin-top: 10px;
	width: 200px;
	margin-right: 5px;
	flex-shrink: 0;
	background-color: #fff;
	border-right: 1px solid #ebeef5;
	border-radius: 10px;
}

.tree-container {
	padding: 8px 0;
}

.tree-item {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 10px 16px;
	cursor: pointer;
	transition: background-color 0.3s;
	width: 185px;
}
.item-content span{
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		width: 100%;
	}

.tree-item:hover {
	background-color: #f5f7fa;
}

.tree-item.active {
	background-color: #f0f7ff;
	color: #409eff;
	border-right: 2px solid #409eff;
}

.item-content {
	display: flex;
	align-items: center;
	gap: 8px;
	min-width: 0;
	flex: 1;
}

.item-count {
	font-size: 12px;
	color: #909399;
}

.category-title {
	display: flex;
	align-items: center;
	padding: 12px 16px;
	margin-top: 8px;
	font-weight: 500;
	border-top: 1px solid #ebeef5;
	border-bottom: 1px solid #ebeef5;
	gap: 8px;
	cursor: pointer;
}

.expand-icon {
	margin-left: auto;
	transition: transform 0.3s;
}

.expand-icon.is-expanded {
	transform: rotate(90deg);
}

.position-list {
	width: 100%;
	padding-left: 8px;
}

.content {
	flex: 1;
	overflow: hidden;
}

.submenu {
	padding-left: 20px;
	background-color: #f8f9fa;
}

.submenu .tree-item {
	padding: 8px 16px;
	font-size: 13px;
}

.submenu .tree-item .item-content {
	padding-left: 16px;
}

.expand-icon {
	margin-left: auto;
	transition: transform 0.3s;
	font-size: 12px;
}

.expand-icon.is-expanded {
	transform: rotate(90deg);
}

.show-resigned-checkbox {
	position: fixed;
	bottom: 20px;
	right: 20px;
	background-color: #fff;
	padding: 8px 12px;
	border-radius: 4px;
	box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
	z-index: 100;
}
</style>
