<template>
	<div class="ads-summary-new-customer">
		<el-card shadow="hover">
			<template #header
				><div class="card-header"><span>真新客监控</span></div></template
			>
			<div class="search-container">
				<el-form :model="searchParams" :inline="true" class="search-form">
					<el-form-item label="时间范围">
						<el-date-picker
							v-model="searchParams.dateRange"
							type="daterange"
							range-separator="至"
							start-placeholder="开始日期"
							end-placeholder="结束日期"
							value-format="YYYY-MM-DD"
							:shortcuts="dateShortcuts"
						/>
					</el-form-item>
					<el-form-item label="渠道">
						<el-select v-model="searchParams.channel" clearable placeholder="请选择渠道">
							<el-option label="搜索广告" value="search" />
							<el-option label="社交媒体" value="social" />
							<el-option label="信息流" value="feed" />
							<el-option label="其他" value="other" />
						</el-select>
					</el-form-item>
					<el-form-item>
						<el-button type="primary" @click="handleSearch">查询</el-button>
						<el-button @click="handleReset">重置</el-button>
					</el-form-item>
				</el-form>
			</div>
			<div class="chart-container">
				<el-row :gutter="20">
					<el-col :span="12">
						<el-card>
							<template #header><div class="card-header">新客户趋势</div></template>
							<div ref="trendChartRef" class="chart"></div>
						</el-card>
					</el-col>
					<el-col :span="12">
						<el-card>
							<template #header><div class="card-header">渠道分布</div></template>
							<div ref="channelChartRef" class="chart"></div>
						</el-card>
					</el-col>
				</el-row>
			</div>
			<div class="data-container">
				<el-card>
					<template #header><div class="card-header">数据概览</div></template>
					<div class="stats-grid">
						<el-card shadow="hover" class="stats-card">
							<div class="stats-item">
								<div class="stats-label">新客户数</div>
								<div class="stats-value">{{ totalStats.newCustomers }}</div>
							</div>
						</el-card>
						<el-card shadow="hover" class="stats-card">
							<div class="stats-item">
								<div class="stats-label">获客成本</div>
								<div class="stats-value">¥{{ totalStats.acquisitionCost }}</div>
							</div>
						</el-card>
						<el-card shadow="hover" class="stats-card">
							<div class="stats-item">
								<div class="stats-label">新客转化率</div>
								<div class="stats-value">{{ totalStats.newCustomerConversionRate }}%</div>
							</div>
						</el-card>
						<el-card shadow="hover" class="stats-card">
							<div class="stats-item">
								<div class="stats-label">新客留存率</div>
								<div class="stats-value">{{ totalStats.newCustomerRetentionRate }}%</div>
							</div>
						</el-card>
					</div>
				</el-card>
			</div>
			<div class="table-container">
				<el-card>
					<template #header><div class="card-header">新客户明细</div></template>
					<el-table :data="pagedData" style="width: 100%">
						<el-table-column prop="date" label="日期" />
						<el-table-column prop="channel" label="渠道"
							><template #default="scope">{{ channelMap[scope.row.channel as keyof typeof channelMap] }}</template></el-table-column
						>
						<el-table-column prop="newCustomers" label="新客户数" />
						<el-table-column prop="acquisitionCost" label="获客成本"
							><template #default="scope">¥{{ scope.row.acquisitionCost }}</template></el-table-column
						>
						<el-table-column prop="conversionRate" label="转化率"
							><template #default="scope">{{ scope.row.conversionRate }}%</template></el-table-column
						>
						<el-table-column prop="retentionRate" label="留存率"
							><template #default="scope">{{ scope.row.retentionRate }}%</template></el-table-column
						>
						<el-table-column prop="roi" label="ROI"
							><template #default="scope">{{ scope.row.roi }}</template></el-table-column
						>
					</el-table>
					<div class="pagination-container">
						<el-pagination
							v-model:current-page="pagination.currentPage"
							v-model:page-size="pagination.pageSize"
							:page-sizes="[10, 20, 50, 100]"
							layout="total, sizes, prev, pager, next, jumper"
							:total="pagination.total"
							@size-change="handlePageSizeChange"
							@current-change="handlePageChange"
						/>
					</div>
				</el-card>
			</div>
		</el-card>
	</div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import * as echarts from 'echarts';

interface NewCustomerData {
	date: string;
	channel: string;
	newCustomers: number;
	acquisitionCost: string;
	conversionRate: string;
	retentionRate: string;
	roi: string;
}

const channelMap = {
	search: '搜索广告',
	social: '社交媒体',
	feed: '信息流',
	other: '其他',
};

const searchParams = reactive({
	dateRange: [],
	channel: '',
});

const dateShortcuts = [
	{
		text: '最近7天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
			return [start, end];
		},
	},
	{
		text: '最近30天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
			return [start, end];
		},
	},
	{
		text: '最近90天',
		value: () => {
			const end = new Date();
			const start = new Date();
			start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
			return [start, end];
		},
	},
];

const trendChartRef = ref();
const channelChartRef = ref();
let trendChart: echarts.ECharts | null = null;
let channelChart: echarts.ECharts | null = null;

const totalStats = reactive({
	newCustomers: 0,
	acquisitionCost: '0',
	newCustomerConversionRate: 0,
	newCustomerRetentionRate: 0,
});

const data = ref<NewCustomerData[]>([]);
const pagination = reactive({
	currentPage: 1,
	pageSize: 10,
	total: 0,
});

const pagedData = computed(() => {
	const start = (pagination.currentPage - 1) * pagination.pageSize;
	const end = start + pagination.pageSize;
	return data.value.slice(start, end);
});

const getMockData = (): NewCustomerData[] => {
	const mockData: NewCustomerData[] = [];
	const channels: (keyof typeof channelMap)[] = ['search', 'social', 'feed', 'other'];
	const end = new Date();
	const start = new Date();
	start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);

	let current = new Date(start);
	while (current <= end) {
		const date = current.toISOString().split('T')[0];
		channels.forEach((channel) => {
			const newCustomers = Math.floor(Math.random() * 100) + 10;
			const acquisitionCost = (Math.random() * 500 + 50).toFixed(2);
			const conversionRate = (Math.random() * 5 + 1).toFixed(2);
			const retentionRate = (Math.random() * 30 + 20).toFixed(2);
			const roi = (Math.random() * 3 + 0.5).toFixed(2);

			mockData.push({
				date,
				channel,
				newCustomers,
				acquisitionCost,
				conversionRate,
				retentionRate,
				roi,
			});
		});

		current.setDate(current.getDate() + 1);
	}

	return mockData;
};

const calculateTotalStats = (data: NewCustomerData[]) => {
	totalStats.newCustomers = data.reduce((sum, item) => sum + item.newCustomers, 0);
	totalStats.acquisitionCost = data.reduce((sum, item) => sum + parseFloat(item.acquisitionCost), 0).toFixed(2);
	totalStats.newCustomerConversionRate = data.reduce((sum, item) => sum + parseFloat(item.conversionRate), 0) / data.length;
	totalStats.newCustomerRetentionRate = data.reduce((sum, item) => sum + parseFloat(item.retentionRate), 0) / data.length;
};

const initTrendChart = (data: NewCustomerData[]) => {
	if (!trendChartRef.value) return;

	if (trendChart) trendChart.dispose();
	trendChart = echarts.init(trendChartRef.value);

	// 按日期分组数据
	const dateMap: { [key: string]: number } = {};
	data.forEach((item) => {
		if (!dateMap[item.date]) {
			dateMap[item.date] = 0;
		}
		dateMap[item.date] += item.newCustomers;
	});

	const dates = Object.keys(dateMap).sort();
	const newCustomers = dates.map((date) => dateMap[date]);

	trendChart.setOption({
		title: {
			text: '新客户趋势',
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
		},
		legend: {
			data: ['新客户数'],
			bottom: 0,
		},
		xAxis: {
			type: 'category',
			data: dates,
			axisLabel: {
				rotate: 45,
			},
		},
		yAxis: {
			type: 'value',
			name: '新客户数',
		},
		series: [
			{
				name: '新客户数',
				type: 'line',
				data: newCustomers,
				areaStyle: {},
			},
		],
	});
};

const initChannelChart = (data: NewCustomerData[]) => {
	if (!channelChartRef.value) return;

	if (channelChart) channelChart.dispose();
	channelChart = echarts.init(channelChartRef.value);

	// 按渠道分组数据
	const channelDataMap: { [key: string]: number } = {};
	data.forEach((item) => {
		if (!channelDataMap[item.channel]) {
			channelDataMap[item.channel] = 0;
		}
		channelDataMap[item.channel] += item.newCustomers;
	});

	channelChart.setOption({
		title: {
			text: '渠道分布',
			left: 'center',
		},
		tooltip: {
			trigger: 'item',
			formatter: '{b}: {c} ({d}%)',
		},
		legend: {
			orient: 'vertical',
			left: 'left',
			data: Object.values(channelMap),
		},
		series: [
			{
				name: '渠道',
				type: 'pie',
				radius: '50%',
				data: Object.entries(channelDataMap).map(([channel, value]) => ({
					value,
					name: channelMap[channel as keyof typeof channelMap],
				})),
				emphasis: {
					itemStyle: {
						shadowBlur: 10,
						shadowOffsetX: 0,
						shadowColor: 'rgba(0, 0, 0, 0.5)',
					},
				},
			},
		],
	});
};

const handleSearch = () => {
	data.value = getMockData();
	pagination.total = data.value.length;
	calculateTotalStats(data.value);
	initTrendChart(data.value);
	initChannelChart(data.value);
};

const handleReset = () => {
	searchParams.dateRange = [];
	searchParams.channel = '';
	pagination.currentPage = 1;
	handleSearch();
};

const handlePageSizeChange = (size: number) => {
	pagination.pageSize = size;
	pagination.currentPage = 1;
};

const handlePageChange = (page: number) => {
	pagination.currentPage = page;
};

onMounted(() => {
	handleSearch();
	window.addEventListener('resize', () => {
		trendChart?.resize();
		channelChart?.resize();
	});
});
</script>

<style scoped>
.ads-summary-new-customer {
	padding: 20px;
}

.card-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	font-size: 16px;
	font-weight: 600;
}

.search-container {
	margin-bottom: 20px;
}

.search-form {
	display: flex;
	align-items: center;
	flex-wrap: wrap;
}

.search-form :deep(.el-form-item) {
	margin-right: 12px;
	margin-bottom: 12px;
}

.chart-container {
	margin-bottom: 20px;
}

.chart {
	width: 100%;
	height: 300px;
}

.data-container {
	margin-bottom: 20px;
}

.stats-grid {
	display: grid;
	grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
	gap: 16px;
}

.stats-card {
	text-align: center;
}

.stats-item {
	padding: 10px;
}

.stats-label {
	font-size: 14px;
	color: #606266;
	margin-bottom: 8px;
}

.stats-value {
	font-size: 24px;
	font-weight: 600;
	color: #303133;
}

.table-container {
	margin-top: 20px;
}

.pagination-container {
	margin-top: 16px;
	display: flex;
	justify-content: flex-end;
}
</style>
