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

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

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

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

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

	const columns: ProColumns<BusinessAPI.PaymentTaskVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.taskName' }),
			dataIndex: 'taskName',
			key: 'taskName',
			renderText: (text: string) => <span className="font-medium">{text}</span>,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.paymentTaskSn' }),
			dataIndex: 'paymentTaskSn',
			key: 'paymentTaskSn',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.state' }),
			dataIndex: 'state',
			key: 'state',
			valueType: 'select',
			valueEnum: {
				PENDING: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.pending',
				}),
				PARTIAL: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.partial',
				}),
				COMPLETED: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.completed',
				}),
				CANCELLED: intl.formatMessage({
					id: intlPrefix + '.column.state.enum.cancelled',
				}),
			},
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.totalAmount' }),
			dataIndex: 'totalAmount',
			key: 'totalAmount',
			valueType: 'money',
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.paidAmount' }),
			dataIndex: 'paidAmount',
			key: 'paidAmount',
			valueType: 'money',
		},
		...(initExtraColumns || []),
	];

	function setPaymentTaskVOStorage(paymentTaskVO: BusinessAPI.PaymentTaskVO) {
		const localPaymentTaskList = localStorage.getItem(sessionKey);
		const paymentTaskList = localPaymentTaskList
			? JSON.parse(localPaymentTaskList)
			: [];
		paymentTaskList.forEach(
			(item: BusinessAPI.PaymentTaskVO, index: number) => {
				if (item.paymentTaskId === paymentTaskVO.paymentTaskId) {
					paymentTaskList.splice(index, 1);
				}
			},
		);
		if (paymentTaskList.length < 5) {
			paymentTaskList.unshift(paymentTaskVO);
			localStorage.setItem(sessionKey, JSON.stringify(paymentTaskList));
		} else {
			paymentTaskList.pop();
			paymentTaskList.unshift(paymentTaskVO);
			localStorage.setItem(sessionKey, JSON.stringify(paymentTaskList));
		}
	}

	return (
		<SelectModal<BusinessAPI.PaymentTaskVO, BusinessAPI.PaymentTaskPageQry>
			rowKey={'paymentTaskId'}
			modalProps={{
				title: title || '选择付款任务',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'paymentTaskId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'paymentTaskModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.paymentTask.pagePaymentTask({
							paymentTaskPageQry: 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.PaymentTaskVO>();
					selectedRows.forEach((item: BusinessAPI.PaymentTaskVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.paymentTaskId)) {
								selectedRowsMap.set(item.paymentTaskId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.PaymentTaskVO) => {
						if (!selectedRowsMap.has(item.paymentTaskId)) {
							selectedRowsMap.set(item.paymentTaskId, item);
						}
					});
					let selectedTempList: BusinessAPI.PaymentTaskVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.PaymentTaskVO) => {
						if (selectedRowKeys.includes(item.paymentTaskId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.PaymentTaskVO) => {
									return (
										item && (
											<span key={item.paymentTaskId}>{item.taskName}</span>
										)
									);
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localPaymentTaskList = localStorage.getItem(sessionKey);
						if (localPaymentTaskList) {
							const paymentTaskList = JSON.parse(localPaymentTaskList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{paymentTaskList.map((item: BusinessAPI.PaymentTaskVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={async () => {
														const { data: paymentTaskVO } =
															await business.paymentTask.showPaymentTask({
																paymentTaskShowQry: {
																	paymentTaskId: item.paymentTaskId,
																},
															});

														if (paymentTaskVO) {
															onFinish([paymentTaskVO]);
															setPaymentTaskVOStorage(paymentTaskVO);
														}
													}}
													key={item.paymentTaskId}
												>
													({item.taskName}) {item.paymentTaskSn}
												</Tag>
											);
										})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
						</LightFilter>
					),
					search: {
						placeholder: '请输入付款任务名称/付款编码',
						onSearch: async (value: string) => {
							setParams({
								...params,
								taskName: value,
							});
						},
					},
				},
			}}
			onFinish={(paymentTaskVOList) => {
				if (type === 'radio') {
					if (paymentTaskVOList.length > 0) {
						setPaymentTaskVOStorage(paymentTaskVOList[0]);
					}
				}

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