import { ReconciliationShipCardProps } from '@/components';
import { formatCurrency } from '@/utils/format';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import {
	Button,
	Card,
	Col,
	Descriptions,
	Divider,
	Row,
	Space,
	Tag,
	Typography,
} from 'antd';
import { useState } from 'react';
import { useIntl } from 'umi';

const { Text } = Typography;

/** 调整类型映射 */
const ADJUSTMENT_TYPE_MAP: Record<string, string> = {
	LOSS: '损耗',
	DOWNGRADE: '降级',
	SHORTAGE: '短少',
	DAMAGE: '破损',
	QUALITY: '质量问题',
	OTHER: '其他',
};

/** 业务来源类型映射 */
const BUSINESS_SOURCE_MAP: Record<string, { label: string; color: string }> = {
	PRODUCTION_PURCHASE: { label: '产地采购', color: 'red' },
	MARKET_PURCHASE: { label: '市场采购', color: 'blue' },
};

export default function ReconciliationShipCard({
	shipOrder,
	adjustments,
	onAddAdjustment,
	onRemoveAdjustment,
	expanded: controlledExpanded,
	onExpandChange,
}: ReconciliationShipCardProps) {
	const intl = useIntl();
	const intlPrefix = 'reconciliation';

	// 内部展开状态
	const [internalExpanded, setInternalExpanded] = useState(true);
	const expanded =
		controlledExpanded !== undefined ? controlledExpanded : internalExpanded;
	const setExpanded = (val: boolean) => {
		if (controlledExpanded !== undefined) {
			onExpandChange?.(val);
		} else {
			setInternalExpanded(val);
		}
	};

	// 计算汇总数据
	const originalAmount = shipOrder.receivableAmount;

	const adjustmentTotal = adjustments.reduce((sum, adj) => sum + adj.amount, 0);

	const actualAmount = originalAmount + adjustmentTotal;

	// 计算总件数和总重量
	const totalBoxes =
		shipOrder.orderShipItemList?.reduce(
			(sum, item) => sum + (item.boxCount || 0),
			0,
		) || 0;

	const totalNetWeight =
		shipOrder.orderShipItemList?.reduce(
			(sum, item) => sum + (item.netWeight || 0),
			0,
		) || 0;

	// 计算平均单价
	const averageUnitPrice =
		totalNetWeight > 0 ? originalAmount / totalNetWeight : 0;

	// 获取车辆信息
	const vehicle = shipOrder.orderVO?.orderVehicle;
	const orderType = shipOrder.orderVO?.type;

	return (
		<Card
			style={{ marginBottom: 16 }}
			bordered
			title={
				<Row align="middle" justify="space-between" style={{ width: '100%' }}>
					<Space size="large">
						<Text strong style={{ fontSize: 16 }}>
							车次 {vehicle?.vehicleNo || shipOrder.orderSn}
						</Text>
						<Text type="secondary">
							{vehicle?.plate || '-'} | {vehicle?.origin || '-'} |{' '}
							{vehicle?.destination || '-'} | {shipOrder.watermelonGrade || '-'}{' '}
							| 原金额: {formatCurrency(originalAmount)}
						</Text>
						{BUSINESS_SOURCE_MAP[orderType || ''] && (
							<Tag color={BUSINESS_SOURCE_MAP[orderType!].color}>
								{BUSINESS_SOURCE_MAP[orderType!].label}
							</Tag>
						)}
					</Space>
					<Button
						type="text"
						icon={expanded ? <UpOutlined /> : <DownOutlined />}
						onClick={() => setExpanded(!expanded)}
					>
						{expanded ? '收起' : '展开'}
					</Button>
				</Row>
			}
			size="small"
		>
			{expanded && (
				<>
					{/* 发货信息 */}
					<Descriptions
						size="small"
						column={{ xs: 1, sm: 2, md: 4 }}
						style={{ marginBottom: 16 }}
					>
						<Descriptions.Item
							label={intl.formatMessage({
								id: `${intlPrefix}.shipCard.boxCount`,
							})}
						>
							{totalBoxes.toLocaleString()} 件
						</Descriptions.Item>
						<Descriptions.Item
							label={intl.formatMessage({
								id: `${intlPrefix}.shipCard.netWeight`,
							})}
						>
							{totalNetWeight.toLocaleString()} 斤
						</Descriptions.Item>
						<Descriptions.Item
							label={intl.formatMessage({
								id: `${intlPrefix}.shipCard.avgUnitPrice`,
							})}
						>
							{formatCurrency(averageUnitPrice)} / 斤
						</Descriptions.Item>
						<Descriptions.Item
							label={intl.formatMessage({
								id: `${intlPrefix}.shipCard.companyName`,
							})}
						>
							{shipOrder.companyName || '-'}
						</Descriptions.Item>
					</Descriptions>

					{/* 调整项记录 */}
					<Text strong style={{ display: 'block', marginBottom: 12 }}>
						{intl.formatMessage({
							id: `${intlPrefix}.shipCard.adjustmentTitle`,
						})}
					</Text>

					{adjustments.length > 0 ? (
						<>
							{adjustments.map((adj) => (
								<Row
									key={adj.id}
									align="middle"
									style={{
										padding: '8px 0',
										borderBottom: '1px solid #f0f0f0',
									}}
								>
									<Col span={2}>
										<Text>{ADJUSTMENT_TYPE_MAP[adj.type] || adj.type}</Text>
									</Col>
									<Col span={4}>
										<Text>{adj.quantity.toLocaleString()} 斤</Text>
									</Col>
									<Col span={4}>
										<Text>{formatCurrency(adj.unitPrice)}</Text>
									</Col>
									<Col span={4}>
										<Text type={adj.amount < 0 ? 'danger' : 'success'}>
											{formatCurrency(adj.amount)}
										</Text>
									</Col>
									<Col span={8}>
										<Text type="secondary">{adj.remark || '-'}</Text>
									</Col>
									<Col span={2} style={{ textAlign: 'right' }}>
										<Button
											type="link"
											danger
											size="small"
											onClick={() =>
												onRemoveAdjustment(shipOrder.orderShipId, adj.id)
											}
										>
											删除
										</Button>
									</Col>
								</Row>
							))}

							<Divider style={{ margin: '12px 0' }} />

							{/* 本车次调整总额 */}
							<Row justify="end" style={{ marginBottom: 8 }}>
								<Col>
									<Space>
										<Text strong>
											{intl.formatMessage({
												id: `${intlPrefix}.shipCard.adjustmentTotal`,
											})}
										</Text>
										<Text
											strong
											type={adjustmentTotal < 0 ? 'danger' : undefined}
										>
											{formatCurrency(adjustmentTotal)}
										</Text>
									</Space>
								</Col>
							</Row>

							{/* 本车次实际应收 */}
							<Row justify="end">
								<Col>
									<Space>
										<Text strong>
											{intl.formatMessage({
												id: `${intlPrefix}.shipCard.actualAmount`,
											})}
										</Text>
										<Text strong style={{ fontSize: 18 }}>
											{formatCurrency(actualAmount)}
										</Text>
									</Space>
								</Col>
							</Row>
						</>
					) : (
						<Row
							justify="center"
							align="middle"
							style={{
								padding: '24px 0',
								borderBottom: '1px solid #f0f0f0',
							}}
						>
							<Text type="secondary">
								{intl.formatMessage({
									id: `${intlPrefix}.shipCard.noAdjustment`,
								})}
							</Text>
						</Row>
					)}

					{/* 新增调整项按钮 */}
					<Button
						type="dashed"
						style={{ marginTop: 16, width: '100%' }}
						onClick={() => onAddAdjustment(shipOrder.orderShipId)}
					>
						{intl.formatMessage({
							id: `${intlPrefix}.shipCard.addAdjustment`,
						})}
					</Button>
				</>
			)}
		</Card>
	);
}
