import { IUserModalProps, UserModal } from '@/components';
import {
	FormInstance,
	ProFormSelect,
	ProFormSelectProps,
} from '@ant-design/pro-components';
import { useState } from 'react';

export interface IUserSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: IUserModalProps['selectedList'];
	onFinish?: (userVOList: BusinessAPI.UserVO[]) => void;
}

export default function UserSearch(props: IUserSearchProps) {
	const { form, selectedList, onFinish, ...rest } = props;

	const [showUserModal, setShowUserModal] = useState<boolean>(false);
	const [userList, setUserList] =
		useState<(BusinessAPI.UserVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowUserModal(true);
					},
					placeholder: '请选择客户',
					options: userList?.map((userVO?: BusinessAPI.UserVO) => {
						console.log('userVO', userVO);
						return {
							value: userVO?.userId,
							label: `(ID: ${userVO?.userId}) ${userVO?.nickname || userVO?.name}`,
						};
					}),
				}}
			/>
			<UserModal
				title={'选择客户'}
				open={showUserModal}
				onOk={() => setShowUserModal(false)}
				onCancel={() => setShowUserModal(false)}
				selectedList={selectedList}
				onFinish={async (userVOList) => {
					if (userVOList.length > 0) {
						const userVO = userVOList[0];
						form.setFieldsValue({
							userId: userVO?.userId,
							userVO: userVO,
						});
						form.validateFields(['userId', 'userVO']);
						setUserList(userVOList);
						setShowUserModal(false);
						onFinish?.(userVOList);
					}
				}}
				type={'radio'}
			/>
		</>
	);
}
