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

export interface ISupplierFormItemProps extends Omit<
	ProFieldFCRenderProps,
	'value' | 'onChange'
> {
	value?: BusinessAPI.SupplierVO['supplierId'];
	onChange?: (value?: BusinessAPI.SupplierVO['supplierId']) => void;
	params: BusinessAPI.SupplierPageQry;
}

export default function SupplierFormItem(props: ISupplierFormItemProps) {
	const { value, onChange, params } = props;

	const [showSupplierModal, setShowSupplierModal] = useState<boolean>(false);
	const [supplierList, setSupplierList] =
		useState<(BusinessAPI.SupplierVO | undefined)[]>();

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

	return (
		<>
			<ProFormSelect
				fieldProps={{
					open: false,
					onClear: () => {
						onChange?.(undefined);
					},
					onClick: () => {
						setShowSupplierModal(true);
					},
					value: value,
					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)}
				onFinish={async (supplierVOList) => {
					if (supplierVOList.length > 0) {
						const supplierVO = supplierVOList[0];
						onChange?.(supplierVO?.supplierId);
						setSupplierList(supplierVOList);
						setShowSupplierModal(false);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
