import { DealerSelect } from '@/components';
import { generateShortId } from '@/utils';
import {
	ModalForm,
	ProFormDigit,
	ProFormTextArea,
} from '@ant-design/pro-components';
import { message } from 'antd';

interface IExpenseProvisionCreateProps {
	onFinish?: (expenseProvision: BusinessAPI.ExpenseProvision) => void;
	visible: boolean;
	onClose: () => void;
	editMode?: boolean;
	expenseProvision?: BusinessAPI.ExpenseProvision;
}

export default function ExpenseProvisionCreate(
	props: IExpenseProvisionCreateProps,
) {
	const {
		onFinish,
		visible,
		onClose,
		editMode = false,
		expenseProvision: initialExpenseProvision,
	} = props;

	return (
		<ModalForm<BusinessAPI.ExpenseProvision>
			title={editMode ? '编辑计提' : '添加计提'}
			open={visible}
			onOpenChange={(open) => {
				if (!open) {
					onClose();
				}
			}}
			modalProps={{
				destroyOnClose: true,
			}}
			initialValues={initialExpenseProvision}
			onFinish={async (values) => {
				// 编辑模式下保留原有ID，新增模式下生成新ID
				const finalExpenseProvision: BusinessAPI.ExpenseProvision = {
					...values,
					expenseProvisionId: editMode
						? initialExpenseProvision?.expenseProvisionId ||
							values.expenseProvisionId
						: values.expenseProvisionId || generateShortId(),
				};

				onFinish?.(finalExpenseProvision);
				message.success(editMode ? '保存成功' : '添加成功');
				return true;
			}}
		>
			{/* 编辑模式下客户名称不可修改 */}
			<DealerSelect disabled={editMode} />

			<ProFormDigit
				name="provisionAmount"
				label="计提金额"
				placeholder="请输入计提金额"
				fieldProps={{
					prefix: '¥',
					precision: 2,
					min: 0,
					style: { width: '100%' },
				}}
				rules={[
					{ required: true, message: '请输入计提金额' },
					{
						type: 'number',
						min: 0.01,
						message: '计提金额必须大于0',
					},
				]}
			/>

			<ProFormTextArea
				name="remark"
				label="备注（可选）"
				placeholder="请输入备注信息"
				fieldProps={{
					autoSize: { minRows: 3, maxRows: 6 },
					showCount: true,
					maxLength: 200,
				}}
			/>
		</ModalForm>
	);
}
