import { ExpenseCostCard, ExpenseCostCreate } from '@/components';
import { business } from '@/services';
import { PlusOutlined } from '@ant-design/icons';
import { ProCard } from '@ant-design/pro-components';
import { Button, Col, Divider, Empty, Row, Statistic } from 'antd';
import { useEffect, useState } from 'react';

interface IExpenseCostProps {
	expenseRecord?: BusinessAPI.ExpenseRecordVO;
	onChange?: (expenseRecord: BusinessAPI.ExpenseRecordVO) => void;
}

export default function ExpenseCostList(props: IExpenseCostProps) {
	const { expenseRecord, onChange } = props;

	const expenseCosts = expenseRecord?.expenseCostList || [];

	const [costList, setCostList] = useState<BusinessAPI.CostVO[]>();

	const [visible, setVisible] = useState(false);

	const getCostList = async () => {
		const { data: costList } = await business.cost.listCost({
			costListQry: {
				status: true,
				type: 'EXPENSE_TYPE',
			},
		});

		setCostList(costList);
	};

	// 获取显示的费用列表：isDefault=true 或已录入的费用
	const getDisplayCostList = () => {
		if (!costList) return [];

		return costList.filter((cost) => {
			// 如果已录入，则显示
			const isRecorded = expenseCosts.some(
				(item) => item.costId === cost.costId,
			);
			// 如果是默认费用，则显示
			const isDefault = cost.isDefault === true;

			return isRecorded || isDefault;
		});
	};

	// 获取可添加的费用列表：未显示的费用
	const getAvailableCostList = () => {
		if (!costList) return [];

		const displayedCostIds = getDisplayCostList().map((cost) => cost.costId);

		return costList.filter((cost) => !displayedCostIds.includes(cost.costId));
	};

	useEffect(() => {
		getCostList();
	}, []);

	const totalAmount = expenseCosts.reduce(
		(sum, expense) => sum + (expense.expenseAmount || 0),
		0,
	);

	const displayCostList = getDisplayCostList();

	return (
		<ProCard
			style={{ marginBottom: '12px' }}
			title={'已录入费用'}
			extra={
				getAvailableCostList().length > 0 && (
					<Button
						type="primary"
						size="middle"
						block
						icon={<PlusOutlined />}
						onClick={() => {
							setVisible(true);
						}}
					>
						添加费用
					</Button>
				)
			}
		>
			{displayCostList.length === 0 ? (
				<Empty
					description="暂无费用数据"
					image={Empty.PRESENTED_IMAGE_SIMPLE}
				/>
			) : (
				<div>
					{displayCostList.map((cost) => {
						// 查找该费用类型对应的已录入费用
						const expenseCost = expenseCosts.find(
							(item) => item.costId === cost.costId,
						);
						return (
							<ExpenseCostCard
								key={cost.costId}
								cost={cost}
								expenseCost={expenseCost}
								onUpdate={(expenseCost) => {
									// 如果是更新已存在的费用
									const updatedList = expenseCosts.some(
										(item) => item.costId === cost.costId,
									)
										? expenseCosts.map((item) =>
												item.costId === cost.costId ? expenseCost : item,
											)
										: [...expenseCosts, expenseCost];
									onChange?.({
										...expenseRecord!,
										expenseCostList: updatedList,
									});
								}}
								onDelete={() => {
									onChange?.({
										...expenseRecord!,
										expenseCostList: expenseCosts.filter(
											(item) => item.costId !== cost.costId,
										),
									});
								}}
							/>
						);
					})}
				</div>
			)}

			<Divider />

			{/* 合计区域 */}
			<Row gutter={16}>
				<Col span={12}>
					<Statistic
						title="合计"
						value={totalAmount}
						precision={2}
						prefix="¥"
					/>
				</Col>
			</Row>

			{/* 只有当有可添加的费用时才显示添加按钮 */}

			<ExpenseCostCreate
				visible={visible}
				onClose={() => setVisible(false)}
				onFinish={(expressCost) => {
					onChange?.({
						...expenseRecord!,
						expenseCostList: [...expenseCosts, expressCost],
					});
				}}
			/>
		</ProCard>
	);
}
