RoleModal.tsx 5.02 KB
import { useEffect } from 'react';
import { message } from 'antd';
import { useMutation } from '@tanstack/react-query';
import { UForm, UModal } from '@uj/ui';
import { role, type RolePageItem } from '@/api';
import { CombiForm, type FieldSchema } from '@/components';
import { dataScopeOptions } from '@/constants/dataScope';

interface RoleFormValues extends Record<string, unknown> {
  roleName: string;
  roleCode: string;
  sort: string;
  status: number;
  description?: string;
  defaultDataScope: number;
}

export interface RoleModalProps {
  open: boolean;
  roleItem?: RolePageItem;
  onCancel: () => void;
  onSuccess: () => void;
}

const statusOptions = [
  { label: '启用', value: 1 },
  { label: '停用', value: 0 },
];

export function RoleModal({ open, roleItem, onCancel, onSuccess }: RoleModalProps) {
  const [form] = UForm.useForm<RoleFormValues>();
  const isEdit = Boolean(roleItem);
  const saveMutation = useMutation({
    mutationFn: (values: RoleFormValues) => {
      const payload = {
        roleName: values.roleName.trim(),
        defaultDataScope: Number(1),
        sort: Number(values.sort),
        status: Number(values.status),
        description: values.description?.trim() || undefined,
      };
      return roleItem
        ? role.updateSystem({ ...payload, roleId: roleItem.roleId })
        : role.createSystem({ ...payload, roleCode: values.roleCode.trim() });
    },
    onSuccess: () => {
      void message.success(isEdit ? '角色已保存' : '角色已创建');
      onSuccess();
    },
    onError: (error: Error) => void message.error(error.message || '保存失败,请稍后重试'),
  });

  useEffect(() => {
    if (!open) return;
    form.setFieldsValue({
      roleName: roleItem?.roleName ?? '',
      roleCode: roleItem?.roleCode ?? '',
      sort: String(roleItem?.sort ?? 10),
      status: roleItem?.status ?? 1,
      description: roleItem?.description ?? '',
      defaultDataScope: Number(roleItem?.defaultDataScope ?? 1),
    });
  }, [form, open, roleItem]);

  const fields: FieldSchema<RoleFormValues>[] = [
    {
      name: 'roleName',
      label: '角色名称',
      type: 'input',
      section: '基本信息',
      inputProps: { maxLength: 20 },
      rules: [
        { required: true, message: '请输入角色名称' },
        { max: 20, message: '角色名称不能超过 20 个字符' },
      ],
    },
    {
      name: 'roleCode',
      label: '角色编码',
      type: 'input',
      section: '基本信息',
      disabled: isEdit,
      inputProps: { maxLength: 50 },
      placeholder: '例如:REGION_OPS',
      rules: [
        { required: true, message: '请输入角色编码' },
        { pattern: /^[A-Z0-9_]+$/, message: '仅支持大写字母、数字和下划线' },
      ],
    },
    {
      name: 'sort',
      label: '显示排序',
      type: 'input',
      section: '基本信息',
      inputProps: { inputMode: 'numeric' },
      rules: [{ pattern: /^\d+$/, message: '请输入整数' }],
    },
    {
      name: 'status',
      label: '状态',
      type: 'select',
      section: '基本信息',
      options: statusOptions,
      selectProps: { allowClear: false },
    },
    {
      name: 'description',
      label: '角色描述',
      type: 'textarea',
      section: '基本信息',
      itemStyle: { gridColumn: '1 / -1' },
      textareaProps: { maxLength: 200, rows: 2 },
      placeholder: '选填,用于说明角色的职责边界',
      rules: [{ max: 200, message: '角色描述不能超过 200 个字符' }],
    },
    {
      name: 'defaultDataScope',
      label: '默认数据域',
      type: 'select',
      disabled: true,
      section: '数据域',
      options: dataScopeOptions,
      rules: [{ required: true, message: '请选择默认数据域' }],
    },
  ];

  return (
    <UModal
      open={open}
      title={isEdit ? '编辑角色' : '新增角色'}
      width={520}
      okText="保存"
      cancelText="取消"
      confirmLoading={saveMutation.isPending}
      onCancel={onCancel}
      onOk={() => form.submit()}
      styles={{ body: { maxHeight: '65vh', overflowY: 'auto', paddingTop: 8 } }}
    >
      <CombiForm<RoleFormValues>
        mode="form"
        form={form}
        layout="vertical"
        initialValues={{ sort: '10', status: 1 }}
        fields={fields}
        onSubmit={(values) => saveMutation.mutate(values)}
        sectionContentStyle={twoColumnStyle}
        renderSectionTitle={(title) => <SectionTitle>{title}</SectionTitle>}
      />
    </UModal>
  );
}

const twoColumnStyle = { display: 'grid', gridTemplateColumns: '1fr 1fr', columnGap: 12 };
function SectionTitle({ children }: { children: string }) {
  return (
    <h3 style={sectionTitleStyle}>
      <span style={sectionMarkerStyle} />
      {children}
    </h3>
  );
}
const sectionTitleStyle = {
  alignItems: 'center',
  borderBottom: '1px solid #eef0f4',
  display: 'flex',
  fontSize: 14,
  gap: 6,
  lineHeight: '16px',
  margin: '0 0 12px',
  padding: '0 0 8px',
};
const sectionMarkerStyle = { backgroundColor: '#315ce8', borderRadius: 2, height: 10, width: 3 };