import {
	BizEditor,
	ButtonAccess,
	OrderShipSelectList,
	PageContainer,
	ReconciliationAdjustment,
	ReconciliationSummary,
} from '@/components';
import DealerModal from '@/components/Dealer/DealerModal';
import OrderShipModal from '@/components/Order/OrderShipModal';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { formLayout } from '@/utils/formLayout';
import { useIntl } from '@@/exports';
import { PlusOutlined } from '@ant-design/icons';
import {
	DrawerForm,
	FooterToolbar,
	ProCard,
	ProForm,
	ProFormDependency,
	ProFormSelect,
	RouteContext,
	RouteContextType,
} from '@ant-design/pro-components';
import { Button, Col, message, Row, Space, Steps, Table, Tag } from 'antd';
import { useState } from 'react';

interface IReconciliationCreateProps {
	mode: 'page' | 'drawer';
	onFinish?: () => void;
}

export default function ReconciliationCreate(
	props: IReconciliationCreateProps,
) {
	const { mode, onFinish } = props;
	const intl = useIntl();
	const intlPrefix = 'reconciliation';
	const [current, setCurrent] = useState(0);
	const [submitLoading, setSubmitLoading] = useState(false);

	const [selectedDealer, setSelectedDealer] =
		useState<BusinessAPI.DealerVO | null>(null);
	const [dealerModalOpen, setDealerModalOpen] = useState(false);
	const [selectedShipOrderList, setSelectedShipOrderList] = useState<
		BusinessAPI.OrderShipVO[]
	>([]);
	const [orderShipModalOpen, setOrderShipModalOpen] = useState(false);

	// 调整项状态 Map<发货单ID, 调整项数组>
	const [adjustmentsMap, setAdjustmentsMap] = useState<
		Record<string, ReconciliationAdjustment[]>
	>({});

	// 抹零状态
	const [roundOff, setRoundOff] = useState<{
		roundOffEnabled?: boolean;
		roundOffAmount?: number;
		roundOffRemark?: string;
	}>({});

	// 备注状态
	const [remark, setRemark] = useState('');

	const [companyId, setCompanyId] =
		useState<BusinessAPI.CompanyVO['companyId']>();

	// // 添加调整项
	// const handleAddAdjustment = useCallback((shipOrderId: string) => {
	// 	const newAdjustment: ReconciliationAdjustment = {
	// 		id: `${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
	// 		type: 'LOSS',
	// 		quantity: 0,
	// 		unitPrice: 0,
	// 		amount: 0,
	// 		remark: '',
	// 	};
	// 	setAdjustmentsMap((prev) => ({
	// 		...prev,
	// 		[shipOrderId]: [...(prev[shipOrderId] || []), newAdjustment],
	// 	}));
	// }, []);
	//
	// // 删除调整项
	// const handleRemoveAdjustment = useCallback(
	// 	(shipOrderId: string, adjustmentId: string) => {
	// 		setAdjustmentsMap((prev) => ({
	// 			...prev,
	// 			[shipOrderId]: (prev[shipOrderId] || []).filter(
	// 				(adj) => adj.id !== adjustmentId,
	// 			),
	// 		}));
	// 	},
	// 	[],
	// );

	let receivableAmount =
		selectedShipOrderList?.reduce(
			(sum, item) => sum + (item.receivableAmount || 0),
			0,
		) || 0;
	let adjustedAmount =
		selectedShipOrderList?.reduce(
			(sum, item) => sum + (item.adjustedAmount || 0),
			0,
		) || 0;

	// 计算调整总额
	const adjustmentTotal = Object.values(adjustmentsMap)
		.flat()
		.reduce((sum, adj) => sum + (adj.amount || 0), 0);

	// 计算原对账金额（应收金额 - 已调整金额）
	const originalAmount = receivableAmount - adjustedAmount;

	// 计算实际对账金额（含抹零）
	const roundingAmount = roundOff.roundOffEnabled
		? roundOff.roundOffAmount || 0
		: 0;
	const reconciliationAmount =
		originalAmount - adjustmentTotal + roundingAmount;

	// 提交对账单处理函数
	const handleSubmit = async () => {
		if (!selectedDealer) {
			message.warning('请选择经销商');
			return;
		}
		if (selectedShipOrderList.length === 0) {
			message.warning('请选择发货车次');
			return;
		}

		setSubmitLoading(true);
		try {
			const result = await business.reconciliation.createReconciliation({
				dealerId: selectedDealer.dealerId!,
				originalAmount,
				isRounding: roundOff.roundOffEnabled || false,
				roundingAmount,
				roundingRemark: roundOff.roundOffRemark || '',
				reconciliationAmount,
				remark,
				companyId: companyId!,
				orderShipVOList: selectedShipOrderList,
			});

			if (result.success) {
				message.success('对账单创建成功');
				onFinish?.();
			} else {
				message.error(result.errMessage || '对账单创建失败');
			}
		} catch (error) {
			message.error('对账单创建失败，请稍后重试');
			console.error('提交对账单失败:', error);
		} finally {
			setSubmitLoading(false);
		}
	};

	const orderCount = selectedShipOrderList.length;

	const renderForm = () => {
		{
			/* 对账单表单 */
		}
		return (
			<ProCard
				title={'创建对账单'}
				headerBordered
				subTitle={
					<Space>
						<Tag color="blue">步骤 {current + 1}</Tag>
						{current === 0 && '选择经销商'}
						{current === 1 && '选择发货车次'}
						{current === 2 && '核对并录入调整项'}
					</Space>
				}
			>
				{/* 步骤1：选择经销商 */}
				{(current === 0 || current === 1) && (
					<>
						{/* 选择经销商 */}
						<ProCard
							title={'经销商信息'}
							style={{ marginTop: 16 }}
							bordered
							extra={
								current === 0 && (
									<Button
										type="primary"
										size="middle"
										onClick={() => setDealerModalOpen(true)}
									>
										选择经销商
									</Button>
								)
							}
						>
							{selectedDealer ? (
								<Row gutter={[16, 16]}>
									<Col span={8}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												经销商简称
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{selectedDealer.shortName || '-'}
											</div>
										</div>
									</Col>
									<Col span={8}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												经销商类型
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{selectedDealer.dealerType === 'MARKET'
													? '市场'
													: '超市'}
											</div>
										</div>
									</Col>
									<Col span={8}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												应收金额
											</div>
											<div style={{ fontWeight: 'bold' }}>
												￥{selectedDealer.receivable || '-'}
											</div>
										</div>
									</Col>
								</Row>
							) : (
								<div
									style={{
										textAlign: 'center',
										padding: '40px 0',
										color: '#999',
									}}
								>
									暂无选择，请点击「选择经销商」按钮选择
								</div>
							)}
						</ProCard>
					</>
				)}

				{/* 步骤2：选择发货车次 */}
				{current === 1 && selectedDealer && (
					<>
						{/* 选择车次 */}
						<ProCard
							title={'选择车次'}
							style={{ marginTop: 16 }}
							bordered
							extra={
								<Button
									type="primary"
									size="middle"
									onClick={() => setOrderShipModalOpen(true)}
								>
									添加车次
								</Button>
							}
						>
							{selectedShipOrderList.length > 0 ? (
								<OrderShipSelectList
									dataSource={selectedShipOrderList}
									columns={[
										{
											title: '操作',
											key: 'action',
											fixed: 'right',
											width: 80,
											render: (_: any, record: BusinessAPI.OrderShipVO) => (
												<Button
													type="link"
													danger
													onClick={() => {
														setSelectedShipOrderList(
															selectedShipOrderList.filter(
																(item) =>
																	item.orderShipId !== record.orderShipId,
															),
														);
														// 同时清除该车次的调整项
														setAdjustmentsMap((prev) => {
															const newMap = { ...prev };
															delete newMap[record.orderShipId];
															return newMap;
														});
													}}
												>
													移除
												</Button>
											),
										},
									]}
									pagination={false}
									size="small"
									summary={(pageData) => {
										let receivableAmount =
											pageData?.reduce(
												(sum, item) => sum + (item.receivableAmount || 0),
												0,
											) || 0;
										let adjustedAmount =
											pageData?.reduce(
												(sum, item) => sum + (item.adjustedAmount || 0),
												0,
											) || 0;
										return (
											<Table.Summary fixed>
												<Table.Summary.Row>
													<Table.Summary.Cell index={0} colSpan={9}>
														<strong>合计</strong>
													</Table.Summary.Cell>
													<Table.Summary.Cell index={1}>
														<strong className="text-blue-600 font-medium">
															￥{formatCurrency(receivableAmount)}
														</strong>
													</Table.Summary.Cell>
													<Table.Summary.Cell index={1}>
														<strong
															className={
																adjustedAmount >= 0
																	? 'text-green-600'
																	: 'text-red-600'
															}
														>
															￥{formatCurrency(adjustedAmount)}
														</strong>
													</Table.Summary.Cell>
													<Table.Summary.Cell index={2} />
												</Table.Summary.Row>
											</Table.Summary>
										);
									}}
								/>
							) : (
								<div
									style={{
										textAlign: 'center',
										padding: '40px 0',
										color: '#999',
									}}
								>
									暂无数据，请点击「添加车次」按钮添加
								</div>
							)}
						</ProCard>

						{/* 任务摘要 */}
						{selectedShipOrderList.length > 0 && (
							<ProCard title={'对账摘要'} style={{ marginTop: 16 }} bordered>
								<Row gutter={[16, 16]}>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												对账经销商
											</div>
											<div style={{ fontWeight: 'bold' }}>
												{selectedDealer?.fullName || selectedDealer?.shortName}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												车次数量
											</div>
											<div style={{ fontWeight: 'bold' }}>{orderCount} 车</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												对账总额
											</div>
											<div style={{ fontWeight: 'bold', color: '#ff4d4f' }}>
												￥{formatCurrency(receivableAmount - adjustedAmount)}
											</div>
										</div>
									</Col>
									<Col span={6}>
										<div>
											<div style={{ color: '#999', marginBottom: 4 }}>
												对账状态
											</div>
											<div>
												<Tag color="orange">待对账</Tag>
											</div>
										</div>
									</Col>
								</Row>
							</ProCard>
						)}
					</>
				)}

				{/* 步骤3：核对并录入调整项 */}
				{current === 2 && (
					<>
						{/* 对账车次清单 */}
						{/*<ProCard title={'对账车次清单'} style={{ marginTop: 16 }} bordered>*/}
						{/*	{selectedShipOrderList.map((shipOrder) => (*/}
						{/*		<ReconciliationShipCard*/}
						{/*			key={shipOrder.orderShipId}*/}
						{/*			shipOrder={shipOrder}*/}
						{/*			adjustments={adjustmentsMap[shipOrder.orderShipId] || []}*/}
						{/*			onAddAdjustment={handleAddAdjustment}*/}
						{/*			onRemoveAdjustment={handleRemoveAdjustment}*/}
						{/*		/>*/}
						{/*	))}*/}
						{/*</ProCard>*/}

						{/* 对账汇总 */}
						<ProCard title={'对账汇总'} style={{ marginTop: 16 }} bordered>
							<ProFormDependency name={['roundOffAmount']}>
								{({ roundOffAmount }) => {
									return (
										<ReconciliationSummary
											shipOrders={selectedShipOrderList}
											adjustmentsMap={adjustmentsMap}
											roundOffAmount={roundOffAmount}
										/>
									);
								}}
							</ProFormDependency>
						</ProCard>

						{/* 备注信息 */}
						<ProCard title={'备注信息'} style={{ marginTop: 16 }} bordered>
							<ProFormSelect
								label={'入账公司'}
								name={'companyId'}
								placeholder={'请选择入账公司'}
								request={async (params) => {
									const { data } = await business.company.listCompany({
										companyListQry: {
											...params,
										},
									});

									return (
										data?.map((item) => {
											return {
												label: item.fullName,
												value: item.companyId,
											};
										}) || []
									);
								}}
							/>
							<ProFormDependency key={'remark'} name={['remark']}>
								{({}, form) => {
									return (
										<BizEditor
											key={'remark'}
											value={remark}
											onChange={(value) => {
												setRemark(value);
												form.setFieldValue('remark', value);
											}}
											label={'对账备注'}
											name={'remark'}
											placeholder={'请输入对账备注信息'}
										/>
									);
								}}
							</ProFormDependency>
						</ProCard>
					</>
				)}
			</ProCard>
		);
	};

	return (
		<>
			<RouteContext.Consumer>
				{(value: RouteContextType) => {
					const { isMobile } = value;
					if (mode === 'page') {
						return (
							<PageContainer
								permission={''}
								fieldProps={{
									content: (
										<Steps
											current={current}
											style={{ padding: '16px 0' }}
											items={[
												{
													title: '选择经销商',
												},
												{
													title: '选择发货车次',
												},
												{
													title: '核对并录入调整项',
												},
											]}
										/>
									),
								}}
							>
								<ProForm
									{...formLayout(isMobile)}
									submitter={{
										render: () => (
											<FooterToolbar
												style={{
													width: 'calc(100% - 248px)',
												}}
											>
												<Space>
													{current === 1 && (
														<Button onClick={() => setCurrent(0)}>
															上一步
														</Button>
													)}
													{current === 2 && (
														<Button onClick={() => setCurrent(1)}>
															上一步
														</Button>
													)}
													{current === 0 && (
														<Button
															type="primary"
															disabled={!selectedDealer}
															onClick={() => setCurrent(1)}
														>
															下一步：选择发货车次
														</Button>
													)}
													{current === 1 && (
														<Button
															type="primary"
															disabled={selectedShipOrderList.length === 0}
															onClick={() => setCurrent(2)}
														>
															下一步：核对并录入调整项
														</Button>
													)}
													{current === 2 && (
														<Button
															type="primary"
															loading={submitLoading}
															onClick={handleSubmit}
														>
															提交对账单
														</Button>
													)}
												</Space>
											</FooterToolbar>
										),
									}}
									onValuesChange={(formData) => {
										setRoundOff({
											roundOffEnabled: formData.roundOffEnabled || false,
											roundOffAmount: formData.roundOffAmount || 0,
											roundOffRemark: formData.roundOffRemark || '',
										});

										setRemark(formData.remark || '');
										setCompanyId(formData.companyId || '');
									}}
								>
									{renderForm()}
								</ProForm>
							</PageContainer>
						);
					}

					if (mode === 'drawer') {
						return (
							<DrawerForm<any>
								title={intl.formatMessage({
									id: intlPrefix + '.modal.create.title',
								})}
								{...formLayout(isMobile)}
								width={isMobile ? '100%' : '85%'}
								drawerProps={{
									destroyOnHidden: true,
								}}
								trigger={
									<ButtonAccess
										key={'createPaymentTask'}
										permission={'operation-paymentTask-create'}
										type={'primary'}
										size={'middle'}
										icon={<PlusOutlined />}
									>
										{intl.formatMessage({
											id: intlPrefix + '.modal.create.button',
										})}
									</ButtonAccess>
								}
								submitter={{
									render: () => (
										<Space>
											{current === 1 && (
												<Button onClick={() => setCurrent(0)}>上一步</Button>
											)}
											{current === 2 && (
												<Button onClick={() => setCurrent(1)}>上一步</Button>
											)}
											{current === 0 && (
												<Button
													type="primary"
													disabled={!selectedDealer}
													onClick={() => setCurrent(1)}
												>
													下一步：选择发货车次
												</Button>
											)}
											{current === 1 && (
												<Button
													type="primary"
													disabled={selectedShipOrderList.length === 0}
													onClick={() => setCurrent(2)}
												>
													下一步：核对并录入调整项
												</Button>
											)}
											{current === 2 && (
												<Button
													type="primary"
													loading={submitLoading}
													onClick={handleSubmit}
												>
													提交对账单
												</Button>
											)}
										</Space>
									),
								}}
								onFinish={handleSubmit}
							>
								{renderForm()}
							</DrawerForm>
						);
					}
				}}
			</RouteContext.Consumer>

			{/* 选择经销商模态框 */}
			<DealerModal
				open={dealerModalOpen}
				title="选择经销商"
				type="radio"
				selectedList={selectedDealer ? [selectedDealer] : []}
				onFinish={(dealerVOList) => {
					setSelectedDealer(dealerVOList[0]);
					// 切换经销商时清空已选车次和调整项
					setSelectedShipOrderList([]);
					setAdjustmentsMap({});
					setDealerModalOpen(false);
				}}
				onCancel={() => setDealerModalOpen(false)}
				tips="请选择对账的经销商"
				num={1}
			/>
			{/* 选择发货单模态框 */}
			<OrderShipModal
				open={orderShipModalOpen}
				title="选择需要对账的发货单"
				type="checkbox"
				selectedList={selectedShipOrderList}
				onFinish={(orderShipList) => {
					// 过滤掉已经选择的发货单
					const newOrders = orderShipList.filter(
						(item) =>
							!selectedShipOrderList.some(
								(selected) => selected.orderShipId === item.orderShipId,
							),
					);
					setSelectedShipOrderList([...selectedShipOrderList, ...newOrders]);
					setOrderShipModalOpen(false);
				}}
				onCancel={() => setOrderShipModalOpen(false)}
				params={{
					dealerId: selectedDealer?.dealerId,
				}}
				tips="请选择该经销商未对账的发货单"
				num={999}
			/>
		</>
	);
}
