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

export interface IDealerSearchProps extends ProFormSelectProps {
	form: FormInstance;
	selectedList?: IDealerModalProps['selectedList'];
	onFinish?: (dealerVOList: BusinessAPI.DealerVO[]) => void;
	params: BusinessAPI.DealerPageQry;
}

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

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

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