import { business } from '@/services';
import { generateShortId } from '@/utils';
import {
	ModalForm,
	ProFormMoney,
	ProFormSelect,
	ProFormTextArea,
} from '@ant-design/pro-components';
import { message } from 'antd';

interface IExpenseCostCreateProps {
	onFinish?: (expressCost: BusinessAPI.ExpenseCost) => void;
	visible: boolean;
	onClose: () => void;
	editMode?: boolean;
	cost?: BusinessAPI.CostVO;
	expenseCost?: BusinessAPI.ExpenseCost;
}

export default function ExpenseCostCreate(props: IExpenseCostCreateProps) {
	const {
		onFinish,
		visible,
		onClose,
		editMode = false,
		cost: costVO,
		expenseCost: initialExpenseCost,
	} = props;

	return (
		<ModalForm<BusinessAPI.ExpenseCost>
			title={editMode ? '编辑费用' : '添加费用'}
			open={visible}
			onOpenChange={(open) => {
				if (!open) {
					onClose();
				}
			}}
			modalProps={{
				destroyOnClose: true,
			}}
			initialValues={{
				...initialExpenseCost,
				...(costVO && {
					costId: costVO.costId,
					costName: costVO.name,
				}),
			}}
			onFinish={async (values) => {
				// 编辑模式下保留原有ID，新增模式下生成新ID
				const finalExpenseCost: BusinessAPI.ExpenseCost = {
					...values,
					expenseCostId: editMode
						? initialExpenseCost?.expenseCostId || values.expenseCostId
						: values.expenseCostId || generateShortId(),
				};

				onFinish?.(finalExpenseCost);
				message.success(editMode ? '保存成功' : '添加成功');
				return true;
			}}
		>
			{/* 编辑模式或指定费用类型时，费用类型不可修改 */}
			<ProFormSelect
				disabled={editMode || !!costVO}
				name="costId"
				label="费用类型"
				rules={[{ required: true, message: '请选择费用类型' }]}
				params={{
					type: 'EXPENSE_TYPE',
				}}
				request={async (params) => {
					const { data } = await business.cost.listCost({
						costListQry: {
							...params,
						},
					});

					return (
						data?.map((item) => {
							return {
								label: item.name,
								value: item.costId,
							};
						}) || []
					);
				}}
			/>

			<ProFormMoney
				name="expenseAmount"
				label="金额"
				placeholder="请输入费用金额"
				fieldProps={{
					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>
	);
}
