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

export interface ISupplierSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: ISupplierModalProps['selectedList'];
	onFinish?: (supplierVOList: BusinessAPI.SupplierVO[]) => void;
	params: BusinessAPI.SupplierPageQry;
}

export default function SupplierSearch(props: ISupplierSearchProps) {
	const { form, selectedList, onFinish, params, ...rest } = props;
	const [showSupplierModal, setShowSupplierModal] = useState<boolean>(false);
	const [supplierList, setSupplierList] =
		useState<(BusinessAPI.SupplierVO | undefined)[]>();

	const slug = props.params?.type === 'FARMER' ? '瓜农' : '档口';

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowSupplierModal(true);
					},
					placeholder: '请选择' + slug,
					options: supplierList?.map((supplierVO?: BusinessAPI.SupplierVO) => {
						return {
							value: supplierVO?.supplierId,
							label: supplierVO?.name,
						};
					}),
				}}
			/>
			<SupplierModal
				title={'选择' + slug}
				open={showSupplierModal}
				onOk={() => setShowSupplierModal(false)}
				onCancel={() => setShowSupplierModal(false)}
				selectedList={selectedList}
				onFinish={async (supplierVOList) => {
					if (supplierVOList.length > 0) {
						const supplierVO = supplierVOList[0];
						form.setFieldsValue({
							supplierId: supplierVO?.supplierId,
							supplierVO: supplierVO,
						});
						form.validateFields(['supplierId', 'supplierVO']);
						setSupplierList(supplierVOList);
						setShowSupplierModal(false);
						onFinish?.(supplierVOList);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
