<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: 0, id: 'status-1' })">
						<div class="item-content">
							<el-icon><Clock /></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><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>
						</div>
						<div class="item-count" v-if="statusCounts[3]">{{ statusCounts[3] }}</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>
		</div>
		<BatchTagsDialog ref="batchTagsDialogRef" :crudExpose="crudExpose" />
		<BatchStatusDialog ref="batchStatusDialogRef" :crudExpose="crudExpose" @success="handleBatchStatusSuccess" />
		<smSnotification ref="smSnotificationRef" :crudExpose="crudExpose" />
	</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/index.vue';
import BatchStatusDialog from './components/BatchStatusDialog.vue';
import smSnotification from './components/smSnotification.vue';
import { getApplicationStatusSummary } from './api';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { Session } from '/@/utils/storage';

const route = useRoute();

const { crudBinding, crudRef, crudExpose, crudOptions, resetCrudOptions } = useFs({ 
	createCrudOptions,
	context: {
		openBatchTagsDialog: (selection: any) => {
			batchTagsDialogRef.value.open(selection);
		},
		openBatchStatusDialog: (selection: any) => {
			batchStatusDialogRef.value.open(selection);
		},
		openSmsNotification:(selection:any)=>{
			smSnotificationRef.value.open(selection)
		},
		selectedRows: [] // 存储选中的行
	}
});

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

// 状态计数
const totalCount = ref(0);
const statusCounts = reactive<Record<number, number>>({
	1: 0, // 待面试
	2: 0, // 已面试
	3: 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)) {
				data.data.status_data.forEach((item: any) => {
					// 注意：API返回的status可能与前端定义的不完全一致，需要映射
					const statusMap: Record<number, number> = {
						0: 1, // API中的0对应前端的1（待面试）
						2: 2, // 已面试
						3: 3, // 已录用
						4: 4  // 已拒绝
					};
					
					const frontendStatus = statusMap[item.status];
					if (frontendStatus && frontendStatus in statusCounts) {
						statusCounts[frontendStatus] = item.count;
					}
				});
			} else {
				// 如果没有status_data，则使用单独的字段
				statusCounts[1] = data.data.pending || 0;
				statusCounts[2] = data.data.interviewed || 0;
				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);
		}
		
		// 无论如何都执行搜索，确保数据刷新
		crudExpose.doSearch({
			form: {}
		});
	} else if (data.type === 'status') {
		// 按状态筛选
		crudExpose.doSearch({
			form: {
				status: data.value
			}
		});
	} else if (data.type === 'position') {
		// 按职位筛选
		crudExpose.doSearch({
			form: {
				position_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);
	/* getPositionList() */
	// 处理URL参数
	const urlStatus = route.query.status;
	console.log(urlStatus)
	if (urlStatus) {
		// 根据URL状态参数设置活动节点
		const statusValue = Number(urlStatus);
		switch (statusValue) {
			case 0:
				activeNode.value = 'status-1';
				break;
			case 2:
				activeNode.value = 'status-2';
				break;
			case 3:
				activeNode.value = 'status-3';
				break;
			case 4:
				activeNode.value = 'status-4';
				break;
			default:
				activeNode.value = 'all';
		}
		
		// 使用doSearch进行带状态参数的搜索
		crudExpose.doSearch({
			form: {
				status: statusValue
			}
		});
	} else {
		// 没有URL参数时，执行普通刷新
		crudExpose.doRefresh();
	}
});

const getPositionList = async () => {
	try {
		// 从环境变量或配置中获取
		const appid = 'wxc9655eeaa3223b75';
		const secret = 'c0f031b6e07ded1928fded435a913902';
		
		if (!appid || !secret) {
			throw new Error('微信配置信息不完整');
		}

		const response = await fetch(`${import.meta.env.VITE_API_URL}/wechat/generatescheme`);
		const data = await response.json();
		
		if (data.access_token) {
			return data.access_token;
		} else {
			throw new Error(data.errmsg || '获取access_token失败');
		}
	} catch (error) {
		console.error('获取微信access_token失败:', error);
		ElMessage.error('获取微信access_token失败');
		throw error;
	}
}
</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;
}

.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;
}

.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 {
	padding-left: 8px;
}

.content {
	flex: 1;
	overflow: hidden;
}
</style>
