<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>
					
					<!-- 状态6 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-6' }" @click="handleNodeClick({ type: 'status', value: 6, id: 'status-6' })">
						<div class="item-content">
							<el-icon><RefreshRight /></el-icon>
							<span>曾就职</span>
						</div>
						<div class="item-count" v-if="statusCounts['6']">{{ statusCounts['6'] }}</div>
					</div>
					
					<!-- 状态7 -->
					<div class="tree-item" :class="{ active: activeNode === 'status-7' }" @click="handleNodeClick({ type: 'status', value: 7, id: 'status-7' })">
						<div class="item-content">
							<el-icon><RefreshRight /></el-icon>
							<span>具备潜力</span>
						</div>
						<div class="item-count" v-if="statusCounts['7']">{{ statusCounts['7'] }}</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><RefreshRight /></el-icon>
							<span>曾就职</span>
						</div>
						<div class="item-count" v-if="statusCounts['1']">{{ statusCounts['1'] }}</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><CircleClose /></el-icon>
							<span>面试未通过</span>
						</div>
						<div class="item-count" v-if="statusCounts['2']">{{ statusCounts['2'] }}</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, CircleClose } 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 showPositionList = ref(true);
const positions = ref<Array<{id: number|string, title: string, count?: number}>>([]);

// 状态计数
const totalCount = ref(0);
const statusCounts = reactive<Record<string, number>>({
	'6': 0,      // 状态6
	'7': 0,      // 状态7
	'1': 0,      // 曾就职
	'2': 0,      // 面试未通过
});

// 获取职位列表
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;
		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) => {
					if (item.status === 6) { // 状态6
						statusCounts['6'] = item.count;
					} else if (item.status === 7) { // 状态7
						statusCounts['7'] = item.count;
					} else if (item.status === 1) { // 曾就职
						statusCounts['1'] = item.count;
					} else if (item.status === 2) { // 面试未通过
						statusCounts['2'] = item.count;
					}
					// 累加到总数中
					totalCount.value =statusCounts['6']+statusCounts['7'];
				});
			}
		} 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);
		}
		
		crudExpose.doSearch({
			form: {
				status:'6,7'
			}
		});
	} 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();
};

// 页面打开后获取列表数据
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);
	
	// 刷新
	crudExpose.doSearch({
		form: {
			status: '6,7' // 试用期、考察期、在职、已离职、在职已盘点
		}
	});
});
</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>
