import { UserModal } from '@/components';
import { ProFormSelect } from '@ant-design/pro-components';
import { ProFieldFCRenderProps } from '@ant-design/pro-provider';
import { useState } from 'react';

export interface IUserFormItemProps
	extends Omit<ProFieldFCRenderProps, 'value' | 'onChange'> {
	value?: BusinessAPI.UserVO['userId'];
	onChange?: (value?: BusinessAPI.UserVO['userId']) => void;
}

export default function UserFormItem(props: IUserFormItemProps) {
	const { value, onChange } = props;

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

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