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

export interface IOrderSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: IOrderModalProps['selectedList'];
	onFinish?: (orderVOList: BusinessAPI.OrderVO[]) => void;
}

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

	const [showOrderModal, setShowOrderModal] =
		useState<boolean>(false);
	const [orderList, setOrderList] =
		useState<(BusinessAPI.OrderVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowOrderModal(true);
					},
					placeholder: '请选择采购单',
					options: orderList?.map(
						(orderVO?: BusinessAPI.OrderVO) => {
							return {
								value: orderVO?.orderId,
								label: orderVO?.orderSn,
							};
						},
					),
				}}
			/>
			<OrderModal
				title={'请选择采购单'}
				open={showOrderModal}
				onOk={() => setShowOrderModal(false)}
				onCancel={() => setShowOrderModal(false)}
				selectedList={selectedList}
				onFinish={async (orderVOList) => {
					if (orderVOList.length > 0) {
						const orderVO = orderVOList[0];
						form.setFieldsValue({
							orderId: orderVO?.orderId,
							orderVO: orderVO,
						});
						form.validateFields(['orderId', 'orderVO']);
						setOrderList(orderVOList);
						setShowOrderModal(false);
						onFinish?.(orderVOList);
					}
				}}
				type={'radio'}
			/>
		</>
	);
}
