<template>
	<div class="ads-summary-industry">
		<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.industry" clearable placeholder="请选择行业">
							<el-option label="电商" value="ecommerce" />
							<el-option label="教育" value="education" />
							<el-option label="金融" value="finance" />
							<el-option label="医疗" value="medical" />
							<el-option label="游戏" value="game" />
						</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="comparisonChartRef" 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.avgImpressions }}</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.avgClicks }}</div>
							</div>
						</el-card>
						<el-card shadow="hover" class="stats-card">
							<div class="stats-item">
								<div class="stats-label">行业平均CTR</div>
								<div class="stats-value">{{ totalStats.avgCtr }}%</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.avgConversions }}</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="industry" label="行业"><template #default="scope">{{ industryMap[scope.row.industry] }}</template></el-table-column>
						<el-table-column prop="impressions" label="曝光" />
						<el-table-column prop="clicks" label="点击" />
						<el-table-column prop="ctr" label="点击率"><template #default="scope">{{ scope.row.ctr }}%</template></el-table-column>
						<el-table-column prop="conversions" label="转化" />
						<el-table-column prop="conversionRate" label="转化率"><template #default="scope">{{ scope.row.conversionRate }}%</template></el-table-column>
						<el-table-column prop="cost" label="花费"><template #default="scope">¥{{ scope.row.cost }}</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, watch } from 'vue';
import * as echarts from 'echarts';

const industryMap = {
	ecommerce: '电商',
	education: '教育',
	finance: '金融',
	medical: '医疗',
	game: '游戏',
};

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

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 comparisonChartRef = ref();
let trendChart: echarts.ECharts | null = null;
let comparisonChart: echarts.ECharts | null = null;

const totalStats = reactive({
	avgImpressions: 0,
	avgClicks: 0,
	avgCtr: 0,
	avgConversions: 0,
});

const data = ref<any[]>([]);
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 = () => {
	const mockData = [];
	const industries = ['ecommerce', 'education', 'finance', 'medical', 'game'];
	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];
		industries.forEach(industry => {
			const impressions = Math.floor(Math.random() * 10000) + 5000;
			const clicks = Math.floor(impressions * (Math.random() * 0.05 + 0.01));
			const ctr = ((clicks / impressions) * 100).toFixed(2);
			const conversions = Math.floor(clicks * (Math.random() * 0.1 + 0.02));
			const conversionRate = ((conversions / clicks) * 100).toFixed(2);
			const cost = (Math.random() * 1000 + 100).toFixed(2);
			const roi = (Math.random() * 5 + 1).toFixed(2);

			mockData.push({
				date,
				industry,
				impressions,
				clicks,
				ctr,
				conversions,
				conversionRate,
				cost,
				roi,
			});
		});

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

	return mockData;
};

const calculateTotalStats = (data: any[]) => {
	if (data.length === 0) return;

	totalStats.avgImpressions = Math.round(data.reduce((sum, item) => sum + item.impressions, 0) / data.length);
	totalStats.avgClicks = Math.round(data.reduce((sum, item) => sum + item.clicks, 0) / data.length);
	totalStats.avgCtr = (data.reduce((sum, item) => sum + parseFloat(item.ctr), 0) / data.length).toFixed(2);
	totalStats.avgConversions = Math.round(data.reduce((sum, item) => sum + item.conversions, 0) / data.length);
};

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

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

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

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

	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: impressions,
			},
			{
				name: '点击',
				type: 'line',
				data: clicks,
			},
		],
	});
};

const initComparisonChart = (data: any[]) => {
	if (!comparisonChartRef.value) return;

	if (comparisonChart) comparisonChart.dispose();
	comparisonChart = echarts.init(comparisonChartRef.value);

	// 按行业分组数据
	const industryMap: { [key: string]: { ctr: number; conversionRate: number } } = {};
	data.forEach(item => {
		if (!industryMap[item.industry]) {
			industryMap[item.industry] = { ctr: 0, conversionRate: 0 };
		}
		industryMap[item.industry].ctr += parseFloat(item.ctr);
		industryMap[item.industry].conversionRate += parseFloat(item.conversionRate);
	});

	// 计算平均值
	const industryCount = Object.keys(industryMap).length;
	Object.keys(industryMap).forEach(industry => {
		industryMap[industry].ctr /= industryCount;
		industryMap[industry].conversionRate /= industryCount;
	});

	comparisonChart.setOption({
		title: {
			text: '行业对比',
			left: 'center',
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow',
			},
		},
		legend: {
			data: ['点击率', '转化率'],
			bottom: 0,
		},
		xAxis: {
			type: 'category',
			data: Object.keys(industryMap).map(industry => industryMap[industry as keyof typeof industryMap]),
		},
		yAxis: {
			type: 'value',
			name: '百分比',
			axisLabel: {
				formatter: '{value}%',
			},
		},
		series: [
			{
				name: '点击率',
				type: 'bar',
				data: Object.values(industryMap).map(item => item.ctr.toFixed(2)),
			},
			{
				name: '转化率',
				type: 'bar',
				data: Object.values(industryMap).map(item => item.conversionRate.toFixed(2)),
			},
		],
	});
};

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

const handleReset = () => {
	searchParams.dateRange = [];
	searchParams.industry = '';
	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();
		comparisonChart?.resize();
	});
});
</script>

<style scoped>
.ads-summary-industry {
	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>