<template>
	<div class="trade-operation-stats-anchor">
		<el-card shadow="hover">
			<template #header><div class="card-header"><span>主播维度统计</span></div></template>
			<div class="chart-container">
				<el-card>
					<template #header><div class="card-header">主播销售趋势 - {{ currentAnchorName }}</div></template>
					<div ref="salesChartRef" class="chart"></div>
				</el-card>
			</div>
			<div class="anchor-ranking">
				<el-card>
					<template #header><div class="card-header">主播业绩排行</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" /></el-form-item>
							<el-form-item label="主播"><el-input v-model="searchParams.anchorName" placeholder="请输入主播名称" clearable @keyup.enter="handleSearch" /></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>
					<el-table ref="anchorTableRef" :data="pagedAnchorList" style="width: 100%" row-key="anchorName" highlight-current-row @row-click="handleAnchorClick">
						<el-table-column prop="rank" label="排名" width="80" />
						<el-table-column prop="anchorName" label="主播名称" />
						<el-table-column prop="sales" label="销售额" />
						<el-table-column prop="orderCount" label="订单数" />
						<el-table-column prop="signRate" label="签收率" />
						<el-table-column prop="repurchaseRate" label="复购率" />
						<el-table-column label="操作" width="120">
							<template #default="scope">
								<el-button type="primary" link @click.stop="handleAnchorSelect(scope.row.anchorName)">查看趋势</el-button>
							</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="handleSizeChange" @current-change="handleCurrentChange" />
					</div>
				</el-card>
			</div>
		</el-card>
	</div>
</template>

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

interface AnchorItem {
	rank: number;
	anchorName: string;
	sales: number;
	orderCount: number;
	signRate: string;
	repurchaseRate: string;
}

interface AnchorTrend {
	anchorName: string;
	dates: string[];
	sales: number[];
	orders: number[];
}

const searchParams = reactive({ dateRange: [], anchorName: '' });
const anchorList = ref<AnchorItem[]>([]);
const anchorTableRef = ref();
const selectedAnchorName = ref('');
const filteredAnchorList = computed(() => {
	const keyword = searchParams.anchorName.trim().toLowerCase();
	if (!keyword) return anchorList.value;
	return anchorList.value.filter((item) => item.anchorName.toLowerCase().includes(keyword));
});
const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 });
const pagedAnchorList = computed(() =>
	filteredAnchorList.value.slice((pagination.currentPage - 1) * pagination.pageSize, pagination.currentPage * pagination.pageSize)
);
const currentAnchorName = computed(() => selectedAnchorName.value || filteredAnchorList.value[0]?.anchorName || '暂无主播');
const salesChartRef = ref();
let salesChart: echarts.ECharts | null = null;

const getMockAnchorList = () => [
	{ rank: 1, anchorName: '主播A', sales: 528000, orderCount: 1250, signRate: '98.5%', repurchaseRate: '32.8%' },
	{ rank: 2, anchorName: '主播B', sales: 465000, orderCount: 1080, signRate: '97.2%', repurchaseRate: '28.5%' },
	{ rank: 3, anchorName: '主播C', sales: 389000, orderCount: 920, signRate: '99.1%', repurchaseRate: '35.2%' },
	{ rank: 4, anchorName: '主播D', sales: 320000, orderCount: 780, signRate: '96.8%', repurchaseRate: '25.3%' },
	{ rank: 5, anchorName: '主播E', sales: 285000, orderCount: 690, signRate: '98.2%', repurchaseRate: '30.1%' },
	{ rank: 6, anchorName: '主播F', sales: 256000, orderCount: 620, signRate: '97.5%', repurchaseRate: '27.8%' },
	{ rank: 7, anchorName: '主播G', sales: 210000, orderCount: 510, signRate: '96.3%', repurchaseRate: '24.5%' },
	{ rank: 8, anchorName: '主播H', sales: 185000, orderCount: 450, signRate: '98.8%', repurchaseRate: '31.2%' },
	{ rank: 9, anchorName: '主播I', sales: 162000, orderCount: 390, signRate: '97.9%', repurchaseRate: '29.5%' },
	{ rank: 10, anchorName: '主播J', sales: 145000, orderCount: 350, signRate: '96.7%', repurchaseRate: '26.8%' },
];
const getTrendLabels = () => {
	if (Array.isArray(searchParams.dateRange) && searchParams.dateRange.length === 2) {
		const [startText, endText] = searchParams.dateRange as string[];
		const start = new Date(`${startText}T00:00:00`);
		const end = new Date(`${endText}T00:00:00`);
		const labels: string[] = [];
		const cursor = new Date(start.getTime());
		while (cursor <= end && labels.length < 31) {
			labels.push(`${cursor.getMonth() + 1}/${cursor.getDate()}`);
			cursor.setDate(cursor.getDate() + 1);
		}
		return labels;
	}
	return ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
};
const getMockSalesTrend = (anchorName: string): AnchorTrend => {
	const labels = getTrendLabels();
	const anchorIndex = Math.max(anchorList.value.findIndex((item) => item.anchorName === anchorName), 0);
	const baseSales = 120000 + anchorIndex * 26000;
	const baseOrders = 260 + anchorIndex * 36;
	return {
		anchorName,
		dates: labels,
		sales: labels.map((_, index) => {
			const trendFactor = 1 + index * 0.06;
			const fluctuation = 0.9 + ((index + anchorIndex) % 4) * 0.08;
			return Math.round(baseSales * trendFactor * fluctuation);
		}),
		orders: labels.map((_, index) => {
			const trendFactor = 1 + index * 0.045;
			const fluctuation = 0.92 + ((index + anchorIndex + 1) % 5) * 0.05;
			return Math.round(baseOrders * trendFactor * fluctuation);
		}),
	};
};
const setCurrentAnchorRow = async () => {
	await nextTick();
	const currentRow = pagedAnchorList.value.find((item) => item.anchorName === selectedAnchorName.value) || null;
	anchorTableRef.value?.setCurrentRow(currentRow);
};
const syncSelectedAnchor = () => {
	const hasSelectedAnchor = filteredAnchorList.value.some((item) => item.anchorName === selectedAnchorName.value);
	if (!hasSelectedAnchor) {
		selectedAnchorName.value = filteredAnchorList.value[0]?.anchorName || '';
	}
};
const updateChartByAnchor = (anchorName: string) => {
	selectedAnchorName.value = anchorName;
	initSalesChart(getMockSalesTrend(anchorName));
	setCurrentAnchorRow();
};
const handleSearch = () => {
	if (!anchorList.value.length) {
		anchorList.value = getMockAnchorList();
	}
	pagination.currentPage = 1;
	pagination.total = filteredAnchorList.value.length;
	syncSelectedAnchor();
	if (selectedAnchorName.value) {
		updateChartByAnchor(selectedAnchorName.value);
	} else {
		initSalesChart(null);
		setCurrentAnchorRow();
	}
};
const handleReset = () => {
	searchParams.dateRange = [];
	searchParams.anchorName = '';
	selectedAnchorName.value = anchorList.value[0]?.anchorName || '';
	pagination.currentPage = 1;
	pagination.pageSize = 10;
	handleSearch();
};
const handleAnchorClick = (row: AnchorItem) => {
	updateChartByAnchor(row.anchorName);
};
const handleAnchorSelect = (anchorName: string) => {
	updateChartByAnchor(anchorName);
};
const handleSizeChange = (size: number) => {
	pagination.pageSize = size;
	pagination.currentPage = 1;
	setCurrentAnchorRow();
};
const handleCurrentChange = (current: number) => {
	pagination.currentPage = current;
	setCurrentAnchorRow();
};

const initSalesChart = (salesTrend: AnchorTrend | null) => {
	if (!salesChartRef.value) return;
	if (salesChart) salesChart.dispose();
	salesChart = echarts.init(salesChartRef.value);
	const xAxisData = salesTrend?.dates || [];
	const isSingle = xAxisData.length <= 1;
	salesChart.setOption({
		tooltip: { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } },
		legend: { data: salesTrend ? ['销售额', '订单数'] : [] },
		grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true },
		xAxis: { type: 'category', boundaryGap: isSingle, data: xAxisData },
		yAxis: [
			{ type: 'value', name: '销售额', position: 'left' },
			{ type: 'value', name: '订单数', position: 'right' },
		],
		series: salesTrend
			? [
					{ name: '销售额', type: 'line', data: salesTrend.sales, smooth: true, showSymbol: true, symbolSize: isSingle ? 10 : 6 },
					{ name: '订单数', type: 'line', yAxisIndex: 1, data: salesTrend.orders, smooth: true, showSymbol: true, symbolSize: isSingle ? 10 : 6 },
				]
			: [],
	});
};

watch(
	() => filteredAnchorList.value.length,
	(length) => {
		pagination.total = length;
		const maxPage = Math.max(1, Math.ceil(length / pagination.pageSize));
		if (pagination.currentPage > maxPage) {
			pagination.currentPage = maxPage;
		}
		setCurrentAnchorRow();
	}
);

onMounted(() => {
	anchorList.value = getMockAnchorList();
	selectedAnchorName.value = anchorList.value[0]?.anchorName || '';
	handleSearch();
	window.addEventListener('resize', () => salesChart?.resize());
});
</script>

<style scoped>
.trade-operation-stats-anchor { padding: 20px; }
.card-header { display: flex; align-items: center; justify-content: space-between; font-size: 16px; font-weight: 600; }
.search-container { margin-bottom: 16px; }
.search-form { display: flex; align-items: center; flex-wrap: wrap; }
.search-form :deep(.el-form-item) { margin-right: 12px; margin-bottom: 12px; }
.anchor-ranking { margin-bottom: 20px; }
.pagination-container { margin-top: 16px; display: flex; justify-content: flex-end; }
.chart-container { margin: 0 0 20px; }
.chart { width: 100%; height: 400px; }
</style>
