import { CompanyPaymentAccountModal } from '@/components';
import { formatAccountDisplay } from '@/utils/companyPaymentAccount';
import { useIntl } from '@@/exports';
import { ProFormSelect } from '@ant-design/pro-components';
import { ProFieldFCRenderProps } from '@ant-design/pro-provider';
import { useState } from 'react';

export interface ICompanyPaymentAccountFormItemProps extends Omit<
	ProFieldFCRenderProps,
	'value' | 'onChange'
> {
	value?: BusinessAPI.CompanyPaymentAccountVO['accountId'];
	onChange?: (value?: BusinessAPI.CompanyPaymentAccountVO['accountId']) => void;
	params: BusinessAPI.CompanyPaymentAccountPageQry;
}

export default function CompanyPaymentAccountFormItem(
	props: ICompanyPaymentAccountFormItemProps,
) {
	const intl = useIntl();
	const { value, onChange, params } = props;

	const [showModal, setShowModal] = useState<boolean>(false);
	const [accountList, setAccountList] =
		useState<(BusinessAPI.CompanyPaymentAccountVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				fieldProps={{
					open: false,
					onClear: () => {
						onChange?.(undefined);
					},
					onClick: () => {
						setShowModal(true);
					},
					value: value,
					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)}
				onFinish={async (accountList) => {
					if (accountList.length > 0) {
						const account = accountList[0];
						onChange?.(account?.accountId);
						setAccountList(accountList);
						setShowModal(false);
					}
				}}
				type={'radio'}
				params={params}
			/>
		</>
	);
}
