import {
	CompanyPaymentAccountModal,
	ICompanyPaymentAccountModalProps,
} from '@/components';
import { formatAccountDisplay } from '@/utils/companyPaymentAccount';
import { useIntl } from '@@/exports';
import {
	FormInstance,
	ProFormSelect,
	ProFormSelectProps,
} from '@ant-design/pro-components';
import { useState } from 'react';

export interface ICompanyPaymentAccountSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: ICompanyPaymentAccountModalProps['selectedList'];
	onFinish?: (accountList: BusinessAPI.CompanyPaymentAccountVO[]) => void;
	params: BusinessAPI.CompanyPaymentAccountPageQry;
}

export default function CompanyPaymentAccountSearch(
	props: ICompanyPaymentAccountSearchProps,
) {
	const intl = useIntl();
	const { form, selectedList, onFinish, params, ...rest } = props;
	const [showModal, setShowModal] = useState<boolean>(false);
	const [accountList, setAccountList] =
		useState<(BusinessAPI.CompanyPaymentAccountVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				{...rest}
				fieldProps={{
					open: false,
					onClick: () => {
						setShowModal(true);
					},
					placeholder: '请选择付款账户',
					options: accountList?.map(
						(account?: BusinessAPI.CompanyPaymentAccountVO) => {
							return {
								value: account?.accountId,
								label: formatAccountDisplay(account, intl),
							};
						},
					),
				}}
			/>
			<CompanyPaymentAccountModal
				title={'选择付款账户'}
				open={showModal}
				onOk={() => setShowModal(false)}
				onCancel={() => setShowModal(false)}
				selectedList={selectedList}
				onFinish={async (accountList) => {
					if (accountList.length > 0) {
						const account = accountList[0];
						form.setFieldsValue({
							companyPaymentAccountId: account?.accountId,
							companyPaymentAccountVO: account,
						});
						form.validateFields([
							'companyPaymentAccountId',
							'companyPaymentAccountVO',
						]);
						setAccountList(accountList);
						setShowModal(false);
						onFinish?.(accountList);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
