SunshineFormModal.tsx 4.24 KB
import { useEffect, useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { UForm, UModal, useUMessage } from '@uj/ui';
import { CombiForm, type FieldSchema } from '@/components';
import { useAppStore } from '@/store/useAppStore';
import { dashboardApi, operationApi, type StoreItem, type Sunshine } from '@/api';
import { errorDetail } from '@/utils/error';

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

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

/**
 * 源车辆类型字典 constants.js vehicleCategoryOpt:value 存 confId,展示 confValue。
 * 与源 add.vue 的 carType 下拉一致:提交 id、列表按字典翻译。
 */
const CAR_TYPES = [
  { value: '1', label: '置换车' },
  { value: '2', label: '报废车' },
];

/** 新增 / 修改激励字段及校验的唯一配置位置。 */
function buildFields(stores: StoreItem[], editing: boolean): FieldSchema<SunshineFormValues>[] {
  return [
    {
      name: 'sellerMerchantId',
      label: '4S门店',
      type: 'select',
      options: stores.map((s) => ({ value: s.merchantId, label: s.merchantName })),
      // 源 add.vue:编辑时门店不可改(isDisabled: paramsObj.id)。
      selectProps: { showSearch: true, optionFilterProp: 'label', disabled: editing },
      rules: [{ required: true, message: '请选择4S门店' }],
    },
    {
      name: 'carType',
      label: '车辆类型',
      type: 'select',
      options: CAR_TYPES,
      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 { currentUser } = useAppStore();
  const [saving, setSaving] = useState(false);
  const editing = Boolean(record?.id);

  // 4S 门店下拉:源 add.vue 用 getServiceStore 的 storeIdList(merchantId/merchantName)。
  const stores = useQuery({
    queryKey: ['usedcar', 'service-store', 7],
    queryFn: () => dashboardApi.getServiceStore({ scene: 7 }),
  });

  useEffect(() => {
    if (!record) return;
    form.setFieldsValue({
      sellerMerchantId: record.sellerMerchantId ?? '',
      carType: record.carType ?? '',
      sunlightInspiresPrice:
        record.sunlightInspiresPrice === undefined ? '' : String(record.sunlightInspiresPrice),
    });
  }, [form, record]);

  const save = async (values: SunshineFormValues) => {
    const store = (stores.data ?? []).find((s) => s.merchantId === values.sellerMerchantId);
    const payload: Record<string, unknown> = {
      sellerMerchantId: values.sellerMerchantId,
      sellerMerchantName: store?.merchantName ?? record?.sellerMerchantName ?? '',
      carType: values.carType,
      sunlightInspiresPrice: Number(values.sunlightInspiresPrice),
    };
    // 源 add.vue:229/231:新增带 createdBy、编辑带 updatedBy(取当前登录用户名)。
    if (editing) payload.updatedBy = currentUser.name;
    else payload.createdBy = currentUser.name;

    setSaving(true);
    try {
      if (editing) await operationApi.updateSunshine({ ...payload, id: record!.id });
      else await operationApi.createSunshine(payload);
      message.success('操作成功');
      onSaved();
      onClose();
    } catch (error) {
      message.error(errorDetail(error));
    } finally {
      setSaving(false);
    }
  };

  return (
    <UModal
      open={Boolean(record)}
      title={editing ? '修改激励' : '新增激励'}
      confirmLoading={saving}
      onCancel={onClose}
      onOk={() => form.submit()}
    >
      <CombiForm
        mode="form"
        form={form}
        fields={buildFields(stores.data ?? [], editing)}
        layout="vertical"
        onSubmit={(values) => void save(values)}
      />
    </UModal>
  );
}