<template>
	<div class="layout-padding">
		<div class="!overflow-auto px-1">
			<div class="el-card p-2">
				<div class="flex justify-between">
					<Title :title="t('activations.analytics')">
						<template #default>
							<el-popover class="box-item" placement="right" trigger="hover" width="250">
								<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
													>打开应用视为启动。完全退出或后台运行超过30s后再次进入应用，视为一次新启动。开发过程中可以通过setSessionContinueMills来自定义两次启动的间隔，默认30s</span
												>
											</p>
											<p><span class="highlight">启动次数占比：</span><span>某日/周/月的启动次数占所选时间段总启动次数的比例</span></p>
											<p>
												<span
													>按天、周或月查看数据可进行版本、渠道的交叉筛选，小时数据最多展示7天并且不支持筛选。周区间定义为周日至次周周六。按周（按月）显示时，界面上用每周的周日（每个月的第一日）来代表该周（该月）</span
												>
											</p>
										</div>
									</div>
								</template>
							</el-popover>
						</template>
					</Title>
				</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-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-2">
				<div class="">
					<div class="flex items-center justify-between mb-2 mt-3">
						<div>
							<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('activations.version') }}</el-button>
						</div>

						<div class="flex items-center">
							<el-radio-group v-model="timeGranularity" size="small">
								<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 label="month">月</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="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>
							<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>
	</div>
</template>

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

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: 'compare' },
	{ label: '渠道A', value: 'a' },
	{ label: '渠道B', value: 'b' },
];

// 图表相关
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();
});

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);


</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>
