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

export interface ICompanyPaymentAccountModalProps extends ModalProps {
	title: string;
	selectedList?: BusinessAPI.CompanyPaymentAccountVO[];
	onFinish: (accountList: BusinessAPI.CompanyPaymentAccountVO[]) => void;
	type: 'checkbox' | 'radio' | undefined;
	params?: BusinessAPI.CompanyPaymentAccountPageQry;
	num?: number;
	tips?: string;
	extraFilter?: React.ReactNode[];
	extraColumns?: ProColumns<
		BusinessAPI.CompanyPaymentAccountVO,
		BizValueType
	>[];
}

export default function CompanyPaymentAccountModal(
	props: ICompanyPaymentAccountModalProps,
) {
	const {
		title,
		onFinish,
		type,
		selectedList,
		params: initParams,
		num = 10,
		tips,
		extraFilter = [],
		extraColumns: initExtraColumns = [],
		...rest
	} = props;
	const actionRef = useRef<ActionType>();
	const sessionKey = 'companyPaymentAccount';

	const [params, setParams] =
		useState<BusinessAPI.CompanyPaymentAccountPageQry>(initParams || {});
	const [activeKey, setActiveKey] =
		useState<BusinessAPI.CompanyPaymentAccountPageQry['accountCategory']>(
			'COMPANY_ACCOUNT',
		);

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

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

	// 公司账户列配置
	const companyAccountColumns: ProColumns<
		BusinessAPI.CompanyPaymentAccountVO,
		BizValueType
	>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.accountName',
			}),
			dataIndex: 'accountName',
			key: 'accountName',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.bankName',
			}),
			dataIndex: 'bankName',
			key: 'bankName',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.branchName',
			}),
			dataIndex: 'branchName',
			key: 'branchName',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.accountNumber',
			}),
			dataIndex: 'accountNumber',
			key: 'accountNumber',
			search: false,
			ellipsis: true,
		},
		...(initExtraColumns || []),
	];

	// 私人账户列配置
	const privateAccountColumns: ProColumns<
		BusinessAPI.CompanyPaymentAccountVO,
		BizValueType
	>[] = [
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.accountName',
			}),
			dataIndex: 'accountName',
			key: 'accountName',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.accountType',
			}),
			dataIndex: 'accountType',
			key: 'accountType',
			valueType: 'select',
			valueEnum: {
				BANK_CARD: intl.formatMessage({
					id: intlPrefix + '.column.accountType.enum.bankCard',
				}),
				ALIPAY: intl.formatMessage({
					id: intlPrefix + '.column.accountType.enum.alipay',
				}),
				WECHAT: intl.formatMessage({
					id: intlPrefix + '.column.accountType.enum.wechat',
				}),
			},
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.bankName',
			}),
			dataIndex: 'bankName',
			key: 'bankName',
			search: false,
		},
		{
			title: intl.formatMessage({
				id: intlPrefix + '.column.accountNumber',
			}),
			dataIndex: 'accountNumber',
			key: 'accountNumber',
			search: false,
			ellipsis: true,
		},
		...(initExtraColumns || []),
	];

	// 根据 Tab 获取当前列配置
	const getCurrentColumns = ():
		| ProColumns<BusinessAPI.CompanyPaymentAccountVO, BizValueType>[]
		| undefined => {
		if (activeKey === 'COMPANY_ACCOUNT') {
			return companyAccountColumns;
		}
		return privateAccountColumns;
	};

	function setAccountStorage(account: BusinessAPI.CompanyPaymentAccountVO) {
		const localList = localStorage.getItem(sessionKey);
		const accountList = localList ? JSON.parse(localList) : [];
		accountList.forEach(
			(item: BusinessAPI.CompanyPaymentAccountVO, index: number) => {
				if (item.accountId === account.accountId) {
					accountList.splice(index, 1);
				}
			},
		);
		if (accountList.length < 5) {
			accountList.unshift(account);
			localStorage.setItem(sessionKey, JSON.stringify(accountList));
		} else {
			accountList.pop();
			accountList.unshift(account);
			localStorage.setItem(sessionKey, JSON.stringify(accountList));
		}
	}

	return (
		<SelectModal<
			BusinessAPI.CompanyPaymentAccountVO,
			BusinessAPI.CompanyPaymentAccountPageQry
		>
			rowKey={'accountId'}
			modalProps={{
				title: title || '选择付款账户',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
						setActiveKey('COMPANY_ACCOUNT');
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'accountId',
				columns: getCurrentColumns(),
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'companyPaymentAccountModalColumnStateKey',
				},
				params: {
					...params,
					accountCategory: activeKey as any,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.companyPaymentAccount.pageCompanyPaymentAccount({
							companyPaymentAccountPageQry: formatParam<typeof params>(
								params,
								sorter,
								filter,
							),
						});

					return {
						data: data || [],
						total: totalCount,
						success,
					};
				},
				tableAlertRender: ({ selectedRowKeys, selectedRows }) => {
					const selectedRowsMap = new Map<
						string,
						BusinessAPI.CompanyPaymentAccountVO
					>();
					selectedRows.forEach((item: BusinessAPI.CompanyPaymentAccountVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.accountId)) {
								selectedRowsMap.set(item.accountId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.CompanyPaymentAccountVO) => {
						if (!selectedRowsMap.has(item.accountId)) {
							selectedRowsMap.set(item.accountId, item);
						}
					});
					let selectedTempList: BusinessAPI.CompanyPaymentAccountVO[] = [];
					selectedRowsMap.forEach(
						(item: BusinessAPI.CompanyPaymentAccountVO) => {
							if (selectedRowKeys.includes(item.accountId)) {
								selectedTempList.push(item);
							}
						},
					);
					return (
						<span>
							已选 {selectedRowKeys.length} 项{' '}
							{selectedTempList?.map(
								(item: BusinessAPI.CompanyPaymentAccountVO) => {
									return (
										item && <span key={item.accountId}>{item.accountName}</span>
									);
								},
							)}
						</span>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localList = localStorage.getItem(sessionKey);
						if (localList) {
							const accountList = JSON.parse(localList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{accountList
											.filter((item: BusinessAPI.CompanyPaymentAccountVO) => {
												if (params.companyId) {
													return item.companyId === params.companyId;
												}
												return true;
											})
											.map((item: BusinessAPI.CompanyPaymentAccountVO) => {
												return (
													<Tag
														style={{
															cursor: 'pointer',
														}}
														onClick={async () => {
															const { data: account } =
																await business.companyPaymentAccount.showCompanyPaymentAccount(
																	{
																		companyPaymentAccountShowQry: {
																			accountId: item.accountId,
																		},
																	},
																);

															if (account) {
																onFinish([account]);
																setAccountStorage(account);
															}
														}}
														key={item.accountId}
													>
														{item.accountName}
													</Tag>
												);
											})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
						</LightFilter>
					),
					search: {
						placeholder: '请输入账户名称',
						onSearch: async (value: string) => {
							setParams({
								...params,
								accountName: value,
							});
						},
					},
					menu: {
						type: 'tab',
						defaultActiveKey: activeKey,
						onChange: (key) => {
							setActiveKey(key as any);
						},
						items: [
							{
								key: 'COMPANY_ACCOUNT',
								label: intl.formatMessage({
									id:
										intlPrefix + '.column.accountCategory.enum.companyAccount',
								}),
							},
							{
								key: 'PRIVATE_ACCOUNT',
								label: intl.formatMessage({
									id:
										intlPrefix + '.column.accountCategory.enum.privateAccount',
								}),
							},
						],
					},
				},
			}}
			onFinish={(accountList) => {
				if (type === 'radio') {
					if (accountList.length > 0) {
						setAccountStorage(accountList[0]);
					}
				}

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