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

export interface IReconciliationSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: IReconciliationModalProps['selectedList'];
	onFinish?: (reconciliationVOList: BusinessAPI.ReconciliationVO[]) => void;
	params: BusinessAPI.ReconciliationPageQry;
}

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

	const [showReconciliationModal, setShowReconciliationModal] =
		useState<boolean>(false);
	const [reconciliationList, setReconciliationList] =
		useState<(BusinessAPI.ReconciliationVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowReconciliationModal(true);
					},
					placeholder: '请选择对账记录',
					options: reconciliationList?.map(
						(reconciliationVO?: BusinessAPI.ReconciliationVO) => {
							return {
								value: reconciliationVO?.reconciliationId,
								label:
									reconciliationVO?.reconciliationSn ||
									reconciliationVO?.reconciliationId,
							};
						},
					),
				}}
			/>
			<ReconciliationModal
				title={'选择对账记录'}
				open={showReconciliationModal}
				onOk={() => setShowReconciliationModal(false)}
				onCancel={() => setShowReconciliationModal(false)}
				selectedList={selectedList}
				onFinish={async (reconciliationVOList) => {
					if (reconciliationVOList.length > 0) {
						const reconciliationVO = reconciliationVOList[0];
						form.setFieldsValue({
							reconciliationId: reconciliationVO?.reconciliationId,
							reconciliationVO: reconciliationVO,
						});
						form.validateFields(['reconciliationId', 'reconciliationVO']);
						setReconciliationList(reconciliationVOList);
						setShowReconciliationModal(false);
						onFinish?.(reconciliationVOList);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
