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

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

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

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

	const columns: ProColumns<BusinessAPI.UserVO>[] = [
		{
			title: '客户昵称',
			dataIndex: 'nickname',
			valueType: 'text',
		},
		{
			title: '姓名',
			dataIndex: 'name',
			valueType: 'text',
		},
		{
			title: '手机号',
			dataIndex: 'phone',
			valueType: 'text',
		},
		...(initExtraColumns || []),
	];

	function setUserVOStorage(userVO: BusinessAPI.UserVO) {
		const localUserList = localStorage.getItem(sessionKey);
		const userList = localUserList ? JSON.parse(localUserList) : [];
		userList.forEach((item: BusinessAPI.UserVO, index: number) => {
			if (item.userId === userVO.userId) {
				userList.splice(index, 1);
			}
		});
		if (userList.length < 5) {
			userList.unshift(userVO);
			localStorage.setItem(sessionKey, JSON.stringify(userList));
		} else {
			userList.pop();
			userList.unshift(userVO);
			localStorage.setItem(sessionKey, JSON.stringify(userList));
		}
	}

	return (
		<SelectModal<BusinessAPI.UserVO, BusinessAPI.UserPageQry>
			rowKey={'userId'}
			modalProps={{
				title: title || '选择客户',
				...rest,
				destroyOnHidden: true,
				afterOpenChange: (open) => {
					if (!open) {
						setParams({
							...initParams,
						});
					}
				},
			}}
			selectedList={selectedList}
			tableProps={{
				rowKey: 'userId',
				columns: columns,
				columnsState: {
					persistenceType: 'sessionStorage',
					persistenceKey: 'userModalColumnStateKey',
				},
				params: {
					...params,
					isAdmin: false,
					state: ['ENABLE'],
				},
				request: async (params, sorter, filter) => {
					const { data, success, totalCount } = await business.user.pageUser({
						userPageQry: 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.UserVO>();
					selectedRows.forEach((item: BusinessAPI.UserVO) => {
						if (item) {
							if (!selectedRowsMap.has(item.userId)) {
								selectedRowsMap.set(item.userId, item);
							}
						}
					});
					selectedList?.forEach((item: BusinessAPI.UserVO) => {
						if (!selectedRowsMap.has(item.userId)) {
							selectedRowsMap.set(item.userId, item);
						}
					});
					let selectedTempList: BusinessAPI.UserVO[] = [];
					selectedRowsMap.forEach((item: BusinessAPI.UserVO) => {
						if (selectedRowKeys.includes(item.userId)) {
							selectedTempList.push(item);
						}
					});
					return (
						<Space size={12}>
							<span>已选 {selectedRowKeys.length} 项</span>
							<Space wrap={true}>
								{selectedTempList?.map((item: BusinessAPI.UserVO) => {
									return item && <span key={item.userId}>{item.name}</span>;
								})}
							</Space>
						</Space>
					);
				},
				...(tips && {
					tableExtraRender: () => {
						return tips && <Alert type={'info'} message={tips} />;
					},
				}),
				...(type === 'radio' && {
					tableExtraRender: () => {
						const localUserList = localStorage.getItem(sessionKey);
						if (localUserList) {
							const userList = JSON.parse(localUserList);
							return (
								<>
									{tips && <Alert type={'info'} message={tips} />}
									<Row gutter={16}>
										{userList.map((item: BusinessAPI.UserVO) => {
											return (
												<Tag
													style={{
														cursor: 'pointer',
													}}
													onClick={async () => {
														const { data: userVO } =
															await business.user.showUser({
																userShowQry: {
																	userId: item.userId,
																},
															});

														if (userVO) {
															onFinish([userVO]);
															setUserVOStorage(userVO);
														}
													}}
													key={item.userId}
												>
													({item.nickname}) {item.name}
												</Tag>
											);
										})}
									</Row>
								</>
							);
						}
					},
				}),
				actionRef: actionRef,
				toolbar: {
					actions: [<UserList key={'create'} ghost={true} mode={'create'} />],
					filter: (
						<LightFilter
							onFinish={async (values) => {
								setParams({
									...initParams,
									...values,
								});
							}}
						>
							{extraFilter}
						</LightFilter>
					),
					search: {
						placeholder: '请输入客户昵称/姓名',
						onSearch: async (value: string) => {
							setParams({
								...params,
								keyword: value,
							});
						},
					},
				},
			}}
			onFinish={(userVOList) => {
				if (type === 'radio') {
					if (userVOList.length > 0) {
						setUserVOStorage(userVOList[0]);
					}
				}

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