<template>
	<div class="home-container">
		<el-row :gutter="15" class="home-card-one">
			<!-- 左侧主要内容区域 -->
			<el-col :span="18">
				<el-row :gutter="12" class="home-card-one mb15">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<div class="home-card-one-title">{{greeting}}，{{name}}老师。这是今日的人才情况动态。</div>
					</el-col>
				</el-row>
				<el-row :gutter="10" class="home-card-two mb15">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
						<div class="home-card-item" style="margin-bottom: 10px;height: 160px;">
							<div class="home-card-item-title">待办事项</div>
							<div class="todo-list">
								<div class="todo-item clickable" @click="handleTodoItemClick('interviewed-pending')">
									
									<div class="todo-item-left">
										<div class="item_icon">
											<img src="../../../assets/首页图标1.png" alt="">
										</div>
										<div class="todo-item-text">
											<span class="todo-tag">{{ getPendingCandidatesCount() }}位候选人待处理</span>
											<span class="todo-text">{{ getLatestApplicationTime() }}</span>
										</div>
									</div>
									<div class="todo-item-right">
										<el-icon size="20"><ArrowRightBold /></el-icon>
									</div>
								</div>
								
							</div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="14" :md="14" :lg="14" :xl="14">
						<div class="home-card-item">
							<div style="height: 100%" ref="homeLineRef"></div>
						</div>
					</el-col>
					<el-col :xs="24" :sm="10" :md="10" :lg="10" :xl="10" class="home-media">
						<div class="home-card-item">
							<div style="height: 100%" ref="homePieRef"></div>
						</div>
					</el-col>
				</el-row>
			</el-col>

			<!-- 右侧辅助区域 -->
			<el-col :span="6">
				<div class="home-right" style="margin-top: 75px;">
					<div class="home-card-item">
						<!-- <div class="home-card-item-title">快捷操作</div> -->
						<div class="home-card-item-content">
							<el-select 
								v-model="selectedStatus" 
								placeholder="请选择面试状态" 
								style="margin-right: 5px; width: 120px;"
								@change="handleFilterChange"
							>
								<!-- <el-option label="全部状态" value="" />
								<el-option label="待面试" value="0" /> -->
								<el-option label="已面试" value="2" />
								<el-option label="已录用" value="3" />
								<!-- <el-option label="已拒绝" value="4" /> -->
							</el-select>
							<el-select 
								v-model="selectedPosition" 
								placeholder="请选择职位" 
								style="margin-right: 5px; width: 120px;"
								@change="handleFilterChange"
							>
								<el-option label="全部职位" value="" />
								<el-option 
									v-for="position in positions" 
									:key="position.id" 
									:label="position.title" 
									:value="position.title" 
								/>
							</el-select>
							<el-select 
								v-model="selectedTimeRange" 
								placeholder="请选择时间范围" 
								style="margin-right: 5px; width: 120px;"
								@change="handleFilterChange"
							>
								<el-option label="全部时间" value="" />
								<el-option label="今天" value="today" />
								<el-option label="最近3天" value="3days" />
								<el-option label="最近7天" value="7days" />
								<el-option label="最近30天" value="30days" />
							</el-select>
						</div>
						<!-- <p style="margin-top: 20px; font-size: 12px; color:#808080;">筛选结果</p>
						
					
						<div class="candidate-list" v-loading="candidateLoading">
							<div v-if="filteredCandidates.length === 0" class="no-data">
								<el-empty description="暂无符合条件的候选人" />
							</div>
							<div v-else>
								<div 
									v-for="candidate in filteredCandidates.slice(0, 5)" 
									:key="candidate.id"
									class="candidate-item"
									@click="handleCandidateClick(candidate)"
								>
									<div class="candidate-info">
										<div class="candidate-name">{{ candidate.applicant_name || candidate.name }}</div>
										<div class="candidate-details">
											<span class="candidate-position">{{ candidate.position_title || '未知职位' }}</span>
											<span class="candidate-status" :class="getStatusClass(candidate.status)">
												{{ getStatusText(candidate.status) }}
											</span>
										</div>
									</div>
									<div class="candidate-time">
										{{ formatTime(candidate.created_at || candidate.application_time) }}
									</div>
								</div>
								<div v-if="filteredCandidates.length > 5" class="more-candidates">
									<el-button 
										type="text" 
										@click="viewAllCandidates"
										style="color: #409EFF; font-size: 12px;"
									>
										查看全部 {{ filteredCandidates.length }} 位候选人 →
									</el-button>
								</div>
							</div>
						</div> -->
						<p style="margin-top: 20px; font-size: 12px;  color:#808080;">通过情况概览</p>
						<div class="demo-collapse">
							<el-collapse v-model="activeCollapse">
								<el-collapse-item :title="`在此期间共计${Math.min(filteredCandidates.filter(c => Number(c.comprehensive_score) > 60).length, 5)} 位候选人${selectedStatus==='2'?'通过面试':'被录用'}`" name="1">
									<div class="score-list">
										<div class="score-item clickable-item" v-for="item in filteredCandidates.filter(c => Number(c.comprehensive_score) >= 60).slice(0, 5)" :key="item.id" @click="handleCandidateClick(item)">
											<div class="score-name">{{ item.applicant_name || item.name }}</div>
											<div class="score-name">{{ item.applicant_gender_display || '男' }}</div>
											<!-- <div class="score-name">25岁</div> -->
											<div class="score-name">{{item.position_title}}</div>
											<div class="score-value">{{item.comprehensive_score}}</div>
										</div>
										<!-- <div class="score-item">
											<div class="score-name">李老四</div>  
											<div class="score-name">男</div>
											<div class="score-name">42岁</div>
											<div class="score-name">5年经验</div>
											<div class="score-value">65%</div>
										</div> -->
									</div>
								</el-collapse-item>
							</el-collapse>
						</div>
						<p style="margin-top: 20px; font-size: 12px;  color:#808080;">招聘情况总览</p>
						<p style="font-size: 14px;  color:#808080;">共计 {{ totalCandidates }} 位候选人参与面试，通过率 <span style="color: #409EFF;">{{ passRate }}%</span></p>
												<!-- 这里可以添加右侧内容 -->
					</div>
				</div>
			</el-col>
			<el-col
				:xs="24"
				:sm="12"
				:md="12"
				:lg="6"
				:xl="6"
				v-for="(v, k) in homeOne"
				:key="k"
				:class="{ 'home-media home-media-lg': k > 1, 'home-media-sm': k === 1 }"
			>
				<div class="home-card-item flex" @click="handleCardClick(k)" style="cursor: pointer;">
					<div class="flex-margin flex w100" :class="` home-one-animation${k}`">
						<div class="flex-auto">
							<span class="font30">{{ v.num1 }}</span>
							<!-- <span class="ml5 font16" :style="{ color: v.color1 }">{{ v.num2 }}%</span -->
							<div class="mt10">{{ v.num3 }}</div>
						</div>
						<div class="home-card-item-icon flex" :style="{ background: `var(${v.color2})` }">
							<i class="flex-margin font32" :class="v.num4" :style="{ color: `var(${v.color3})` }"></i>
						</div>
					</div>
				</div>
			</el-col>
		</el-row>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, defineComponent, onMounted, ref, watch, nextTick, onActivated, computed } from 'vue';
import * as echarts from 'echarts';
import { storeToRefs } from 'pinia';
import { useThemeConfig } from '/@/stores/themeConfig';
import { useTagsViewRoutes } from '/@/stores/tagsViewRoutes';
import { GetList } from './api';
import { useRouter } from 'vue-router';
import { Session } from '/@/utils/storage';

// 定义API数据接口
interface ApiData {
	total_applications: number;
	total_positions: number;
	total_questions: number;
	total_reports: number;
	application_trend: Array<{
		date: string;
		count: number;
	}>;
}

// 定义职位接口
interface Position {
	id: number | string;
	title: string;
}

// 定义候选人接口
interface Candidate {
	id: number | string;
	applicant_name?: string;
	name?: string;
	position_title?: string;
	status: number | string;
	created_at?: string;
	application_time?: string;
	applicant_gender_display?: string;
	comprehensive_score?: number | string;
}

let global: any = {
	homeChartOne: null,
	homeChartTwo: null,
	homeCharThree: null,
	dispose: [null, '', undefined],
};

export default defineComponent({
	name: 'home',
	setup() {
		const homeLineRef = ref();
		const homePieRef = ref();
		const homeBarRef = ref();
		const storesTagsViewRoutes = useTagsViewRoutes();
		const storesThemeConfig = useThemeConfig();
		const { themeConfig } = storeToRefs(storesThemeConfig);
		const { isTagsViewCurrenFull } = storeToRefs(storesTagsViewRoutes);
		const state = reactive({
			homeOne: [
				{
					num1: '0',
					num2: '0',
					num3: '申请总数',
					num4: 'fa fa-user',
					color1: '#6690F9',
					color2: '--next-color-danger-lighter',
					color3: '--el-color-danger',
				},
				{
					num1: '0',
					num2: '0',
					num3: '面试岗位数',
					num4: 'fa fa-briefcase',
					color1: '#6690F9',
					color2: '--next-color-success-lighter',
					color3: '--el-color-success',
				},
				/* {
					num1: '0',
					num2: '0',
					num3: '问题总数',
					num4: 'fa fa-question-circle',
					color1: '#6690F9',
					color2: '--next-color-warning-lighter',
					color3: '--el-color-warning',
				}, */
				{
					num1: '0',
					num2: '0',
					num3: '问题总数',
					
					num4: 'fa fa-file-text-o',
					color1: '#6690F9',
					color2: '--next-color-primary-lighter',
					color3: '--el-color-primary',
				},
			],
			// 控制折叠面板展开状态
			activeCollapse: ['1'], // 初始化展开name为"1"的面板
			homeThree: [
				{
					icon: 'iconfont icon-yangan',
					label: '浅粉红',
					value: '2.1%OBS/M',
					iconColor: '#F72B3F',
				},
				{
					icon: 'iconfont icon-wendu',
					label: '深红(猩红)',
					value: '30℃',
					iconColor: '#91BFF8',
				},
				{
					icon: 'iconfont icon-shidu',
					label: '淡紫红',
					value: '57%RH',
					iconColor: '#88D565',
				},
				{
					icon: 'iconfont icon-shidu',
					label: '弱紫罗兰红',
					value: '107w',
					iconColor: '#88D565',
				},
				{
					icon: 'iconfont icon-zaosheng',
					label: '中紫罗兰红',
					value: '57DB',
					iconColor: '#FBD4A0',
				},
				{
					icon: 'iconfont icon-zaosheng',
					label: '紫罗兰',
					value: '57PV',
					iconColor: '#FBD4A0',
				},
				{
					icon: 'iconfont icon-zaosheng',
					label: '暗紫罗兰',
					value: '517Cpd',
					iconColor: '#FBD4A0',
				},
				{
					icon: 'iconfont icon-zaosheng',
					label: '幽灵白',
					value: '12kg',
					iconColor: '#FBD4A0',
				},
				{
					icon: 'iconfont icon-zaosheng',
					label: '海军蓝',
					value: '64fm',
					iconColor: '#FBD4A0',
				},
			],
			myCharts: [],
			charts: {
				theme: '',
				bgColor: '',
				color: '#303133',
			},
			apiData: null as ApiData | null,
			name:'',
			greeting: '',
			selectedStatus: '2',
			selectedPosition: '',
			selectedTimeRange: '',
			candidateLoading: false,
			filteredCandidates: [] as Candidate[],
			positions: [] as Position[],
			totalCandidates: 0,
			passedCandidates: 0,
		});
		const router = useRouter();
		
		// 获取问候语
		const getGreeting = () => {
			const hour = new Date().getHours();
			if (hour >= 0 && hour < 12) {
				return '上午好';
			} else if (hour >= 12 && hour < 18) {
				return '下午好';
			} else {
				return '晚上好';
			}
		};
		
		// 折线图
		const initLineChart = () => {
			if (!global.dispose.some((b: any) => b === global.homeChartOne)) global.homeChartOne.dispose();
			global.homeChartOne = <any>echarts.init(homeLineRef.value, state.charts.theme);
			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: '申请趋势',
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				grid: { top: 70, right: 20, bottom: 30, left: 30 },
				tooltip: { trigger: 'axis' },
				legend: { data: ['申请数量'], right: 0 },
				xAxis: {
					data: state.apiData?.application_trend?.map((item: {date: string; count: number}) => item.date.substring(5)) || 
						['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
				},
				yAxis: [
					{
						type: 'value',
						name: '数量',
						splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
						interval: 100,
						axisLabel: {
							formatter: '{value}'
						}
					},
				],
				series: [
					{
						name: '申请数量',
						type: 'line',
						symbolSize: 6,
						symbol: 'circle',
						smooth: true,
						data: state.apiData?.application_trend?.map((item: {date: string; count: number}) => item.count) || 
							[0, 41.1, 30.4, 65.1, 53.3, 53.3, 53.3, 41.1, 30.4, 65.1, 53.3, 10],
						lineStyle: { color: '#fe9a8b' },
						itemStyle: { color: '#fe9a8b', borderColor: '#fe9a8b' },
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: '#fe9a8bb3' },
								{ offset: 1, color: '#fe9a8b03' },
							]),
						},
					}
				],
			};
			(<any>global.homeChartOne).setOption(option);
			(<any>state.myCharts).push(global.homeChartOne);
		};
		// 饼图
		const initPieChart = () => {
			if (!global.dispose.some((b: any) => b === global.homeChartTwo)) global.homeChartTwo.dispose();
			global.homeChartTwo = <any>echarts.init(homePieRef.value, state.charts.theme);
			var getname = ['申请总数', '职位总数', '问题总数', '报告总数'];
			var getvalue = [];
			
			if (state.apiData) {
				getvalue = [
					state.apiData.total_applications,
					state.apiData.total_positions,
					state.apiData.total_questions,
					state.apiData.total_reports
				];
			} else {
				getvalue = [34.2, 38.87, 17.88, 9.05];
			}
			
			var data = [];
			for (var i = 0; i < getname.length; i++) {
				data.push({ name: getname[i], value: getvalue[i] });
			}
			const colorList = ['#51A3FC', '#36C78B', '#FEC279', '#968AF5', '#E790E8'];
			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: '数据统计',
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				tooltip: { trigger: 'item', formatter: '{b} <br/> {c}%' },
				graphic: {
					elements: [
						{
							type: 'image',
							z: -1,
							style: {
								image: themeConfig.value.isIsDark
									? ''
									: 'data:image/png;base64, ',
								width: 230,
								height: 230,
							},
							left: '16.5%',
							top: 'center',
						},
					],
				},
				legend: {
					type: 'scroll',
					orient: 'vertical',
					right: '0%',
					left: '65%',
					top: 'center',
					itemWidth: 14,
					itemHeight: 14,
					data: getname,
					textStyle: {
						rich: {
							name: {
								fontSize: 14,
								fontWeight: 400,
								width: 200,
								height: 35,
								padding: [0, 0, 0, 60],
								color: state.charts.color,
							},
							rate: {
								fontSize: 15,
								fontWeight: 500,
								height: 35,
								width: 40,
								padding: [0, 0, 0, 30],
								color: state.charts.color,
							},
						},
					},
				},
				series: [
					{
						type: 'pie',
						radius: ['82', themeConfig.value.isIsDark ? '50' : '102'],
						center: ['32%', '50%'],
						itemStyle: {
							color: function (params: any) {
								return colorList[params.dataIndex];
							},
						},
						label: { show: false },
						labelLine: { show: false },
						data: data,
					},
				],
			};
			(<any>global.homeChartTwo).setOption(option);
			(<any>state.myCharts).push(global.homeChartTwo);
		};
		// 柱状图
		const initBarChart = () => {
			if (!global.dispose.some((b: any) => b === global.homeCharThree)) global.homeCharThree.dispose();
			global.homeCharThree = <any>echarts.init(homeBarRef.value, state.charts.theme);
			const option = {
				backgroundColor: state.charts.bgColor,
				title: {
					text: '地热开发利用',
					x: 'left',
					textStyle: { fontSize: '15', color: state.charts.color },
				},
				tooltip: { trigger: 'axis' },
				legend: { data: ['供温', '回温', '压力值(Mpa)'], right: 0 },
				grid: { top: 70, right: 80, bottom: 30, left: 80 },
				xAxis: [
					{
						type: 'category',
						data: ['1km', '2km', '3km', '4km', '5km', '6km'],
						boundaryGap: true,
						axisTick: { show: false },
					},
				],
				yAxis: [
					{
						name: '供回温度(℃）',
						nameLocation: 'middle',
						nameTextStyle: { padding: [3, 4, 50, 6] },
						splitLine: { show: true, lineStyle: { type: 'dashed', color: '#f5f5f5' } },
						axisLine: { show: false },
						axisTick: { show: false },
						axisLabel: { color: state.charts.color, formatter: '{value} ' },
					},
					{
						name: '压力值(Mpa)',
						nameLocation: 'middle',
						nameTextStyle: { padding: [50, 4, 5, 6] },
						splitLine: { show: false },
						axisLine: { show: false },
						axisTick: { show: false },
						axisLabel: { color: state.charts.color, formatter: '{value} ' },
					},
				],
				series: [
					{
						name: '供温',
						type: 'line',
						smooth: true,
						showSymbol: true,
						// 矢量画五角星
						symbol: 'path://M150 0 L80 175 L250 75 L50 75 L220 175 Z',
						symbolSize: 12,
						yAxisIndex: 0,
						areaStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: 'rgba(250,180,101,0.3)' },
								{ offset: 1, color: 'rgba(250,180,101,0)' },
							]),
							shadowColor: 'rgba(250,180,101,0.2)',
							shadowBlur: 20,
						},
						itemStyle: { color: '#FF8000' },
						// data中可以使用对象，value代表相应的值，另外可加入自定义的属性
						data: [
							{ value: 1, stationName: 's1' },
							{ value: 3, stationName: 's2' },
							{ value: 4, stationName: 's3' },
							{ value: 9, stationName: 's4' },
							{ value: 3, stationName: 's5' },
							{ value: 2, stationName: 's6' },
						],
					},
					{
						name: '回温',
						type: 'line',
						smooth: true,
						showSymbol: true,
						symbol: 'emptyCircle',
						symbolSize: 12,
						yAxisIndex: 0,
						areaStyle: {
							color: new echarts.graphic.LinearGradient(
								0,
								0,
								0,
								1,
								[
									{ offset: 0, color: 'rgba(199, 237, 250,0.5)' },
									{ offset: 1, color: 'rgba(199, 237, 250,0.2)' },
								],
								false
							),
						},
						itemStyle: {
							color: '#3bbc86',
						},
						data: [
							{ value: 31, stationName: 's1' },
							{ value: 36, stationName: 's2' },
							{ value: 54, stationName: 's3' },
							{ value: 24, stationName: 's4' },
							{ value: 73, stationName: 's5' },
							{ value: 22, stationName: 's6' },
						],
					},
					{
						name: '压力值(Mpa)',
						type: 'bar',
						barWidth: 30,
						yAxisIndex: 1,
						itemStyle: {
							color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
								{ offset: 0, color: 'rgba(108,80,243,0.3)' },
								{ offset: 1, color: 'rgba(108,80,243,0)' },
							]),
							//柱状图圆角
							borderRadius: [30, 30, 0, 0],
						},
						data: [
							{ value: 11, stationName: 's1' },
							{ value: 34, stationName: 's2' },
							{ value: 54, stationName: 's3' },
							{ value: 39, stationName: 's4' },
							{ value: 63, stationName: 's5' },
							{ value: 24, stationName: 's6' },
						],
					},
				],
			};
			(<any>global.homeCharThree).setOption(option);
			(<any>state.myCharts).push(global.homeCharThree);
		};
		// 批量设置 echarts resize
		const initEchartsResizeFun = () => {
			nextTick(() => {
				for (let i = 0; i < state.myCharts.length; i++) {
					setTimeout(() => {
						(<any>state.myCharts[i]).resize();
					}, i * 1000);
				}
			});
		};
		// 批量设置 echarts resize
		const initEchartsResize = () => {
			window.addEventListener('resize', initEchartsResizeFun);
		};
		// 页面加载时
		onMounted(() => {
			fetchApiData();
			fetchPositions();
			fetchCandidates({ status: '2' });
			//fetchAllCandidatesForStats(); // 获取统计数据
			initEchartsResize();
			state.name = Session.get('userInfo').name?.charAt(0) || '';
			state.greeting = getGreeting();
			console.log(Session.get('userInfo'));
		});
		// 由于页面缓存原因，keep-alive
		onActivated(() => {
			initEchartsResizeFun();
		});
		// 监听 vuex 中的 tagsview 开启全屏变化，重新 resize 图表，防止不出现/大小不变等
		watch(
			() => isTagsViewCurrenFull.value,
			() => {
				initEchartsResizeFun();
			}
		);
		// 监听 vuex 中是否开启深色主题
		watch(
			() => themeConfig.value.isIsDark,
			(isIsDark) => {
				nextTick(() => {
					state.charts.theme = isIsDark ? 'dark' : '';
					state.charts.bgColor = isIsDark ? 'transparent' : '';
					state.charts.color = isIsDark ? '#dadada' : '#303133';
					setTimeout(() => {
						initLineChart();
					}, 500);
					setTimeout(() => {
						initPieChart();
					}, 700);
					setTimeout(() => {
						initBarChart();
					}, 1000);
				});
			},
			{
				deep: true,
				immediate: true,
			}
		);
		// 获取API数据
		const fetchApiData = async () => {
			try {
				const res = await GetList({});
				if (res.code === 2000) {
					state.apiData = res.data;
					updateHomeData(res.data);
				}
			} catch (error) {
				console.error('获取统计数据失败:', error);
			}
		};
		// 更新首页数据
		const updateHomeData = (data: ApiData) => {
			// 更新顶部卡片数据
			state.homeOne[0].num1 = data.total_applications.toString();
			state.homeOne[1].num1 = data.total_positions.toString();
			state.homeOne[2].num1 = data.total_questions.toString();
			state.homeOne[3].num1 = data.total_reports.toString();
			
			// 更新折线图数据
			updateLineChart(data.application_trend);
		};
		// 更新折线图数据
		const updateLineChart = (trendData: Array<{date: string; count: number}>) => {
			if (!global.homeChartOne) return;
			
			const option = {
				xAxis: {
					data: trendData.map((item: {date: string; count: number}) => item.date.substring(5)), // 只显示月-日
				},
				series: [
					{
						name: '申请数量',
						data: trendData.map((item: {date: string; count: number}) => item.count),
					}
				]
			};
			
			(<any>global.homeChartOne).setOption(option);
		};
		// 添加卡片点击跳转功能
		const handleCardClick = (index: number) => {
			const routes = [
				'/JobApplication/list/index', // 申请总数
				'/position/list',    // 职位总数
				'/questionBank/list',    // 问题总数
				'/JobApplication/list/index'       // 报告总数
			];
			
			if (index >= 0 && index < routes.length) {
				router.push(routes[index]);
			}
		};
		
		// 处理待办事项点击跳转功能
		const handleTodoItemClick = (status: string) => {
			// 跳转到求职申请列表页面，并传递状态参数
			router.push({
				path: '/JobApplication/list/index',
				query: {
					status: 2 // 传递状态参数，用于页面筛选已面试待处理的候选人
				}
			});
		};
		
		// 获取职位列表
		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')}`, {
					method: 'GET',
					headers: {
						'Authorization': 'JWT ' + Session.get('token'),
						'Content-Type': 'application/json'
					}
				});
				const data = await res.json();
				
				if (data.code === 2000 && data.data) {
					state.positions = data.data.map((item: any) => ({
						id: item.id,
						title: item.title || item.name || item.job_name,
					}));
				} else {
					console.error('获取职位列表失败:', data.msg || '未知错误');
				}
			} catch (error) {
				console.error('获取职位列表异常:', error);
				// 设置默认职位
				state.positions = [{ id: 1, title: '流水线操作工' }];
			}
		};
		
		// 获取候选人列表
		const fetchCandidates = async (params: any = { status: '2' }) => {
			state.candidateLoading = true;
			try {
				const queryParams = new URLSearchParams({
					page: '1',
					limit: '50',
					tenant_id: Session.get('tenant_id'),
					...params
				});
				
				const res = await fetch(`${import.meta.env.VITE_API_URL}/api/system/job_applications/?${queryParams}`, {
					method: 'GET',
					headers: {
						'Authorization': 'JWT ' + Session.get('token'),
						'Content-Type': 'application/json'
					}
				});
				const data = await res.json();
				
				if (data.code === 2000 && data.data) {
					state.filteredCandidates = data.data;
					// 更新统计信息
					updateCandidateStats(data.data);
				} else {
					state.filteredCandidates = [];
					console.error('获取候选人列表失败:', data.msg || '未知错误');
				}
			} catch (error) {
				console.error('获取候选人列表异常:', error);
				state.filteredCandidates = [];
			} finally {
				state.candidateLoading = false;
			}
		};
		
		// 处理筛选变化
		const handleFilterChange = () => {
			const params: any = {};
			
			// 状态筛选
			if (state.selectedStatus !== '') {
				params.status = state.selectedStatus;
			}
			
			// 职位筛选
			if (state.selectedPosition !== '') {
				console.log(state.selectedPosition)
				params.position_title = state.selectedPosition;
			}
			
			// 时间筛选
			if (state.selectedTimeRange !== '') {
				const timeFilter = getTimeFilter(state.selectedTimeRange);
				if (timeFilter) {
					params.date_from = timeFilter.from;
					params.date_to = timeFilter.to;
				}
			}
			console.log(params)
			fetchCandidates(params);
		};
		
		// 获取时间筛选范围
		const getTimeFilter = (range: string) => {
			const now = new Date();
			const today = new Date(now.getFullYear(), now.getMonth(), now.getDate());
			
			switch (range) {
				case 'today':
					return {
						from: today.toISOString().split('T')[0],
						to: today.toISOString().split('T')[0]
					};
				case '3days':
					const threeDaysAgo = new Date(today);
					threeDaysAgo.setDate(today.getDate() - 3);
					return {
						from: threeDaysAgo.toISOString().split('T')[0],
						to: today.toISOString().split('T')[0]
					};
				case '7days':
					const sevenDaysAgo = new Date(today);
					sevenDaysAgo.setDate(today.getDate() - 7);
					return {
						from: sevenDaysAgo.toISOString().split('T')[0],
						to: today.toISOString().split('T')[0]
					};
				case '30days':
					const thirtyDaysAgo = new Date(today);
					thirtyDaysAgo.setDate(today.getDate() - 30);
					return {
						from: thirtyDaysAgo.toISOString().split('T')[0],
						to: today.toISOString().split('T')[0]
					};
				default:
					return null;
			}
		};
		
		// 获取状态文本
		const getStatusText = (status: number | string) => {
			const statusMap: Record<string, string> = {
				'0': '待面试',
				'1': '待面试',
				'2': '已面试',
				'3': '已录用',
				'4': '已拒绝'
			};
			return statusMap[String(status)] || '未知状态';
		};
		
		// 获取状态样式类
		const getStatusClass = (status: number | string) => {
			const classMap: Record<string, string> = {
				'0': 'status-pending',
				'1': 'status-pending',
				'2': 'status-interviewed',
				'3': 'status-hired',
				'4': 'status-rejected'
			};
			return classMap[String(status)] || 'status-unknown';
		};
		
		// 格式化时间
		const formatTime = (timeStr: string) => {
			if (!timeStr) return '';
			const date = new Date(timeStr);
			const now = new Date();
			const diff = now.getTime() - date.getTime();
			const days = Math.floor(diff / (1000 * 60 * 60 * 24));
			
			if (days === 0) {
				return '今天';
			} else if (days === 1) {
				return '昨天';
			} else if (days < 7) {
				return `${days}天前`;
			} else {
				return date.toLocaleDateString('zh-CN', {
					month: 'short',
					day: 'numeric'
				});
			}
		};
		
		// 处理候选人点击
		const handleCandidateClick = (candidate: any) => {
			// 跳转到候选人详情页面
			const baseUrl = window.location.origin;
			const url = `${baseUrl}/#/JobApplication/report/report?id=${candidate.id}&tenant_id=${Session.get('tenant_id')}&application_id=${candidate.applicant}`;
			window.open(url, '_blank');
			
		};
		
		// 查看全部候选人
		const viewAllCandidates = () => {
			const query: any = {};
			
			// 传递当前筛选条件
			if (state.selectedStatus !== '') {
				query.status = state.selectedStatus;
			}
			if (state.selectedPosition !== '') {
				query.position_id = state.selectedPosition;
			}
			
			router.push({
				path: '/JobApplication/list/index',
				query
			});
		};
		
		// 更新候选人统计信息
		const updateCandidateStats = (candidates: Candidate[]) => {
			state.totalCandidates = candidates.length;
			// 计算通过人数（状态为3表示已录用）
			/* state.passedCandidates = candidates.filter(candidate => 
				candidate.status === 3 || candidate.status === '3'
			).length; */
		};
		
		// 计算通过率
		const passRate = computed(() => {
			if (state.totalCandidates === 0) return '0';
			
			state.passedCandidates = state.filteredCandidates.filter((item: any) =>item.comprehensive_score >= 60).length;
			console.log(state.passedCandidates, state.totalCandidates)
			return ((state.passedCandidates / state.totalCandidates) * 100).toFixed(1);
		});
		
		// 页面加载时获取所有候选人数据用于统计
		const fetchAllCandidatesForStats = async () => {
			try {
				const queryParams = new URLSearchParams({
					page: '1',
					limit: '50', // 获取更多数据用于统计
					tenant_id:Session.get('tenant_id')
				});
				
				const res = await fetch(`${import.meta.env.VITE_API_URL}/api/system/job_applications/?${queryParams}`, {
					method: 'GET',
					headers: {
						'Authorization': 'JWT ' + Session.get('token'),
						'Content-Type': 'application/json'
					}
				});
				const data = await res.json();
				
				if (data.code === 2000 && data.data) {
					updateCandidateStats(data.data);
				}
			} catch (error) {
				console.error('获取候选人统计数据异常:', error);
			}
		};
		
		// 获取待处理候选人数量
		const getPendingCandidatesCount = () => {
			if (!state.filteredCandidates || state.filteredCandidates.length === 0) {
				return 0;
			}
			// 统计状态为2（已面试）的候选人数量
			return state.filteredCandidates.filter(candidate => 
				candidate.status === 2 || candidate.status === '2'
			).length;
		};

		// 获取最新投递时间
		const getLatestApplicationTime = () => {
			if (!state.filteredCandidates || state.filteredCandidates.length === 0) {
				return '暂无投递';
			}

			// 找到最新的投递时间
			const latestApplication = state.filteredCandidates.reduce((latest, current) => {
				const currentTime = current.created_at || current.application_time || '';
				const latestTime = latest.created_at || latest.application_time || '';
				const currentDate = new Date(currentTime);
				const latestDate = new Date(latestTime);
				return currentDate > latestDate ? current : latest;
			});

			const date = new Date();
			
			// 格式化为"YYYY年MM月DD日 HH:mm"
			const year = date.getFullYear();
			const month = (date.getMonth() + 1).toString().padStart(2, '0');
			const day = date.getDate().toString().padStart(2, '0');
			const hours = date.getHours().toString().padStart(2, '0');
			const minutes = date.getMinutes().toString().padStart(2, '0');
			console.log(year,month,day,hours,minutes)
			return `${year}年${month}月${day}日 ${hours}:${minutes}最新投递`;
		};

		return {
			homeLineRef,
			homePieRef,
			homeBarRef,
			handleCardClick,
			handleTodoItemClick,
			handleFilterChange,
			handleCandidateClick,
			viewAllCandidates,
			getStatusText,
			getStatusClass,
			formatTime,
			passRate,
			getLatestApplicationTime,
			getPendingCandidatesCount,
			...toRefs(state),
		};
	},
});
</script>

<style scoped lang="scss">
$homeNavLengh: 8;
.home-container {
	padding: 15px;
	overflow: hidden;
	.home-card-one,
	.home-card-two,
	.home-card-three {
		.home-card-one-title{
			padding: 20px 0px;
			color:#808080;
			font-size: 14px;
			letter-spacing: 3px;
		}
		.home-card-item {
			width: 100%;
			height: 130px;
			border-radius: 16px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: hidden;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);
			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}
			&-icon {
				width: 70px;
				height: 70px;
				border-radius: 100%;
				flex-shrink: 1;
				i {
					color: var(--el-text-color-placeholder);
				}
			}
			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
			}
		}
	}
	.home-card-one {
		@for $i from 0 through 3 {
			.home-one-animation#{$i} {
				opacity: 0;
				animation-name: error-num;
				animation-duration: 0.5s;
				animation-fill-mode: forwards;
				animation-delay: calc($i/10) + s;
			}
		}
	}
	.home-card-two,
	.home-card-three {
		.home-card-item {
			height: 400px;
			width: 100%;
			overflow: hidden;
			.home-monitor {
				height: 100%;
				.flex-warp-item {
					width: 25%;
					height: 111px;
					display: flex;
					.flex-warp-item-box {
						margin: auto;
						text-align: center;
						color: var(--el-text-color-primary);
						display: flex;
						border-radius: 5px;
						background: var(--next-bg-color);
						cursor: pointer;
						transition: all 0.3s ease;
						&:hover {
							background: var(--el-color-primary-light-9);
							transition: all 0.3s ease;
						}
					}
					@for $i from 0 through $homeNavLengh {
						.home-animation#{$i} {
							opacity: 0;
							animation-name: error-num;
							animation-duration: 0.5s;
							animation-fill-mode: forwards;
							animation-delay: calc($i/10) + s;
						}
					}
				}
			}
		}
	}
	.home-right {
		.home-card-item {
			height: 600px;
			border-radius: 16px;
			transition: all ease 0.3s;
			padding: 20px;
			overflow: auto;
			background: var(--el-color-white);
			color: var(--el-text-color-primary);
			border: 1px solid var(--next-border-color-light);
			.home-card-item-content{
				display: flex;
			}
			::v-deep(.el-collapse-item__header){
				border: none;
			}
			::v-deep(.el-collapse-item__wrap){
				border: none;
			}
			::v-deep(.el-collapse-item__content){
				padding: 0;
			}
			&-title {
				font-size: 15px;
				font-weight: bold;
				height: 30px;
				border-bottom: 1px solid var(--next-border-color-light);
				padding-bottom: 10px;
				margin-bottom: 10px;
			}

			&:hover {
				box-shadow: 0 2px 12px var(--next-color-dark-hover);
				transition: all ease 0.3s;
			}
		}
	}

	// 响应式处理
	@media screen and (max-width: 1200px) {
		.el-col-18 {
			width: 100%;
		}
		.el-col-6 {
			width: 100%;
			margin-top: 15px;
		}
		.home-right .home-card-item {
			height: auto;
			min-height: 300px;
		}
	}
	
	.todo-list {
		padding: 10px 20px; 
		padding-left: 0;
		margin-top: 15px;
		margin-left: 10px;
		.todo-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 8px 0;
			border-bottom: 1px solid var(--next-border-color-light);
			transition: all 0.3s ease;
			background: #fff;
			
			// 可点击样式
			&.clickable {
				cursor: pointer;
				padding: 12px 16px;
				padding-left: 8px;
				border-radius: 8px;
				margin: 8px 0;
				// background: var(--el-fill-color-lighter);
				border-bottom: none;
				
				&:hover {
					background: #f2f2f2;
					transform: translateY(-2px);
					box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
				}
				
				&:active {
					transform: translateY(0);
				}
			}
			
			.todo-item-left {
				display: flex;
				align-items: flex-start;
				.item_icon{
					width: 43px;
					height: 40px;
					img{
						width:43px;
						height:40px;
					}
				
			}.todo-item-text{
					display: flex;
				flex-direction: column;
				align-items: flex-start;
				}
				.todo-tag {
					margin-right: 10px;
					font-weight: 500;
					// color: var(--el-color-primary);
				}
				.todo-text {
					font-size: 12px;
					color: var(--el-text-color-secondary);
					margin-top: 4px;
				}
			}
			
			.todo-item-right {
				.el-icon {
					// color: var(--el-color-primary);
					transition: transform 0.3s ease;
				}
			}
			
			&.clickable:hover .todo-item-right .el-icon {
				transform: translateX(4px);
			}
			
			&:last-child {
				border-bottom: none;
			}
			
			.todo-date {
				color: var(--el-text-color-secondary);
				font-size: 13px;
			}
			
			:deep(.el-checkbox__label) {
				color: var(--el-text-color-primary);
			}
		}
	}
	.score-list {
		padding: 10px 0;
		.score-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 8px 15px;
			margin: 5px 0;
			background: var(--el-fill-color-light);
			border-radius: 4px;
			
			// 可点击样式
			&.clickable-item {
				cursor: pointer;
				transition: all 0.3s ease;
				
				&:hover {
					background: var(--el-color-primary-light-9);
					transform: translateY(-1px);
					box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
				}
				
				&:active {
					transform: translateY(0);
				}
			}
			
			.score-name {
				font-size: 14px;
				color: var(--el-text-color-primary);
				flex: 0 0 auto; // 不伸缩，固定宽度
				
				&:nth-child(1) {
					width: 60px; // 姓名宽度
					text-align: left;
				}
				
				&:nth-child(2) {
					width: 30px; // 性别宽度
					text-align: center;
				}
				
				&:nth-child(3) {
					width: 80px; // 职位宽度
					text-align: left;
					overflow: hidden;
					text-overflow: ellipsis;
					white-space: nowrap;
				}
			}
			
			.score-value {
				font-size: 14px;
				color: var(--el-color-primary);
				font-weight: 500;
				width: 50px; // 分数宽度
				text-align: right;
				flex: 0 0 auto;
			}
		}
	}
	
	// 候选人列表样式
	.candidate-list {
		max-height: 300px;
		overflow-y: auto;
		
		.no-data {
			text-align: center;
			padding: 20px 0;
			color: var(--el-text-color-secondary);
		}
		
		.candidate-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 10px 5px;
			border-bottom: 1px solid var(--el-border-color-light);
			cursor: pointer;
			transition: all 0.3s ease;
			
			&:hover {
				background: var(--el-fill-color-light);
				transform: translateX(2px);
			}
			
			&:last-child {
				border-bottom: none;
			}
			
			.candidate-info {
				flex: 1;
				
				.candidate-name {
					font-size: 14px;
					font-weight: 500;
					color: var(--el-text-color-primary);
					margin-bottom: 4px;
				}
				
				.candidate-details {
					display: flex;
					gap: 8px;
					align-items: center;
					
					.candidate-position {
						font-size: 12px;
						color: var(--el-text-color-secondary);
					}
					
					.candidate-status {
						font-size: 12px;
						padding: 2px 6px;
						border-radius: 12px;
						
						&.status-pending {
							background: #e6f4ff;
							color: #1890ff;
						}
						
						&.status-interviewed {
							background: #fff7e6;
							color: #fa8c16;
						}
						
						&.status-hired {
							background: #f6ffed;
							color: #52c41a;
						}
						
						&.status-rejected {
							background: #fff2f0;
							color: #ff4d4f;
						}
						
						&.status-unknown {
							background: #f5f5f5;
							color: #999;
						}
					}
				}
			}
			
			.candidate-time {
				font-size: 12px;
				color: var(--el-text-color-secondary);
				white-space: nowrap;
			}
		}
		
		.more-candidates {
			text-align: center;
			padding: 10px 0;
			border-top: 1px solid var(--el-border-color-lighter);
			margin-top: 5px;
		}
	}
}
</style>
