import { DealerModal } from '@/components';
import { ProFormSelect } from '@ant-design/pro-components';
import { ProFieldFCRenderProps } from '@ant-design/pro-provider';
import { useState } from 'react';

export interface IDealerFormItemProps
	extends Omit<ProFieldFCRenderProps, 'value' | 'onChange'> {
	value?: BusinessAPI.DealerVO['dealerId'];
	onChange?: (value?: BusinessAPI.DealerVO['dealerId']) => void;
}

export default function DealerFormItem(props: IDealerFormItemProps) {
	const { value, onChange } = props;

	const [showDealerModal, setShowDealerModal] = useState<boolean>(false);
	const [dealerList, setDealerList] =
		useState<(BusinessAPI.DealerVO | undefined)[]>();

	return (
		<>
			<ProFormSelect
				fieldProps={{
					open: false,
					onClear: () => {
						onChange?.(undefined);
					},
					onClick: () => {
						setShowDealerModal(true);
					},
					value: value,
					placeholder: '请选择经销商',
					options: dealerList?.map((dealerVO?: BusinessAPI.DealerVO) => {
						return {
							value: dealerVO?.dealerId,
							label: dealerVO?.shortName || dealerVO?.fullName,
						};
					}),
				}}
			/>
			<DealerModal
				title={'选择经销商'}
				open={showDealerModal}
				onOk={() => setShowDealerModal(false)}
				onCancel={() => setShowDealerModal(false)}
				onFinish={async (dealerVOList) => {
					if (dealerVOList.length > 0) {
						const dealerVO = dealerVOList[0];
						onChange?.(dealerVO?.dealerId);
						setDealerList(dealerVOList);
						setShowDealerModal(false);
					}
				}}
				type={'radio'}
			/>
		</>
	);
}
