import { PageContainer } from '@/components';
import { business } from '@/services';
import { exportExpenseStatisticsExcel } from '@/utils/exportExcel';
import {
	ArrowDownOutlined,
	ArrowUpOutlined,
	DownOutlined,
	PlusOutlined,
} from '@ant-design/icons';
import {
	Badge,
	Button,
	Card,
	Col,
	Collapse,
	DatePicker,
	Empty,
	List,
	message,
	Row,
	Space,
	Statistic,
	Tag,
} from 'antd';
import type { Dayjs } from 'dayjs';
import dayjs from 'dayjs';
import { useEffect, useMemo, useState } from 'react';

const { RangePicker } = DatePicker;

type StatisticsData = {
	totalVehicles: number;
	totalProvision: number;
	totalExpense: number;
	dailyProfit: number;
	dealerStatistics: Map<string, { vehicleCount: number; totalAmount: number }>;
	costCategoryStatistics: Map<string, number>;
};

export default function Page() {
	const [dateRange, setDateRange] = useState<[Dayjs, Dayjs]>([
		dayjs().startOf('month'),
		dayjs().endOf('month'),
	]);
	const [expenseRecordList, setExpenseRecordList] = useState<
		BusinessAPI.ExpenseRecordVO[]
	>([]);
	const [loading, setLoading] = useState(false);

	// 数据加载
	const loadExpenseData = async () => {
		setLoading(true);
		try {
			const { data: expenseRecordList, success } =
				await business.expenseRecord.listExpenseRecord({
					expenseRecordListQry: {
						startDate: dateRange[0].format('YYYY-MM-DD'),
						endDate: dateRange[1].format('YYYY-MM-DD'),
					},
				});

			if (success) {
				setExpenseRecordList(expenseRecordList || []);
			}
		} catch (error) {
			console.error('加载费用数据失败:', error);
			message.error('加载数据失败');
		} finally {
			setLoading(false);
		}
	};

	useEffect(() => {
		loadExpenseData().then();
	}, [dateRange]);

	// 计算统计数据 - 使用 useMemo 优化性能
	const statistics: StatisticsData = useMemo(() => {
		if (!expenseRecordList || expenseRecordList.length === 0) {
			return {
				totalVehicles: 0,
				totalProvision: 0,
				totalExpense: 0,
				dailyProfit: 0,
				dealerStatistics: new Map(),
				costCategoryStatistics: new Map(),
			};
		}

		const totalVehicles = expenseRecordList.reduce((sum, record) => {
			return sum + (record.expenseProvisionList?.length || 0);
		}, 0);

		const totalProvision = expenseRecordList.reduce((sum, record) => {
			return sum + (record.totalProvision || 0);
		}, 0);

		const totalExpense = expenseRecordList.reduce((sum, record) => {
			return sum + (record.totalExpense || 0);
		}, 0);

		const dailyProfit = totalProvision - totalExpense;

		// 计提方统计（按客户/计提方分组）
		const dealerStatistics = new Map<
			string,
			{ vehicleCount: number; totalAmount: number }
		>();
		expenseRecordList.forEach((record) => {
			record.expenseProvisionList?.forEach((provision) => {
				const dealerName = provision.dealerName || '未分组客户';
				const current = dealerStatistics.get(dealerName) || {
					vehicleCount: 0,
					totalAmount: 0,
				};
				dealerStatistics.set(dealerName, {
					vehicleCount: current.vehicleCount + 1,
					totalAmount: current.totalAmount + (provision.provisionAmount || 0),
				});
			});
		});

		// 费用分类汇总（按费用类型分组）
		const costCategoryStatistics = new Map<string, number>();
		expenseRecordList.forEach((record) => {
			record.expenseCostList?.forEach((cost) => {
				const costName = cost.costName || '未知费用';
				const currentAmount = costCategoryStatistics.get(costName) || 0;
				costCategoryStatistics.set(
					costName,
					currentAmount + (cost.expenseAmount || 0),
				);
			});
		});

		return {
			totalVehicles,
			totalProvision,
			totalExpense,
			dailyProfit,
			dealerStatistics,
			costCategoryStatistics,
		};
	}, [expenseRecordList]);

	// 导出费用统计数据
	const exportStatistics = async () => {
		if (!expenseRecordList || expenseRecordList.length === 0) {
			message.warning('暂无数据可导出');
			return;
		}

		try {
			setLoading(true);

			const startDate = dateRange[0].format('YYYY-MM-DD');
			const endDate = dateRange[1].format('YYYY-MM-DD');

			// 使用工具函数导出Excel
			await exportExpenseStatisticsExcel({
				title: '费用统计报表',
				startDate,
				endDate,
				statistics: statistics,
				recordList: expenseRecordList,
				fileName: `费用统计_${dayjs(startDate).format('YYYYMMDD')}_${dayjs(endDate).format('YYYYMMDD')}.xlsx`,
				sheetName: '费用统计',
			});
		} catch (error) {
			console.error('导出失败:', error);
		} finally {
			setLoading(false);
		}
	};

	// 渲染计提明细
	const renderProvisionDetails = (record: BusinessAPI.ExpenseRecordVO) => {
		const provisionList = record.expenseProvisionList || [];

		if (provisionList.length === 0) {
			return (
				<Empty
					image={Empty.PRESENTED_IMAGE_SIMPLE}
					description="当日无计提记录"
				/>
			);
		}

		// 按客户分组统计
		const dealerGroups = provisionList.reduce(
			(groups, provision) => {
				const dealerName = provision.dealerName || '未分组客户';
				if (!groups[dealerName]) {
					groups[dealerName] = [];
				}
				groups[dealerName].push(provision);
				return groups;
			},
			{} as Record<string, BusinessAPI.ExpenseProvision[]>,
		);

		return (
			<List
				dataSource={Object.entries(dealerGroups)}
				renderItem={([dealerName, provisions]) => {
					const totalAmount = provisions.reduce(
						(sum, p) => sum + (p.provisionAmount || 0),
						0,
					);
					return (
						<List.Item key={dealerName}>
							<Card
								size="small"
								style={{ width: '100%' }}
								title={
									<Space>
										<Badge count={provisions.length} showZero color="blue" />
										<span>{dealerName}</span>
									</Space>
								}
								extra={
									<Statistic
										title=""
										value={totalAmount}
										prefix="¥"
										precision={2}
									/>
								}
							>
								<Space wrap>
									{provisions.map((provision) => (
										<Tag key={provision.expenseProvisionId}>
											{provision.vehicleNo || '未分配'}: ¥
											{provision.provisionAmount?.toLocaleString()}
										</Tag>
									))}
								</Space>
							</Card>
						</List.Item>
					);
				}}
			/>
		);
	};

	// 渲染费用明细
	const renderCostDetails = (record: BusinessAPI.ExpenseRecordVO) => {
		const costStatistics = new Map<string, number>();

		// 统计每种费用类型的金额
		record.expenseCostList?.forEach((cost) => {
			const currentAmount = costStatistics.get(cost.costName || '') || 0;
			costStatistics.set(
				cost.costName || '',
				currentAmount + (cost.expenseAmount || 0),
			);
		});

		if (costStatistics.size === 0) {
			return (
				<Empty
					image={Empty.PRESENTED_IMAGE_SIMPLE}
					description="当日无费用记录"
				/>
			);
		}

		return (
			<Space wrap>
				{Array.from(costStatistics.entries()).map(([costName, amount]) => (
					<Card key={costName} size="small">
						<Space direction="vertical" size={0}>
							<Tag color="orange">{costName}</Tag>
							<Statistic
								title=""
								value={amount}
								prefix="¥"
								precision={0}
								valueStyle={{ fontSize: '14px' }}
							/>
						</Space>
					</Card>
				))}
			</Space>
		);
	};

	const provisionList =
		expenseRecordList.flatMap((record) => record.expenseProvisionList || []) ||
		[];

	// 按客户分组统计
	const dealerGroups = provisionList.reduce(
		(groups, provision) => {
			const dealerName = provision.dealerName || '未分组客户';
			if (!groups[dealerName]) {
				groups[dealerName] = [];
			}
			groups[dealerName].push(provision);
			return groups;
		},
		{} as Record<string, BusinessAPI.ExpenseProvision[]>,
	);
	// 折叠面板配置
	const collapseItems = [
		{
			key: 'summary',
			label: (
				<Space style={{ justifyContent: 'space-between', width: '100%' }}>
					<span>时间段汇总概览</span>
					<span style={{ fontSize: '12px', color: '#999' }}>
						{dateRange[0].format('YYYY年MM月DD日')} ~{' '}
						{dateRange[1].format('YYYY年MM月DD日')}
					</span>
				</Space>
			),
			children: (
				<Space direction="vertical" style={{ width: '100%' }}>
					{/* 计提方统计 */}
					<div>
						<h4 style={{ color: '#1890ff', marginBottom: 16 }}>计提方统计</h4>
						<List
							dataSource={Object.entries(dealerGroups)}
							renderItem={([dealerName, provisions]) => {
								const totalAmount = provisions.reduce(
									(sum, p) => sum + (p.provisionAmount || 0),
									0,
								);
								return (
									<List.Item key={dealerName}>
										<Card
											size="small"
											style={{ width: '100%' }}
											title={
												<Space>
													<Badge
														count={provisions.length}
														showZero
														color="blue"
													/>
													<span>{dealerName}</span>
												</Space>
											}
											extra={
												<Statistic
													title=""
													value={totalAmount}
													prefix="¥"
													precision={2}
												/>
											}
										>
											<Space wrap>
												{provisions.map((provision) => (
													<Tag key={provision.expenseProvisionId}>
														{provision.vehicleNo || '未分配'}: ¥
														{provision.provisionAmount?.toLocaleString()}
													</Tag>
												))}
											</Space>
										</Card>
									</List.Item>
								);
							}}
							locale={{ emptyText: <Empty description="暂无计提数据" /> }}
						/>
					</div>

					{/* 费用分类汇总 */}
					<div>
						<h4 style={{ color: '#fa8c16', marginBottom: 16 }}>费用分类汇总</h4>
						{statistics.costCategoryStatistics.size > 0 ? (
							<Space wrap>
								{Array.from(statistics.costCategoryStatistics.entries()).map(
									([costName, amount]) => (
										<Card key={costName} size="small">
											<Space direction="vertical" size={0}>
												<Tag color="orange">{costName}</Tag>
												<Statistic
													title=""
													value={amount}
													prefix="¥"
													precision={0}
													valueStyle={{ fontSize: '14px' }}
												/>
											</Space>
										</Card>
									),
								)}
							</Space>
						) : (
							<Empty description="暂无费用数据" />
						)}
					</div>
				</Space>
			),
		},
	];

	// 每日明细折叠面板
	const dailyCollapseItems = expenseRecordList.map((record) => {
		const vehicleCount = record.expenseProvisionList?.length || 0;
		const dayProfit = (record.totalProvision || 0) - (record.totalExpense || 0);

		return {
			key: record.recordDate,
			label: (
				<div
					style={{
						display: 'flex',
						justifyContent: 'space-between',
						alignItems: 'center',
						width: '100%',
					}}
				>
					<Space direction="vertical" size={0}>
						<span style={{ fontWeight: 500 }}>
							{dayjs(record.recordDate).format('YYYY年MM月DD日')}
						</span>
						<Space size="middle" style={{ fontSize: '12px', color: '#666' }}>
							<span>车次: {vehicleCount}</span>
							<span style={{ color: '#1890ff' }}>
								计提: ¥{(record.totalProvision || 0).toLocaleString()}
							</span>
							<span style={{ color: '#fa8c16' }}>
								费用: ¥{(record.totalExpense || 0).toLocaleString()}
							</span>
						</Space>
					</Space>
					<Space>
						<Button
							type="primary"
							size="small"
							onClick={(e) => e.stopPropagation()}
						>
							录入
						</Button>
						<Statistic
							title=""
							value={dayProfit}
							prefix="¥"
							precision={2}
							valueStyle={{
								color: dayProfit >= 0 ? '#3f8600' : '#cf1322',
								fontSize: '16px',
								fontWeight: 'bold',
							}}
							suffix={
								dayProfit >= 0 ? (
									<ArrowUpOutlined style={{ color: '#3f8600' }} />
								) : (
									<ArrowDownOutlined style={{ color: '#cf1322' }} />
								)
							}
						/>
					</Space>
				</div>
			),
			children: (
				<Space direction="vertical" style={{ width: '100%' }}>
					<div>
						<h4 style={{ color: '#1890ff', marginBottom: 12 }}>计提明细</h4>
						{renderProvisionDetails(record)}
					</div>
					<div>
						<h4 style={{ color: '#fa8c16', marginBottom: 12 }}>费用明细</h4>
						{renderCostDetails(record)}
					</div>
				</Space>
			),
		};
	});

	return (
		<PageContainer
			permission={''}
			fieldProps={{
				extra: (
					<Space direction="horizontal" size="small">
						<RangePicker
							value={dateRange}
							onChange={(dates) => {
								if (dates && dates[0] && dates[1]) {
									setDateRange([dates[0], dates[1]]);
								}
							}}
							style={{ width: '100%' }}
							allowClear={false}
						/>
						<Button
							size="middle"
							onClick={exportStatistics}
							icon={<DownOutlined />}
						>
							导出统计
						</Button>
						<Button type="primary" size="middle" icon={<PlusOutlined />}>
							花销录入
						</Button>
					</Space>
				),
			}}
		>
			<Space direction="vertical" style={{ width: '100%' }} size="middle">
				{/* 汇总统计卡片 */}
				<Card title="时间段汇总概览" size="small" loading={loading}>
					<Row gutter={[16, 16]}>
						<Col xs={12} sm={6}>
							<Statistic
								title="总车次"
								value={statistics.totalVehicles}
								suffix="车"
							/>
						</Col>
						<Col xs={12} sm={6}>
							<Statistic
								title="计提总额"
								value={statistics.totalProvision}
								prefix="¥"
								precision={2}
							/>
						</Col>
						<Col xs={12} sm={6}>
							<Statistic
								title="费用总额"
								value={statistics.totalExpense}
								prefix="¥"
								precision={2}
							/>
						</Col>
						<Col xs={12} sm={6}>
							<Statistic
								title="日常利润"
								value={statistics.dailyProfit}
								prefix="¥"
								precision={2}
								valueStyle={{
									color: statistics.dailyProfit >= 0 ? '#3f8600' : '#cf1322',
								}}
								suffix={
									statistics.dailyProfit >= 0 ? (
										<ArrowUpOutlined style={{ color: '#3f8600' }} />
									) : (
										<ArrowDownOutlined style={{ color: '#cf1322' }} />
									)
								}
							/>
						</Col>
					</Row>
				</Card>

				{/* 详细统计 - 使用折叠面板 */}
				<Collapse
					expandIconPosition={'start'}
					items={collapseItems}
					bordered={false}
					defaultActiveKey={['summary']}
				/>

				{/* 每日花销明细 */}
				<Card title="每日花销明细" size="small" loading={loading}>
					{expenseRecordList.length > 0 ? (
						<Collapse
							expandIconPosition={'start'}
							items={dailyCollapseItems}
							bordered={false}
							defaultActiveKey={[]}
						/>
					) : (
						<Empty description="暂无数据">
							<Button
								type="primary"
								onClick={() =>
									setDateRange([
										dayjs().startOf('month'),
										dayjs().endOf('month'),
									])
								}
							>
								查看本月数据
							</Button>
						</Empty>
					)}
				</Card>
			</Space>
		</PageContainer>
	);
}
