<template>
	<view>
		<view class="container" id="top1">
			<uni-row style="margin-bottom: 10rpx; margin-left: 30rpx; margin-right: 30rpx">
				<uni-col :span="24"><uni-title :title="'所选单位'" align="left" type="h4"></uni-title></uni-col>
			</uni-row>
			<uni-row style="margin-bottom: 20rpx; margin-left: 30rpx; margin-right: 30rpx">
				<uni-col :span="24">
					<trq-depart-select v-model="orgCode" returnCodeOrID="orgCode"
						@change="departChange"></trq-depart-select>
				</uni-col>
			</uni-row>
			<!-- 概览统计 -->
			<view class="stats-box" v-if="summary.total">
				<view class="stat-item">
					<text class="label">总人数</text>
					<text class="value">{{ summary.total }}</text>
				</view>
				<view class="stat-item">
					<text class="label">平均年龄</text>
					<text class="value">{{ summary.avgAge.toFixed(1) }}</text>
				</view>
			</view>
		</view>
		<!-- ECharts图表 -->
		<view class="chart-container">
			<l-echart ref="chart" @finished="initChart" />
		</view>

		<!-- 数据表格 -->

		<uni-row style="margin-top: 10px; margin-left: 30rpx; margin-right: 30rpx" v-if="tableData.length > 0">
			<uni-col :span="3">
				<view class="titleStyle">序号</view>
			</uni-col>
			<uni-col :span="5">
				<view class="titleStyle">姓名</view>
			</uni-col>
			<uni-col :span="5">
				<view class="titleStyle">性别</view>
			</uni-col>
			<uni-col :span="5">
				<view class="titleStyle">年龄</view>
			</uni-col>
			<uni-col :span="6">
				<view class="titleStyle">操作</view>
			</uni-col>
		</uni-row>

		<scroll-view scroll-y :style="{ height: bottomHeight + 'px' }">
			<uni-row style="margin-bottom: 10rpx; margin-left: 30rpx; margin-right: 30rpx">
				<view v-for="(item, index) in tableData">
					<uni-col :span="3">
						<view class="dataStyle">
							{{ index + 1 }}
						</view>
					</uni-col>
					<uni-col :span="5">
						<view class="dataStyle">
							{{ item.xm }}
						</view>
					</uni-col>
					<uni-col :span="5">
						<view class="dataStyle">
							{{ item.xb_dictText }}
						</view>
					</uni-col>
					<uni-col :span="5">
						<view class="dataStyle">
							{{ item.nl }}
						</view>
					</uni-col>
					<uni-col :span="6">
						<view class="dataStyle">
							<span @click="detail(item)" style="color: red;">详情</span>
							<!-- <button size="mini" type="primary" @click="detail(item)">详情</button> -->
						</view>
					</uni-col>
				</view>
			</uni-row>
		</scroll-view>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive,
		onMounted
	} from 'vue';
	import * as echarts from 'echarts';

	import {
		queryRenyuanByDepartID
	} from '@/api/renyuan.js';

	// 存储下方组件的高度
	const bottomHeight = ref(0);
	// 新增加载状态
	const isLoading = ref(false);
	const orgCode = ref('');
	const rawData = ref([]);
	const tableData = ref([]);
	const summary = reactive({
		total: 0,
		avgAge: 0
	});
	const chart = ref(null);
	const chartOption = ref({});
	const drillPopup = ref(null);
	const drillList = ref([]);
	const drillTitle = ref('');

	function detail(record) {
		// console.log(record)
		uni.navigateTo({
			url: '/pages/views/renliziyuan/renyuanxinxi/detail?data=' + encodeURIComponent(JSON.stringify(record))
		});
	}
	// 计算年龄initChart
	const calculateAge = (birthDate) => {
		const today = new Date();
		const birth = new Date(birthDate);
		let age = today.getFullYear() - birth.getFullYear();
		const monthDiff = today.getMonth() - birth.getMonth();
		if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
			age--;
		}
		return age;
	};
	// 加载数据
	const departChange = async (e, data) => {
		tableData.value = [];
		console.log(e);
		orgCode.value = e;
		try {
			// 显示加载状态

			isLoading.value = true;
			if (orgCode.value.length <= 6) {
				console.log(123242353);
				uni.showToast({
					title: '全厂数据较多，请选 下一层级...',
					icon: 'none',
					duration: 1000
				});
				isLoading.value = false;
				return;
			} else {
				uni.showLoading({
					title: '数据加载中...',
					mask: true
				});
			}

			let params = {
				pageSize: 3000,
				fields: ['xm', 'nl', 'xb', 'xb_dictText', 'orgCode', 'jcdw', 'jcxd', 'jcxdCode']
			};
			if (orgCode.value.length <= 9) {
				params.orgCode = orgCode.value;
			} else {
				params.jcxd_code = orgCode.value;
			}
			queryRenyuanByDepartID(params)
				.then((res) => {
					if (res.success) {
						processData(res.result.records);

						// 隐藏加载状态
						isLoading.value = false;
						uni.hideLoading();
					}
				})
				.catch((err) => {
					console.log(err);
					uni.showToast({
						title: '数据加载失败',
						icon: 'none',
						duration: 1000
					});
				});
		} catch (error) {
			console.log(error);
			uni.showToast({
				title: '数据加载失败',
				icon: 'none',
				duration: 1000
			});
		} finally {
			// 隐藏加载状态
			isLoading.value = false;
			uni.hideLoading();
		}
	};

	// 数据处理
	const processData = (data) => {
		// 添加年龄字段并过滤有效数据
		const validData = data
			.map((item) => ({
				...item,
				nl: calculateAge(item.cssj)
			}))
			.filter((item) => item.nl >= 21 && item.nl <= 64);
		// 计算概览数据
		summary.total = validData.length;
		summary.avgAge = validData.reduce((sum, cur) => sum + cur.nl, 0) / summary.total || 0;
		// 生成表格数据
		// tableData.value = validData;

		groupsData(validData);
		// 生成图表数据
		generateChartData(validData);
	};

	// 计算统计信息...
	const subOrgStaffs = ref({}); // 按下级单位存储所有人员
	const ageGroupStaffs = ref({}); // 按年龄段存储所有人员

	const groupsData = (data) => {
		// 清空旧数据
		subOrgStaffs.value = {};
		ageGroupStaffs.value = {};
		data.reduce((acc, cur) => {
			// console.log(cur)
			let subOrg = '';
			let ageRange = getAgeRange(cur.nl);
			// console.log(cur.orgCode, cur.jcxdCode)
			if (cur.orgCode <= 6) {
				subOrg = cur.orgCode;
			} else {
				subOrg = cur.jcxdCode;
			}

			// 存储到subOrgStaffs
			if (!subOrgStaffs.value[subOrg]) {
				subOrgStaffs.value[subOrg] = [];
			}
			subOrgStaffs.value[subOrg].push(cur);

			// 存储到ageGroupStaffs
			if (!ageGroupStaffs.value[ageRange]) {
				ageGroupStaffs.value[ageRange] = [];
			}
			ageGroupStaffs.value[ageRange].push(cur);
		});
	};

	// 新增年龄范围计算方法
	const getAgeRange = (age) => {
		const ranges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
		const index = Math.floor((age - 21) / 10);
		return ranges[index] || '其他';
	};

	// 修改后的显示人员列表方法
	const showStaffList = (subOrg, ageRange) => {
		// 从结构化数据中直接获取
		const targetStaffs = subOrgStaffs.value[subOrg].filter((staff) => getAgeRange(staff.nl) === ageRange);

		staffList.value = targetStaffs;
		popupTitle.value = `${subOrg} ${ageRange}人员列表（共${targetStaffs.length}人）`;
		popup.value.open();
	};

	// 新增获取指定单位人员的方法
	const getSubOrgStaffs = (subOrgCode) => {
		return subOrgStaffs.value[subOrgCode] || [];
	};

	// 新增获取指定年龄段人员的方法
	const getAgeGroupStaffs = (ageRange) => {
		return ageGroupStaffs.value[ageRange] || [];
	};

	// 生成图表数据（修改部分）
	const generateChartData = (data) => {
		// 按基层单位分组
		const ageRanges = ['21-30岁', '31-40岁', '41-50岁', '51-60岁', '61-64岁'];
		const jcdwGroups = data.reduce((acc, cur) => {
			if (!acc[cur.jcdw]) {
				acc[cur.jcdw] = {
					ageGroups: [0, 0, 0, 0, 0] // 21-30,31-40,41-50,51-60,61-64
				};
			}
			const ageGroup = Math.floor((cur.nl - 21) / 10);
			// console.log(ageGroup, cur.jcdw)
			if (ageGroup >= 0 && ageGroup <= 4) {
				acc[cur.jcdw].ageGroups[ageGroup]++;
			}
			return acc;
		}, {});

		// 生成分组柱状图配置
		const xData = Object.keys(jcdwGroups);

		const seriesData = ageRanges.map((range, index) => ({
			name: range,
			type: 'bar',
			data: xData.map((jcdw) => jcdwGroups[jcdw].ageGroups[index] || 0),
			itemStyle: {
				color: ['#5470C6', '#91CC75', '#FAC858', '#EE6666', '#73C0DE'][index]
			},
			// 显示数值标签
			label: {
				show: true,
				position: 'top'
			}
			// 设置柱宽为 20 像素
			// barWidth: 20
		}));
		chartOption.value = {
			title: {
				text: '人员年龄分组统计',
				padding: [0, 0, 0, 30]
			},
			toolbox: {
				padding: [0, 30, 0, 0],
				show: true,
				feature: {
					//工具配置项

					restore: {
						show: true //是否显示该工具
					},
					saveAsImage: {
						show: true //是否显示该工具
					}
				}
			},
			// tooltip: {
			// 	trigger: 'axis',
			// 	axisPointer: {
			// 		type: 'shadow',
			// 		label: {
			// 			show: false
			// 		}
			// 	}
			// },
			grid: {
				top: '15%',
				left: '4%',
				right: '4%',
				bottom: '10%',
				containLabel: true
			},
			legend: {
				data: ageRanges,
				itemGap: 5,
				padding: [0, 15, 0, 15],
				y: 'bottom',
				itemHeight: 8, //高
				itemWidth: 8, //宽
				type: 'scroll'
			},
			xAxis: {
				type: 'category',
				data: xData,
				axisLabel: {
					color: '#7F84B5',
					fontWeight: 300,
					interval: 0,
					rotate: 0
				},
				padding: [0, 10, 0, 10],
				axisTick: {
					show: false //刻度线
				},
				axisLine: {
					show: false //不显示坐标轴线
				}
			},
			yAxis: [{
				show: true,
				boundaryGap: false, //解决数据与线不对应问题
				type: 'value',
				// name: 'Budget (million USD)',
				// data: this.yList,
				minInterval: 1,
				axisLabel: {
					interval: 0
				},
				splitLine: {
					show: true,
					lineStyle: {
						//背景网格线
						type: 'dashed'
					}
				},

				axisTick: {
					show: true //刻度线
				},
				axisLine: {
					show: false //不显示坐标轴线
				}
			}],

			series: seriesData
		};

		// 初始化图表
		setTimeout(async () => {
			if (!chart.value) return;
			const myChart = await chart.value.init(echarts);
			myChart.setOption(chartOption.value);
			myChart.on('click', (params) => {
				console.log(params.seriesName);
				tableData.value = getAgeGroupStaffs(params.seriesName);
			});
		}, 300);

		// #ifdef APP
		getHeight();
		// #endif
	};

	onMounted(() => {
		// #ifdef APP
		getHeight();
		// #endif
	});
	// #ifdef APP

	const getHeight = () => {
		// 获取屏幕高度
		const systemInfo = uni.getSystemInfoSync();
		const screenHeight = systemInfo.screenHeight;
		// 创建选择器查询对象
		const query = uni.createSelectorQuery();
		// 获取上方组件的高度
		query
			.select('#top1')
			.boundingClientRect((rect1) => {
				// 计算上方组件高度总和
				const topComponentsHeight = rect1.height;
				// 计算下方组件的高度
				bottomHeight.value = screenHeight - topComponentsHeight - 415;
			})
			.exec();
	};

	// #endif
	// 初始化图表
	const initChart = () => {
		setTimeout(async () => {
			if (!chart.value) return;
			const myChart = await chart.value.init(echarts);
			myChart.setOption(chartOption.value);
		}, 300);
	};
</script>

<style scoped>
	.container {
		margin: 20, 20, 20, 20rpx;
	}

	.input-group {
		display: flex;
		gap: 20rpx;
		margin-bottom: 30rpx;
	}

	.input {
		flex: 1;
		border: 1rpx solid #ddd;
		padding: 15rpx;
		border-radius: 8rpx;
	}

	.query-btn {
		background: #007aff;
		color: white;
		padding: 0 40rpx;
		border-radius: 8rpx;
	}

	.stats-box {
		display: flex;
		justify-content: space-around;
		margin: 30rpx 0;
		padding: 20rpx;
		background: #f8f8f8;
		border-radius: 12rpx;
	}

	.stat-item {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.label {
		font-size: 24rpx;
		color: #666;
	}

	.value {
		font-size: 36rpx;
		font-weight: bold;
		color: #0000ff;
	}

	.chart-container {
		height: 400rpx;
		margin-top: 20rpx;
	}

	.titleStyle {
		font-size: 12px;
		color: #747474;
		line-height: 30px;
		height: 30px;
		background: #f2f9fc;
		text-align: center;
		vertical-align: middle;
		border-left: 1px solid #919191;
		border-bottom: 1px solid #919191;
	}

	/* 内容样式 */
	.dataStyle {
		max-font-size: 14px;
		/* 最大字体限制 */
		min-font-size: 10px;
		/* 最小字体限制 */
		font-size: 12px;
		color: #00007f;
		line-height: 30px;
		height: 30px;
		font-weight: 500;
		text-align: center;
		vertical-align: middle;
		border-bottom: 1px solid #919191;
		border-left: 1px solid #919191;
		text-overflow: ellipsis;
	}
</style>