import { SelectModal } from '@/components';
import { business } from '@/services';
import { formatCurrency } from '@/utils/format';
import { formatParam } from '@/utils/formatParam';
import { pagination } from '@/utils/pagination';
import { useIntl } from '@@/exports';
import {
	ActionType,
	LightFilter,
	ProColumns,
	ProFormSelect,
} from '@ant-design/pro-components';
import { Alert, ModalProps, Row, Space, Tag } from 'antd';
import React, { useEffect, useRef, useState } from 'react';

export interface IReconciliationModalProps extends ModalProps {
	title: string;
	selectedList?: BusinessAPI.ReconciliationVO[];
	onFinish: (reconciliationVOList: BusinessAPI.ReconciliationVO[]) => void;
	type: 'checkbox' | 'radio' | undefined;
	params?: BusinessAPI.ReconciliationPageQry;
	num?: number;
	tips?: string;
	extraFilter?: React.ReactNode[];
	extraColumns?: ProColumns<BusinessAPI.ReconciliationVO>[];
}

export default function ReconciliationModal(props: IReconciliationModalProps) {
	const {
		title,
		onFinish,
		type,
		selectedList,
		params: initParams,
		num = 10,
		tips,
		extraFilter = [],
		extraColumns: initExtraColumns = [],
		...rest
	} = props;
	const actionRef = useRef<ActionType>();
	const sessionKey = `reconciliationList`;
	const [params, setParams] = useState<BusinessAPI.ReconciliationPageQry>(
		initParams || {},
	);

	useEffect(() => {
		if (initParams) {
			setParams({
				...params,
				...initParams,
			});
		}
	}, [initParams]);

	const intl = useIntl();
	const intlPrefix = 'reconciliation';

	// 状态映射
	const stateMap: Record<string, string> = {
		PENDING: '待对账',
		RECONCILED: '已对账',
		PARTIAL_INVOICE: '部分开票',
		INVOICED: '已开票',
		PARTIAL_PAYMENT: '部分回款',
		PAID: '已回款',
	};

	const columns: ProColumns<BusinessAPI.ReconciliationVO>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.reconciliationSn',
			}),
			dataIndex: 'reconciliationSn',
			key: 'reconciliationSn',
			renderText: (text: string) => <span className="font-medium">{text}</span>,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.state' }),
			dataIndex: 'state',
			key: 'state',
			valueType: 'select',
			valueEnum: Object.entries(stateMap).reduce(
				(acc, [key, label]) => {
					acc[key] = { text: label };
					return acc;
				},
				{} as Record<string, { text: string }>,
			),
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.reconciliationAmount',
			}),
			dataIndex: 'reconciliationAmount',
			key: 'reconciliationAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span className="text-green-600 font-medium">
					￥{formatCurrency(record.reconciliationAmount)}
				</span>
			),
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.originalAmount' }),
			dataIndex: 'originalAmount',
			key: 'originalAmount',
			valueType: 'money',
			search: false,
			render: (_, record) => (
				<span className="text-gray-600">
					￥{formatCurrency(record.originalAmount)}
				</span>
			),
		},
		...(initExtraColumns || []),
	];

	function setReconciliationVOStorage(
		reconciliationVO: BusinessAPI.ReconciliationVO,
	) {
		const localReconciliationList = localStorage.getItem(sessionKey);
		const reconciliationList = localReconciliationList
			? JSON.parse(localReconciliationList)
			: [];
		reconciliationList.forEach(
			(item: BusinessAPI.ReconciliationVO, index: number) => {
				if (item.reconciliationId === reconciliationVO.reconciliationId) {
					reconciliationList.splice(index, 1);
				}
			},
		);
		if (reconciliationList.length < 5) {
			reconciliationList.unshift(reconciliationVO);
			localStorage.setItem(sessionKey, JSON.stringify(reconciliationList));
		} else {
			reconciliationList.pop();
			reconciliationList.unshift(reconciliationVO);
			localStorage.setItem(sessionKey, JSON.stringify(reconciliationList));
		}
	}

	return (
		<SelectModal<
			BusinessAPI.ReconciliationVO,
			BusinessAPI.ReconciliationPageQry
		>
			rowKey={'reconciliationId'}
			modalProps={{
				title: title || '选择对账记录',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'reconciliationId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'reconciliationModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.reconciliation.pageReconciliation({
							reconciliationPageQry: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

					return {
						data: data || [],
						total: totalCount,
						success,
					};
				},
				pagination: {
					...pagination(),
					position: ['bottomRight'],
				},
				tableAlertRender: ({ selectedRowKeys, selectedRows }) => {
					// selectedRows 和 selectedList 组合在一起，去重
					const selectedRowsMap = new Map<
						string,
						BusinessAPI.ReconciliationVO
					>();
					selectedRows.forEach((item: BusinessAPI.ReconciliationVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.reconciliationId)) {
								selectedRowsMap.set(item.reconciliationId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.ReconciliationVO) => {
						if (!selectedRowsMap.has(item.reconciliationId)) {
							selectedRowsMap.set(item.reconciliationId, item);
						}
					});
					let selectedTempList: BusinessAPI.ReconciliationVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.ReconciliationVO) => {
						if (selectedRowKeys.includes(item.reconciliationId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.ReconciliationVO) => {
									return (
										item && (
											<span key={item.reconciliationId}>
												{item.reconciliationSn}
											</span>
										)
									);
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localReconciliationList = localStorage.getItem(sessionKey);
						if (localReconciliationList) {
							const reconciliationList = JSON.parse(localReconciliationList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{reconciliationList.map(
											(item: BusinessAPI.ReconciliationVO) => {
												return (
													<Tag
														style={{
															cursor: 'pointer',
														}}
														onClick={async () => {
															const { data: reconciliationVO } =
																await business.reconciliation.showReconciliation(
																	{
																		reconciliationShowQry: {
																			reconciliationId: item.reconciliationId,
																		},
																	},
																);

															if (reconciliationVO) {
																onFinish([reconciliationVO]);
																setReconciliationVOStorage(reconciliationVO);
															}
														}}
														key={item.reconciliationId}
													>
														{item.reconciliationSn}
													</Tag>
												);
											},
										)}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					actions: [],
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
							{!initParams?.state && (
								<ProFormSelect
									label={'对账单状态'}
									name={'state'}
									placeholder={'请选择对账单状态'}
									valueEnum={{
										PENDING: '待对账',
										RECONCILED: '已对账',
										PARTIAL_INVOICE: '部分开票',
										INVOICED: '已开票',
										PARTIAL_PAYMENT: '部分回款',
										PAID: '已回款',
									}}
									fieldProps={{
										showSearch: true,
										allowClear: true,
										autoClearSearchValue: true,
									}}
								/>
							)}
						</LightFilter>
					),
					search: {
						placeholder: '请输入对账编号',
						onSearch: async (value: string) => {
							setParams({
								...params,
								reconciliationSn: value,
							});
						},
					},
				},
			}}
			onFinish={(reconciliationVOList) => {
				if (type === 'radio') {
					if (reconciliationVOList.length > 0) {
						setReconciliationVOStorage(reconciliationVOList[0]);
					}
				}

				onFinish(reconciliationVOList);
			}}
			num={num}
			type={type}
		/>
	);
}
