<template>
	<div class="layout-padding">
		<div class="!overflow-auto pl-1">
			<!-- 顶部控制区域 -->
			<div class="mb-2 el-card  p-9">
				<div class="flex items-center mb-4">
					<Title title="页面访问路径" />
				</div>

				<div class="flex items-center justify-between space-x-4">
					<div class="flex items-center">
						<el-select v-model="formData.selectedChannelCompare" class="!w-[180px]" placeholder="版本选择">
							<el-option v-for="item in channelCompareOptions" :key="item.value" :label="item.label" :value="item.value" />
						</el-select>
						<el-button type="primary" class="ml-2"
							><el-icon class="mr-2"><Platform /></el-icon> 管理版本</el-button
						>
					</div>
					<div class="flex items-center">
						<el-button class="mr-2" type="primary" plain>昨日</el-button>
						<el-date-picker v-model="formData.time" class="w-[200px]" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" />
					</div>
				</div>
			</div>
			<div class="el-card  p-9">
				<div class="flex justify-between items-center mb-2">
					<Title left-line title="访问路径">
						<template #default>
							<el-popover class="box-item" placement="right" trigger="hover" width="600">
								<template #reference>
									<el-icon class="ml-1" style="color: #a4b8cf"><QuestionFilled /></el-icon>
								</template>
								<template #default>
									<div class="ant-popover-inner-content">
										<div style="padding: 8px 16px">
											<span
												class="um-vc-text"
												title="页面访问路径描述的是用户从打开到离开应用整个过程中每一步骤的页面访问、跳转情况。页面访问路径是全量统计。如果您在Android应用中使用了Fragment页面统计功能，这里的页面包括您指定统计的activity和Fragment。"
												style="color: rgb(0, 0, 0); font-size: 12px"
												>页面访问路径描述的是用户从打开到离开应用整个过程中每一步骤的页面访问、跳转情况。页面访问路径是全量统计。如果您在Android应用中使用了Fragment页面统计功能，这里的页面包括您指定统计的activity和Fragment。</span
											><span
												class="um-vc-text"
												title="页面的高度表现该页面被访问的次数，同一页面在不同步骤中用相同的颜色进行展示。"
												style="color: rgb(0, 0, 0); font-size: 12px"
												>页面的高度表现该页面被访问的次数，同一页面在不同步骤中用相同的颜色进行展示。</span
											><span
												class="um-vc-text"
												title="每一步骤中，页面节点按照访问次数大小从上往下排列，会显示每一步总的页面访问次数、占总访问次数比例以及前后两步之间的转化率。"
												style="color: rgb(0, 0, 0); font-size: 12px"
												>每一步骤中，页面节点按照访问次数大小从上往下排列，会显示每一步总的页面访问次数、占总访问次数比例以及前后两步之间的转化率。</span
											><span
												class="um-vc-text"
												title="如果页面的总会话数达到50W上限，或者单版本会话数达到10W上限，会进行日志抽样处理。"
												style="color: rgb(0, 0, 0); font-size: 12px"
												>如果页面的总会话数达到50W上限，或者单版本会话数达到10W上限，会进行日志抽样处理。</span
											>
										</div>
									</div>
								</template>
							</el-popover>
						</template>
					</Title>
					<div class="flex items-center">
						<el-radio-group v-model="formData.selectedType" class="!flex items-center">
							<el-radio-button label="1">描述</el-radio-button>
							<el-radio-button label="2">原名</el-radio-button>
						</el-radio-group>
						<el-button link class="ml-2" type="primary">编辑页面描述</el-button>
					</div>
				</div>
				<!-- 顶部统计方块 -->
				<div class="mb-3 flex items-stretch flex-wrap gap-4">
					<div class="min-w-[120px]">
						<div class="bg-[#f5f7fa] text-[12px] text-gray-500 px-3 py-1 rounded-t">第1步</div>
						<div class="border border-[#e5e7eb] rounded-b px-3 py-2 text-[#111827]">
							<div class="text-[20px] leading-6 font-medium">66,254</div>
						</div>
					</div>
					<div class="flex items-center text-[#3b82f6] text-[13px]">&gt;&nbsp;99.19%</div>
					<div class="min-w-[140px]">
						<div class="bg-[#f5f7fa] text-[12px] text-gray-500 px-3 py-1 rounded-t">第2步</div>
						<div class="border border-[#e5e7eb] rounded-b px-3 py-2 text-[#111827]">
							<div class="text-[20px] leading-6 font-medium">66,770<span class="text-[12px] text-gray-500">(99%)</span></div>
						</div>
					</div>
					<div class="flex items-center text-[#3b82f6] text-[13px]">&gt;&nbsp;0.00%</div>
					<div class="min-w-[140px]">
						<div class="bg-[#f5f7fa] text-[12px] text-gray-500 px-3 py-1 rounded-t">第3步</div>
						<div class="border border-[#e5e7eb] rounded-b px-3 py-2 text-[#111827]">
							<div class="text-[20px] leading-6 font-medium">156<span class="text-[12px] text-gray-500">(19%)</span></div>
						</div>
					</div>
					<div class="flex items-center text-[#3b82f6] text-[13px]">&gt;&nbsp;0.00%</div>
					<div class="min-w-[140px]">
						<div class="bg-[#f5f7fa] text-[12px] text-gray-500 px-3 py-1 rounded-t">结束</div>
						<div class="border border-[#e5e7eb] rounded-b px-3 py-2 text-[#111827]">
							<div class="text-[20px] leading-6 font-medium">156<span class="text-[12px] text-gray-500">(19%)</span></div>
						</div>
					</div>
				</div>
				<!-- 主图表区域 -->
				<div class="mb-4 overflow-x-auto">
					<div ref="mainChartRef" style="width: 100%; height: 600px"></div>
				</div>
			</div>
			<div class="el-card  p-9 mt-2">
				<div class="flex justify-between items-center mb-2">
					<Title left-line title="访问详情">
						<template #default>
							<el-popover class="box-item" placement="right" trigger="hover" width="500">
								<template #reference>
									<el-icon class="ml-1" style="color: #a4b8cf"><QuestionFilled /></el-icon>
								</template>
								<template #default>
									<div class="ant-popover-inner-content">
										<div style="padding: 8px 16px; ">
											<span
												class="um-vc-text"
												title="页面访问详情展示了用户使用每个页面的使用次数、访问时长以及跳转情况，这些数据可以帮助您分析每个页面的使用情况。"
												style="color: rgb(0, 0, 0); font-size: 12px"
												>页面访问详情展示了用户使用每个页面的使用次数、访问时长以及跳转情况，这些数据可以帮助您分析每个页面的使用情况。</span
											>
											<div>
												<span class="um-vc-text" title="访问次数：" style="color: rgb(33, 150, 243); font-size: 12px">访问次数：</span
												><span class="um-vc-text" title="用户进入当前页面的总次数" style="color: rgb(0, 0, 0); font-size: 12px"
													>用户进入当前页面的总次数</span
												>
											</div>
											<div>
												<span class="um-vc-text" title="访问次数占比：" style="color: rgb(33, 150, 243); font-size: 12px">访问次数占比：</span
												><span class="um-vc-text" title="当前页面访问次数占全部页面访问次数的比例" style="color: rgb(0, 0, 0); font-size: 12px"
													>当前页面访问次数占全部页面访问次数的比例</span
												>
											</div>
											<div>
												<span class="um-vc-text" title="平均访问时长：" style="color: rgb(33, 150, 243); font-size: 12px">平均访问时长：</span
												><span class="um-vc-text" title="用户每次进入当前页面的平均停留时长" style="color: rgb(0, 0, 0); font-size: 12px"
													>用户每次进入当前页面的平均停留时长</span
												>
											</div>
											<div>
												<span class="um-vc-text" title="访问时长占比：" style="color: rgb(33, 150, 243); font-size: 12px">访问时长占比：</span
												><span
													class="um-vc-text"
													title="用户在当前页面停留时间总和占用户在全体页面停留的时间总和的比例"
													style="color: rgb(0, 0, 0); font-size: 12px"
													>用户在当前页面停留时间总和占用户在全体页面停留的时间总和的比例</span
												>
											</div>
											<div>
												<span class="um-vc-text" title="跳出率：" style="color: rgb(33, 150, 243); font-size: 12px">跳出率：</span
												><span class="um-vc-text" title="用户从当前页面离开应用的比例" style="color: rgb(0, 0, 0); font-size: 12px"
													>用户从当前页面离开应用的比例</span
												>
											</div>
											<div>
												<span class="um-vc-text" title="跳转情况：" style="color: rgb(33, 150, 243); font-size: 12px">跳转情况：</span
												><span class="um-vc-text" title="用户从当前页面进入其他页面的概率分布情况" style="color: rgb(0, 0, 0); font-size: 12px"
													>用户从当前页面进入其他页面的概率分布情况</span
												>
											</div>
										</div>
									</div>
								</template>
							</el-popover>
						</template>
					</Title>
					<div class="flex items-center">
						
						<el-button link class="ml-2" type="primary">导出</el-button>
					</div>
				</div>
				<!-- 明细表格 -->
				<div class="mt-3">
				
					<el-table v-if="showDetail1" :data="pagedTableRows" border>
						<el-table-column prop="date" label="页面(Activity/Fragment)" align="center" min-width="140" />
						<el-table-column prop="hyyh" label="描述" align="center" min-width="140" />
						<el-table-column prop="hyyh" label="访问次数(占比)" align="center" min-width="140" />
						<el-table-column prop="hyyh" label="平均访问时长(占比)" align="center" min-width="140" />
						<el-table-column prop="ratio" label="跳出率" align="center" min-width="220" />
					</el-table>
					<div v-if="showDetail1" class="flex justify-end mt-2">
						<el-pagination
							v-model:current-page="currentPage"
							v-model:page-size="pageSize"
							background
							layout="total, prev, pager, next, sizes"
							:total="tableRows.length"
							:page-sizes="[5, 10, 20]"
						/>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, defineAsyncComponent, onBeforeUnmount } from 'vue';
import * as echarts from 'echarts';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();
const Title = defineAsyncComponent(() => import('/@/components/Title/index.vue'));
interface TableRow {
	date: string;
	newUsers: number;
	ratio: string;
}
const formData = ref<Record<string, any>>({
	selectedChannelCompare: '',
});
const channelCompareOptions = [
	{ label: '全部版本', value: '' },
	{ label: '1.0', value: '1.0' },
	{ label: '2.0', value: '2.0' },
];

// Sankey 图表
const mainChartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

function initSankey(): void {
	if (!mainChartRef.value) return;
	if (chartInstance) chartInstance.dispose();
	chartInstance = echarts.init(mainChartRef.value);

	// 左列来源节点（带计数）
	const leftNodes = [
		{ name: 'Ac_Search (13459)', itemStyle: { color: '#cfe8f3' } },
		{ name: 'Ac_CourseDetail (13459)', itemStyle: { color: '#dbeafe' } },
		{ name: 'Fr_SearchKeywords (13459)', itemStyle: { color: '#e9d5ff' } },
		{ name: 'Ac_Search (13459)#2', itemStyle: { color: '#e0f2fe' } },
		{ name: 'Ac_CourseDetail (13459)#2', itemStyle: { color: '#dcfce7' } },
		{ name: '其他 (13459)', itemStyle: { color: '#fef3c7' } },
	];

	// 中列节点（重复的视频播放目标）
	const middleNodes = Array.from({ length: 10 }).map((_, i) => ({
		name: `Ac_VideoPlay (13459)#${i + 1}`,
		itemStyle: { color: ['#e5e7eb', '#fde68a', '#bbf7d0', '#bfdbfe', '#fbcfe8'][i % 5] },
	}));

	// 右列汇总/结束节点
	const rightNodes = [
		{ name: 'Step3 总计 (156 / 49%)', itemStyle: { color: '#e5e7eb' } },
		{ name: 'Step4 结束 (158 / 50%)', itemStyle: { color: '#f3f4f6' } },
	];

	const nodes = [...leftNodes, ...middleNodes, ...rightNodes];

	// 构造链接：左 -> 中，多条细流；中 -> 右 少量
	const links: Array<{ source: string; target: string; value: number }> = [];
	const leftToMidValues = [3400, 3000, 2800, 2600, 2000, 1500];
	leftNodes.forEach((ln, li) => {
		middleNodes.forEach((mn, mi) => {
			// 让靠前的中间节点获得更多流量，形成图中“多条细灰线”效果
			const base = leftToMidValues[li % leftToMidValues.length];
			const decay = Math.max(0.1, 1 - mi * 0.08);
			const v = Math.round((base * decay) / 10); // 保持细流
			if (v > 0) links.push({ source: ln.name, target: mn.name, value: v });
		});
	});

	// 中 -> 右，较小比例收敛
	middleNodes.forEach((mn, idx) => {
		const v1 = 20 + Math.max(0, 60 - idx * 5);
		const v2 = 10 + Math.max(0, 40 - idx * 4);
		links.push({ source: mn.name, target: rightNodes[0].name, value: v1 });
		links.push({ source: mn.name, target: rightNodes[1].name, value: v2 });
	});

	const option: echarts.EChartsOption = {
		tooltip: {
			trigger: 'item',
			formatter: (p: any) => {
				if (p.dataType === 'edge') {
					return `${p.data.source} → ${p.data.target}<br/>${p.data.value}`;
				}
				return p.name;
			},
		},
		series: [
			{
				type: 'sankey',
				data: nodes,
				links,
				left: 60,
				right: 60,
				top: 6,
				bottom: 6,
				nodeWidth: 14,
				nodeGap: 6,
				nodeAlign: 'justify',
				layoutIterations: 0,
				draggable: false,
				label: {
					color: '#475569',
					fontSize: 11,
					formatter: (p: any) => {
						const m = /^(.*) \((\d+)\)/.exec(p.name);
						if (!m) return p.name;
						return `{name|${m[1]}} {count|(${m[2]})}`;
					},
					rich: {
						name: { color: '#374151', fontSize: 11 },
						count: { color: '#9ca3af', fontSize: 10 },
					},
				},
				itemStyle: { borderColor: '#dbe3ec', borderWidth: 1 },
				lineStyle: { color: '#cbd5e1', curveness: 0.35, opacity: 0.28 },
				emphasis: { focus: 'adjacency', lineStyle: { opacity: 0.6 } },
				levels: [
					{ depth: 0, itemStyle: { color: '#dbeafe' } },
					{ depth: 1, itemStyle: { color: '#f1f5f9' } },
					{ depth: 2, itemStyle: { color: '#f3f4f6' } },
				],
			},
		],
	};

	chartInstance.setOption(option);
}

// 表格相关（静态数据）
const tableRows = ref<TableRow[]>(
	Array.from({ length: 42 }).map((_, idx) => ({
		date: `2025-08-${String(11).padStart(2, '0')}`,
		newUsers: 727,
		hyyh: '115',
		ratio: '97.45%',
	}))
);

const currentPage = ref(1);
const pageSize = ref(5);
const pagedTableRows = computed(() => {
	const startIndex = (currentPage.value - 1) * pageSize.value;

	return tableRows.value.slice(startIndex, startIndex + pageSize.value);
});

onMounted(() => {
	setTimeout(() => {
		initSankey();
		window.addEventListener('resize', () => chartInstance && chartInstance.resize());
	}, 300);
});

onBeforeUnmount(() => {
	if (chartInstance) {
		chartInstance.dispose();
		chartInstance = null;
	}
});

// 展开/收起明细
const showDetail1 = ref(true);
</script>

<style lang="scss" scoped>
.el-card {
	background: white;
	border-radius: 8px;
	box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
:deep(.el-tabs__item.is-top.is-active) {
	color: #167af0;
	background-color: #e8f2fe;
}

.el-radio-button__inner {
	border-radius: 4px;
}

.el-radio-button:first-child .el-radio-button__inner {
	border-radius: 4px 0 0 4px;
}

.el-radio-button:last-child .el-radio-button__inner {
	border-radius: 0 4px 4px 0;
}
</style>
