import { DealerList, 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 IDealerModalProps extends ModalProps {
	title: string;
	selectedList?: BusinessAPI.DealerVO[];
	onFinish: (dealerVOList: BusinessAPI.DealerVO[]) => void;
	type: 'checkbox' | 'radio' | undefined;
	params?: BusinessAPI.DealerPageQry;
	num?: number;
	tips?: string;
	extraFilter?: React.ReactNode[];
	extraColumns?: ProColumns<BusinessAPI.DealerVO>[];
}

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

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

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

	const columns: ProColumns<BusinessAPI.DealerVO>[] = [
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.shortName' }),
			dataIndex: 'shortName',
			key: 'shortName',
			renderText: (text: string) => <span className="font-medium">{text}</span>,
		},
		{
			title: intl.formatMessage({ id: intlPrefix + '.column.dealerType' }),
			dataIndex: 'dealerType',
			key: 'dealerType',
			valueType: 'select',
			valueEnum: {
				MARKET: intl.formatMessage({
					id: intlPrefix + '.column.dealerType.enum.market',
				}),
				SUPERMARKET: intl.formatMessage({
					id: intlPrefix + '.column.dealerType.enum.supermarket',
				}),
			},
		},
		...(initExtraColumns || []),
	];

	function setDealerVOStorage(dealerVO: BusinessAPI.DealerVO) {
		const localDealerList = localStorage.getItem(sessionKey);
		const dealerList = localDealerList ? JSON.parse(localDealerList) : [];
		dealerList.forEach((item: BusinessAPI.DealerVO, index: number) => {
			if (item.dealerId === dealerVO.dealerId) {
				dealerList.splice(index, 1);
			}
		});
		if (dealerList.length < 5) {
			dealerList.unshift(dealerVO);
			localStorage.setItem(sessionKey, JSON.stringify(dealerList));
		} else {
			dealerList.pop();
			dealerList.unshift(dealerVO);
			localStorage.setItem(sessionKey, JSON.stringify(dealerList));
		}
	}

	return (
		<SelectModal<BusinessAPI.DealerVO, BusinessAPI.DealerPageQry>
			rowKey={'dealerId'}
			modalProps={{
				title: title || '选择经销商',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'dealerId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'dealerModalColumnStateKey',
				},
				params: {
					...params,
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } =
						await business.dealer.pageDealer({
							dealerPageQry: 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.DealerVO>();
					selectedRows.forEach((item: BusinessAPI.DealerVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.dealerId)) {
								selectedRowsMap.set(item.dealerId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.DealerVO) => {
						if (!selectedRowsMap.has(item.dealerId)) {
							selectedRowsMap.set(item.dealerId, item);
						}
					});
					let selectedTempList: BusinessAPI.DealerVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.DealerVO) => {
						if (selectedRowKeys.includes(item.dealerId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.DealerVO) => {
									return (
										item && <span key={item.dealerId}>{item.shortName}</span>
									);
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localDealerList = localStorage.getItem(sessionKey);
						if (localDealerList) {
							const dealerList = JSON.parse(localDealerList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{dealerList.map((item: BusinessAPI.DealerVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={async () => {
														const { data: dealerVO } =
															await business.dealer.showDealer({
																dealerShowQry: {
																	dealerId: item.dealerId,
																},
															});

														if (dealerVO) {
															onFinish([dealerVO]);
															setDealerVOStorage(dealerVO);
														}
													}}
													key={item.dealerId}
												>
													{item.shortName}
												</Tag>
											);
										})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					actions: [<DealerList key={'create'} ghost={true} mode={'create'} />],
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
						</LightFilter>
					),
					search: {
						placeholder: '请输入经销商昵称/姓名',
						onSearch: async (value: string) => {
							setParams({
								...params,
								shortName: value,
							});
						},
					},
				},
			}}
			onFinish={(dealerVOList) => {
				if (type === 'radio') {
					if (dealerVOList.length > 0) {
						setDealerVOStorage(dealerVOList[0]);
					}
				}

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