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

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

export default function PurchaseOrderFormItem(
	props: IPurchaseOrderFormItemProps,
) {
	const { value, onChange } = props;

	const [showPurchaseOrderModal, setShowPurchaseOrderModal] =
		useState<boolean>(false);
	const [purchaseOrderList, setPurchaseOrderList] =
		useState<(BusinessAPI.PurchaseOrderVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				fieldProps={{
					open: false,
					onClear: () => {
						onChange?.(undefined);
					},
					onClick: () => {
						setShowPurchaseOrderModal(true);
					},
					value: value,
					placeholder: '请选择采购单',
					options: purchaseOrderList?.map(
						(dealerVO?: BusinessAPI.PurchaseOrderVO) => {
							return {
								value: dealerVO?.orderId,
								label: `${dealerVO?.orderSn}`,
							};
						},
					),
				}}
			/>
			<PurchaseOrderModal
				title={'选择采购单'}
				open={showPurchaseOrderModal}
				onOk={() => setShowPurchaseOrderModal(false)}
				onCancel={() => setShowPurchaseOrderModal(false)}
				onFinish={async (purchaseOrderVOList) => {
					if (purchaseOrderVOList.length > 0) {
						const purchaseOrderVO = purchaseOrderVOList[0];
						onChange?.(purchaseOrderVO?.orderId);
						setPurchaseOrderList(purchaseOrderVOList);
						setShowPurchaseOrderModal(false);
					}
				}}
				type={'radio'}
			/>
		</>
	);
}
