<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('retainedUser.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>
												某段时间内的新增用户（活跃用户），经过一段时间后，又继续使用应用的被认作是留存用户；这部分用户占当时新增用户（活跃用户）的比例即是留存率。例如，5月份新增用户200，这200人在6月份启动过应用的有100人，7月份启动过应用的有80人，8月份启动过应用的有50人；则5月新增用户一个月后的留存率是50%，两个月后的留存率是40%，三个月后的留存率是25%。
											</p>
											<p>注：“活跃用户留存”仅支持查看2018年4月1日之后的留存情况</p>
										</div>
									</div>
								</template>
							</el-popover>
						</template>
					</Title>
					<div class="">
						<el-button type="primary">{{ t('activeUser.growth') }}</el-button>
						<el-button type="primary">{{ t('activeUser.ai') }}</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-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">
				<div class="border-b pb-4">
					<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>
						</div>

						<div class="flex items-center">
							<el-radio-group v-model="timeGranularity">
								<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>
							<el-radio-group v-model="timeGranularity" class="ml-2">
								<el-radio-button label="day">留存率</el-radio-button>
								<el-radio-button label="week">留存数</el-radio-button>
							</el-radio-group>
							<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> 某段时间内的新增用户（活跃用户），经过一段时间后，又继续使用应用的比例</p>
											<p><span class="highlight">留存数：</span> 某段时间内的新增用户（活跃用户），经过一段时间后，又继续使用应用的用户数</p>
										</div>
									</div>
								</template>
							</el-popover>
							<el-button class="ml-2">导出</el-button>
						</div>
					</div>

					<div class="relative">
						<el-table :data="currentTableData" border>
							<el-table-column
								v-for="column in currentTableColumns"
								:key="column.dataIndex"
								:prop="column.dataIndex"
								:label="column.title"
								:align="column.align"
								:min-width="column.width"
							>
								<template #default="scope">
									<span :class="getCellStyle(column.dataIndex, scope.row[column.dataIndex])">
										{{ scope.row[column.dataIndex] }}
									</span>
								</template>
							</el-table-column>
						</el-table>
					</div>
					<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 class="flex items-center justify-between mb-2 mt-4">
					<Title left-line :title="t('retainedUser.retained')" />
					<div class="flex items-center w-[140px]">
						<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>
					</div>
				</div>

				<div class="relative">
					<div ref="lineChartRef" style="width: 100%; height: 320px"></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;
	hyyh: string;
	ratio: string;
}

const dayColumns = ref<any[]>([
	{
		title: '时间',
		width: '140px',
		align: 'center',
		dataIndex: 'date',
	},
	{
		title: '新增用户',
		width: '120px',
		align: 'center',
		dataIndex: 'newUsers',
	},
	{
		title: '1天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day1',
	},
	{
		title: '2天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day2',
	},
	{
		title: '3天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day3',
	},
	{
		title: '4天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day4',
	},
	{
		title: '5天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day5',
	},
	{
		title: '6天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day6',
	},
	{
		title: '7天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day7',
	},
	{
		title: '14天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day14',
	},
	{
		title: '30天后',
		width: '100px',
		align: 'center',
		dataIndex: 'day30',
	},
]);

const weekColumns = ref<any[]>([
	{
		title: '时间',
		width: '140px',
		align: 'center',
		dataIndex: 'date',
	},
	{
		title: '新增用户',
		width: '120px',
		align: 'center',
		dataIndex: 'newUsers',
	},
	{
		title: '1周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week1',
	},
	{
		title: '2周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week2',
	},
	{
		title: '3周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week3',
	},
	{
		title: '4周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week4',
	},
	{
		title: '8周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week8',
	},
	{
		title: '12周后',
		width: '100px',
		align: 'center',
		dataIndex: 'week12',
	},
]);

const monthColumns = ref<any[]>([
	{
		title: '时间',
		width: '140px',
		align: 'center',
		dataIndex: 'date',
	},
	{
		title: '新增用户',
		width: '120px',
		align: 'center',
		dataIndex: 'newUsers',
	},
	{
		title: '1月后',
		width: '100px',
		align: 'center',
		dataIndex: 'month1',
	},
	{
		title: '2月后',
		width: '100px',
		align: 'center',
		dataIndex: 'month2',
	},
	{
		title: '3月后',
		width: '100px',
		align: 'center',
		dataIndex: 'month3',
	},
	{
		title: '6月后',
		width: '100px',
		align: 'center',
		dataIndex: 'month6',
	},
	{
		title: '12月后',
		width: '100px',
		align: 'center',
		dataIndex: 'month12',
	},
]);

// 动态表格数据
const dayTableData = ref<any[]>([
	{
		date: '2025-08-01',
		newUsers: 1000,
		day1: '45.2%',
		day2: '32.1%',
		day3: '28.5%',
		day4: '25.8%',
		day5: '23.4%',
		day6: '21.7%',
		day7: '20.3%',
		day14: '15.6%',
		day30: '12.8%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
		day4: '26.5%',
		day5: '24.2%',
		day6: '22.8%',
		day7: '21.5%',
		day14: '16.3%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
		day4: '26.5%',
		day5: '24.2%',
		day6: '22.8%',
		day7: '21.5%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
		day4: '26.5%',
		day5: '24.2%',
		day6: '22.8%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
		day4: '26.5%',
		day5: '24.2%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
		day4: '26.5%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
		day3: '29.1%',
	},
	{
		date: '2025-08-02',
		newUsers: 950,
		day1: '46.8%',
		day2: '33.2%',
	},
]);

const weekTableData = ref<any[]>([
	{
		date: '2025-08-01',
		newUsers: 7000,
		week1: '35.2%',
		week2: '28.1%',
		week3: '24.5%',
		week4: '22.8%',
		week8: '18.4%',
		week12: '15.7%',
	},
	{
		date: '2025-08-08',
		newUsers: 6800,
		week1: '36.8%',
		week2: '29.2%',
		week3: '25.1%',
		week4: '23.5%',
		week8: '19.2%',
		week12: '16.3%',
	},
]);

const monthTableData = ref<any[]>([
	{
		date: '2025-08-01',
		newUsers: 30000,
		month1: '25.2%',
		month2: '20.1%',
		month3: '18.5%',
		month6: '15.8%',
		month12: '12.4%',
	},
	{
		date: '2025-09-01',
		newUsers: 32000,
		month1: '26.8%',
		month2: '21.2%',
		month3: '19.1%',
		month6: '16.5%',
		month12: '13.2%',
	},
]);

// 当前选中的表格数据
const currentTableData = computed(() => {
	switch (timeGranularity.value) {
		case 'day':
			return dayTableData.value;
		case 'week':
			return weekTableData.value;
		case 'month':
			return monthTableData.value;
		default:
			return dayTableData.value;
	}
});

// 当前选中的表格列
const currentTableColumns = computed(() => {
	switch (timeGranularity.value) {
		case 'day':
			return dayColumns.value;
		case 'week':
			return weekColumns.value;
		case 'month':
			return monthColumns.value;
		default:
			return dayColumns.value;
	}
});

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(() => {
	setTimeout(() => {
		initLineChart();
	}, 500);
});

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 Title = defineAsyncComponent(() => import('/@/components/Title/index.vue'));

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

function getCellStyle(dataIndex: string, rowText: any) {
	if (dataIndex === 'date' || dataIndex === 'newUsers' || !rowText) {
		return '';
	}
	return 'flex justify-center items-center absolute left-0 right-0 top-0 bottom-0 bg-[#e6f7ff]';
}
</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>
