<template>
	<div class="layout-padding">
		<div class="!overflow-auto px-1">
			<div class="el-card  p-9">
				<div class="flex justify-between">
					<Title :title="t('versionDistribution.analytics')" />
					<div class="">
						<el-button type="primary">{{ t('versionDistribution.aijb') }}</el-button>
					</div>
				</div>
				<div>
					<el-row shadow="hover" class="ml10 mt-2">
						<el-form :inline="true" :model="formData" @keyup.enter="query" ref="queryRef">
							<el-form-item>
								<el-date-picker v-model="formData.time" type="daterange" start-placeholder="开始时间" end-placeholder="结束时间" />
							</el-form-item>
							<el-form-item>
								<el-select v-model="selectedChannelCompare" class="w-[140px]" placeholder="全部版本">
									<el-option v-for="item in channelCompareOptions" :key="item.value" :label="item.label" :value="item.value" />
								</el-select>
							</el-form-item>
						</el-form>
					</el-row>
				</div>
			</div>
			<div class="mt-2 el-card  p-9">
				<Title left-line :title="selectedChannelCompare === ''? t('versionDistribution.allVersion') : selectedChannelCompare+t('versionDistribution.version')" >
					<template #default>
						<el-popover class="box-item" placement="right" trigger="hover" width="300">
							<template #reference>
								<el-icon class="ml-1" style="color: #a4b8cf"><QuestionFilled /></el-icon>
							</template>
							<template #default>
								<div class="ant-popover-inner-content">
									<div class="um-page-tips-content" style="line-height: 24px">
										<p><span>趋势图展示累计用户排名Top10版本的变化趋势</span></p>
										<p><span class="highlight">新增用户：</span><span>第一次启动应用的用户（以设备为判断标准）</span></p>
										<p>
											<span class="highlight">活跃用户：</span
											><span>启动过应用的用户（去重），启动过一次的用户即视为活跃用户，包括新用户与老用户</span>
										</p>
										<p>
											<span class="highlight">启动次数：</span
											><span
												>打开应用视为启动。完全退出或后台运行超过30s后再次进入应用，视为一次新启动。开发过程中可以通过setSessionContinueMills来自定义两次启动的间隔，默认30s</span
											>
										</p>
										<p>
											<span class="highlight">版本累计用户（%）：</span
											><span>截止到现在，该版本的累计用户（占累计用户全体的比例）；若该版本的用户升级到其他版本，则累计用户会减少</span>
										</p>
										<p><span class="highlight">升级用户：</span><span>从其他版本升级到该版本的用户（以设备为判断标准）</span></p>
										<p>
											<span
												>如果当日用户先启动老版本然后升级到新版本，分版本查看数据时，此用户在新老版本都会被算为活跃用户（按总体查看数据时不受影响）</span
											>
										</p>
									</div>
								</div>
							</template>
						</el-popover>
					</template>
				</Title>
				<div class="">
					<div class="flex items-center justify-between mb-2 mt-3">
						<div>
							<el-select v-if="selectedChannelCompare !== ''" v-model="selectedChannelCompare" class="w-[140px] ml-2" style="width: 140px" placeholder="全部频道">
								<el-option v-for="item in channelCompareOptions" :key="item.value" :label="item.label" :value="item.value" />
							</el-select>
							<el-select v-model="selectedChannelCompare" class="w-[140px] ml-2" style="width: 140px" 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">{{ t('versionDistribution.version') }}</el-button>
						</div>

						<div class="flex items-center">
							<el-radio-group v-model="timeGranularity">
								<el-radio-button label="hour">新增用户</el-radio-button>
								<el-radio-button label="day">活跃用户</el-radio-button>
								<el-radio-button label="week">启动次数</el-radio-button>
								<el-radio-button v-if="selectedChannelCompare !== ''" label="sjcs">升级用户</el-radio-button>
							</el-radio-group>
						</div>
					</div>

					<div class="relative">
						<div ref="lineChartRef" style="width: 100%; height: 320px"></div>
					</div>
				</div>

				<!-- 明细表格 -->
				<div class="mt-3">
					<div class="flex items-center justify-between mb-2">
						<div class="flex">
							<div v-if="selectedChannelCompare == ''" class="flex items-center">
								<el-radio-group v-model="timeGranularity">
									<el-radio-button label="hour">今日</el-radio-button>
									<el-radio-button label="day">作日 </el-radio-button>
								</el-radio-group>
							</div>
							<div class="text-base font-medium cursor-pointer select-none ml-3 items-center flex text-[#167AF0]" @click="showDetail1 = !showDetail1">
								{{ showDetail1 ? '收起明细数据' : '展开明细数据' }}
								<el-icon class="ml-2"><ArrowDown v-if="showDetail1" /> <ArrowUp v-else /> </el-icon>
							</div>
						</div>

						<div>
							<el-button>导出</el-button>
						</div>
					</div>
					<el-table v-if="showDetail1" :data="pagedTableRows" border>
						<el-table-column prop="date" 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-column>
					</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 v-if="selectedChannelCompare !== ''" class="mt-2 el-card  p-9">
				<div class="flex justify-between">
					<Title left-line :title="'版本用户来源'">
						<template #default>
							<el-popover class="box-item" placement="right" trigger="hover" width="300">
								<template #reference>
									<el-icon class="ml-1" style="color: #a4b8cf"><QuestionFilled /></el-icon>
								</template>
								<template #default>
									<div class="ant-popover-inner-content">
										<div class="um-page-tips-content" style="line-height: 24px">
											<p><span class="highlight">版本用户来源：</span><span>展示各版本用户的主要获取渠道分布</span></p>
											<p><span class="highlight">新增用户：</span><span>第一次启动应用的用户（以设备为判断标准）</span></p>
											<p><span class="highlight">升级用户比例：</span><span>从其他版本升级到该版本的用户占比</span></p>
										</div>
									</div>
								</template>
							</el-popover>
						</template>
					</Title>
				</div>
				<div class="flex items-center justify-between mt-3">
					<el-select v-model="channelDistribution" style="width: 180px" placeholder="新增用户渠道分布">
						<el-option label="新增用户渠道分布" value="distribution" />
					</el-select>
					<div class="ml-4">
						<el-radio-group v-model="timeRange">
							<el-radio-button label="yesterday">昨天</el-radio-button>
							<el-radio-button label="7days">过去7天</el-radio-button>
							<el-radio-button label="30days">过去30天</el-radio-button>
						</el-radio-group>
					</div>
				</div>

				<!-- 水平柱状图 -->
				<div class="mt-4">
					<div class="relative">
						<div ref="barChartRef" style="width: 100%; height: 200px"></div>
					</div>
				</div>

				<!-- 明细表格 -->
				<div class="mt-4">
					<div class="flex items-center justify-between mb-2">
						<div class="text-base font-medium cursor-pointer select-none ml-3 items-center flex text-[#167AF0]" @click="showDetail2 = !showDetail2">
							{{ showDetail2 ? '收起明细数据' : '展开明细数据' }} <el-icon class="ml-2"><ArrowDown v-if="showDetail2" /> <ArrowUp v-else /> </el-icon>
						</div>

						<div>
							<el-button>导出</el-button>
						</div>
					</div>
					<el-table v-if="showDetail2" :data="pagedSourceRows" border>
						<el-table-column prop="channel" label="渠道" min-width="140" />
						<el-table-column prop="newUsers" label="新增用户" min-width="140" />
						<el-table-column prop="upgradeRatio" label="升级用户比例" min-width="140" />
					</el-table>
					<div v-if="showDetail2" class="flex justify-end mt-3">
						<el-pagination
							v-model:current-page="sourcePage"
							v-model:page-size="sourcePageSize"
							background
							layout="total, prev, pager, next, sizes"
							:total="sourceRows.length"
							:page-sizes="[5, 10, 20]"
						/>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, defineAsyncComponent } from 'vue';
import * as echarts from 'echarts';
import { useI18n } from 'vue-i18n';
import { QuestionFilled } from '@element-plus/icons-vue';

const { t } = useI18n();

interface TableRow {
	date: string;
	newUsers: number;
	ratio: string;
}

const formData = ref<Record<string, any>>({});
const query = () => {
	console.log(formData.value);
};

const selectedChannelCompare = ref('');
const channelCompareOptions = [
	{ label: '全部版本', value: '' },
	{ label: '1.0', value: '1.0' },
	{ label: '2.0', value: '2.0' },
];

// 图表相关
const timeGranularity = ref<'hour' | 'day' | 'week' | 'month'>('week');
const lineChartRef = ref<HTMLDivElement | null>(null);
let chartInstance: echarts.ECharts | null = null;

const lineChartData = ref<Array<{ x: string; value: number }>>([
	{ x: '2025-07-01', value: 900 },
	{ x: '2025-07-08', value: 1000 },
	{ x: '2025-07-15', value: 1100 },
	{ x: '2025-07-22', value: 1000 },
	{ x: '2025-07-29', value: 600 },
	{ x: '2025-08-05', value: 300 },
	{ x: '2025-08-12', value: 250 },
	{ x: '2025-08-19', value: 200 },
	{ x: '2025-08-26', value: 650 },
	{ x: '2025-09-02', value: 950 },
	{ x: '2025-09-09', value: 900 },
	{ x: '2025-09-16', value: 120 },
]);

function initLineChart(): void {
	if (!lineChartRef.value) return;
	if (chartInstance) chartInstance.dispose();
	chartInstance = echarts.init(lineChartRef.value);
	const option: echarts.EChartsOption = {
		tooltip: { trigger: 'axis' },
		grid: { left: 40, right: 20, top: 20, bottom: 30 },
		xAxis: {
			type: 'category',
			data: lineChartData.value.map((d) => d.x),
			axisLine: { lineStyle: { color: '#e5e7eb' } },
			axisLabel: { color: '#6b7280' },
			axisTick: { alignWithLabel: true },
		},
		yAxis: {
			type: 'value',
			axisLine: { show: false },
			splitLine: { lineStyle: { color: '#f3f4f6' } },
			axisLabel: { color: '#6b7280' },
		},
		series: [
			{
				name: '新增人数',
				type: 'line',
				smooth: true,
				showSymbol: true,
				symbolSize: 6,
				itemStyle: { color: '#409EFF' },
				lineStyle: { color: '#409EFF' },
				data: lineChartData.value.map((d) => d.value),
			},
		],
	};
	chartInstance.setOption(option);
}

onMounted(() => {
	initLineChart();
	initBarChart();
});

watch(timeGranularity, () => {
	// 静态页面：仅重新渲染
	initLineChart();
});

// 表格相关（静态数据）
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);
});

const Title = defineAsyncComponent(() => import('/@/components/Title/index.vue'));

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

// 版本用户来源相关
const channelDistribution = ref('distribution');
const timeRange = ref('yesterday');
const barChartRef = ref<HTMLDivElement | null>(null);
let barChartInstance: echarts.ECharts | null = null;

const sourceRows = ref<Array<{ channel: string; newUsers: number; upgradeRatio: string }>>([
	{ channel: '渠道A', newUsers: 100, upgradeRatio: '10%' },
	{ channel: '渠道B', newUsers: 80, upgradeRatio: '15%' },
	{ channel: '渠道C', newUsers: 70, upgradeRatio: '20%' },
	{ channel: '渠道D', newUsers: 60, upgradeRatio: '25%' },
	{ channel: '渠道E', newUsers: 50, upgradeRatio: '30%' },
	{ channel: '渠道F', newUsers: 40, upgradeRatio: '35%' },
	{ channel: '渠道G', newUsers: 30, upgradeRatio: '40%' },
	{ channel: '渠道H', newUsers: 20, upgradeRatio: '45%' },
	{ channel: '渠道I', newUsers: 10, upgradeRatio: '50%' },
	{ channel: '渠道J', newUsers: 5, upgradeRatio: '55%' },
]);

function initBarChart(): void {
	if (!barChartRef.value) return;
	if (barChartInstance) barChartInstance.dispose();
	barChartInstance = echarts.init(barChartRef.value);
	const option: echarts.EChartsOption = {
		tooltip: { trigger: 'axis' },
		grid: { left: 40, right: 20, top: 20, bottom: 30 },
		xAxis: {
			type: 'value',
			axisLine: { show: false },
			splitLine: { lineStyle: { color: '#f3f4f6' } },
			axisLabel: { color: '#6b7280' },
		},
		yAxis: {
			type: 'category',
			data: sourceRows.value.map((d) => d.channel),
			axisLine: { lineStyle: { color: '#e5e7eb' } },
			axisLabel: { color: '#6b7280' },
			axisTick: { alignWithLabel: true },
		},
		series: [
			{
				name: '新增用户',
				type: 'bar',
				barWidth: '60%',
				itemStyle: { color: '#409EFF' },
				data: sourceRows.value.map((d) => d.newUsers),
			},
		],
	};
	barChartInstance.setOption(option);
}

onMounted(() => {
	initBarChart();
});

watch(timeRange, () => {
	// 静态页面：仅重新渲染
	initBarChart();
});

watch(selectedChannelCompare, () => {
	// 静态页面：仅重新渲染
	initBarChart();
	initLineChart();
});

const sourcePage = ref(1);
const sourcePageSize = ref(5);
const pagedSourceRows = computed(() => {
	const startIndex = (sourcePage.value - 1) * sourcePageSize.value;

	return sourceRows.value.slice(startIndex, startIndex + sourcePageSize.value);
});

const showDetail2 = ref(true);
</script>
 
<style lang="scss" scoped>
.highlight {
	color: #2196f3;
}
.el-form-item--default {
	margin-bottom: 0;
}
.el-form.el-form--inline .el-form-item--default.el-form-item:last-of-type,
.el-form.el-form--inline .el-form-item--small.el-form-item:last-of-type {
	margin-bottom: 0 !important;
}
</style>
