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

export interface IReconciliationInvoiceSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: IReconciliationInvoiceModalProps['selectedList'];
	onFinish?: (
		reconciliationInvoiceVOList: BusinessAPI.ReconciliationInvoiceVO[],
	) => void;
	params: BusinessAPI.ReconciliationInvoicePageQry;
}

export default function ReconciliationInvoiceSearch(
	props: IReconciliationInvoiceSearchProps,
) {
	const { form, selectedList, onFinish, params, ...rest } = props;

	const [showReconciliationInvoiceModal, setShowReconciliationInvoiceModal] =
		useState<boolean>(false);
	const [reconciliationInvoiceList, setReconciliationInvoiceList] =
		useState<(BusinessAPI.ReconciliationInvoiceVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowReconciliationInvoiceModal(true);
					},
					placeholder: '请选择对账开票',
					options: reconciliationInvoiceList?.map(
						(reconciliationInvoiceVO?: BusinessAPI.ReconciliationInvoiceVO) => {
							return {
								value: reconciliationInvoiceVO?.reconciliationInvoiceId,
								label: reconciliationInvoiceVO?.invoiceSn,
							};
						},
					),
				}}
			/>
			<ReconciliationInvoiceModal
				title={'选择对账开票'}
				open={showReconciliationInvoiceModal}
				onOk={() => setShowReconciliationInvoiceModal(false)}
				onCancel={() => setShowReconciliationInvoiceModal(false)}
				selectedList={selectedList}
				onFinish={async (reconciliationInvoiceVOList) => {
					if (reconciliationInvoiceVOList.length > 0) {
						const reconciliationInvoiceVO = reconciliationInvoiceVOList[0];
						form.setFieldsValue({
							reconciliationInvoiceId:
								reconciliationInvoiceVO?.reconciliationInvoiceId,
							reconciliationInvoiceVO: reconciliationInvoiceVO,
						});
						form.validateFields([
							'reconciliationInvoiceId',
							'reconciliationInvoiceVO',
						]);
						setReconciliationInvoiceList(reconciliationInvoiceVOList);
						setShowReconciliationInvoiceModal(false);
						onFinish?.(reconciliationInvoiceVOList);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
