SunshineFormModal.tsx 2.75 KB
import { useEffect, useState } from 'react';
import { UForm, UModal, useUMessage } from '@uj/ui';
import { CombiForm, type FieldSchema } from '@/components';
import { operationApi, type Sunshine } from '@/api';

interface Props {
  record: Sunshine | null;
  onClose: () => void;
  onSaved: () => void;
}

type SunshineFormValues = {
  sellerMerchantName: string;
  carType: string;
  sunlightInspiresPrice: string;
};

/** 新增 / 修改激励字段及校验的唯一配置位置。 */
const FIELDS: FieldSchema<SunshineFormValues>[] = [
  {
    name: 'sellerMerchantName',
    label: '4S门店',
    type: 'input',
    inputProps: { maxLength: 50 },
    rules: [{ required: true, message: '请输入4S门店' }],
  },
  {
    name: 'carType',
    label: '车辆类型',
    type: 'input',
    inputProps: { maxLength: 50 },
    rules: [{ required: true, message: '请输入车辆类型' }],
  },
  {
    name: 'sunlightInspiresPrice',
    label: '激励价格(元)',
    type: 'input',
    inputProps: { inputMode: 'decimal', maxLength: 10 },
    rules: [
      { required: true, message: '请输入激励价格' },
      { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入最多两位小数的正数' },
    ],
  },
];

/** 新增与修改共用的独立表单弹窗。 */
export default function SunshineFormModal({ record, onClose, onSaved }: Props) {
  const [form] = UForm.useForm<SunshineFormValues>();
  const message = useUMessage();
  const [saving, setSaving] = useState(false);
  const editing = Boolean(record?.id);
  useEffect(() => {
    if (!record) return;
    form.setFieldsValue({
      sellerMerchantName: record.sellerMerchantName,
      carType: record.carType,
      sunlightInspiresPrice:
        record.sunlightInspiresPrice === undefined ? '' : String(record.sunlightInspiresPrice),
    });
  }, [form, record]);
  const save = async (values: SunshineFormValues) => {
    setSaving(true);
    try {
      const price = Number(values.sunlightInspiresPrice);
      const payload = {
        sellerMerchantName: String(values.sellerMerchantName),
        carType: String(values.carType),
        sunlightInspiresPrice: price,
      };
      if (editing) await operationApi.updateSunshine({ ...payload, id: record!.id });
      else await operationApi.createSunshine(payload);
      message.success('操作成功');
      onSaved();
      onClose();
    } finally {
      setSaving(false);
    }
  };
  return (
    <UModal
      open={Boolean(record)}
      title={editing ? '修改激励' : '新增激励'}
      confirmLoading={saving}
      onCancel={onClose}
      onOk={() => form.submit()}
    >
      <CombiForm
        mode="form"
        form={form}
        fields={FIELDS}
        layout="vertical"
        onSubmit={(values) => void save(values)}
      />
    </UModal>
  );
}