index.tsx 8.52 KB
import { useMemo, useState } from 'react';
import { useMutation, useQuery } from '@tanstack/react-query';
import { UCard, UTag, UText, useUMessage } from '@uj/ui';
import {
  DataTable,
  DEFAULT_PAGE_SIZE,
  ConfirmModal,
  PageShell,
  SearchForm,
  type FieldSchema,
  type DataTableColumnsType,
  type RowActionSchema,
  type SearchPagination,
} from '@/components';
import { P, PermButton } from '@/access';
import { org, role, user, type UserPageItem, type UserPageParams } from '@/api';
import { AccountFormDrawer } from './components/AccountFormDrawer';
import { createAccountPageParams, toOrgCascaderOptions, withAllOption } from './tools/account';

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

interface AccountRow {
  id: number;
  account: string;
  name: string;
  mobile: string;
  orgPath: string;
  roleNames: string[];
  dataScopeLabel: string;
  status: number;
  lastLoginAt: string;
  source: UserPageItem;
}

function toParams(values: Record<string, unknown>, pagination: SearchPagination): UserPageParams {
  return createAccountPageParams(values, pagination);
}

export default function AccountManage() {
  const message = useUMessage();
  const [params, setParams] = useState<UserPageParams>({ current: 1, size: DEFAULT_PAGE_SIZE });
  const [queryVersion, setQueryVersion] = useState(0);
  const [accountFormOpen, setAccountFormOpen] = useState(false);
  const [editingAccount, setEditingAccount] = useState<UserPageItem>();
  const [resettingAccount, setResettingAccount] = useState<UserPageItem>();
  const [changingStatusAccount, setChangingStatusAccount] = useState<UserPageItem>();
  const resetPasswordMutation = useMutation({
    mutationFn: (account: UserPageItem) => user.resetPassword(account.userId, { password: '' }),
    onSuccess: () => {
      void message.success('密码已重置');
      setResettingAccount(undefined);
    },
    onError: (error: Error) => void message.error(error.message || '重置失败,请稍后重试'),
  });
  const statusMutation = useMutation({
    mutationFn: async (account: UserPageItem) => {
      const status = account.status === 1 ? 0 : 1;
      await user.updateStatus(account.userId, { status });
      return status;
    },
    onSuccess: (status) => {
      void message.success(`账号已${status === 1 ? '启用' : '停用'}`);
      setChangingStatusAccount(undefined);
      setQueryVersion((version) => version + 1);
    },
    onError: (error: Error) => void message.error(error.message || '操作失败,请稍后重试'),
  });
  const {
    data: result,
    isLoading,
    isFetching,
  } = useQuery({
    queryKey: ['user-page', params, queryVersion],
    queryFn: () => user.page(params),
  });
  const { data: roleOptions = [] } = useQuery({
    queryKey: ['role-options'],
    queryFn: () => role.options(),
  });
  const { data: orgTree = [] } = useQuery({ queryKey: ['org-tree'], queryFn: () => org.tree() });
  const data = useMemo<AccountRow[]>(
    () =>
      result?.records.map((item) => ({
        id: item.userId,
        account: item.account,
        name: item.name,
        mobile: item.mobile,
        orgPath: item.orgPath ?? '—',
        roleNames: item.roleNames ?? [],
        dataScopeLabel: item.dataScopeLabel ?? '—',
        status: item.status,
        lastLoginAt: item.lastLoginAt ?? '—',
        source: item,
      })) ?? [],
    [result],
  );
  const fields: FieldSchema<Record<string, unknown>>[] = [
    {
      name: 'keyword',
      label: '账号 / 姓名',
      type: 'input',
      placeholder: '模糊搜索',
    },
    {
      name: 'orgId',
      label: '所属组织',
      type: 'cascader',
      options: withAllOption(toOrgCascaderOptions(orgTree)),
    },
    {
      name: 'roleId',
      label: '角色',
      type: 'select',
      options: withAllOption(
        roleOptions.map((item) => ({ label: item.roleName, value: item.roleId })),
      ),
    },
    {
      name: 'status',
      label: '状态',
      type: 'select',
      options: withAllOption(accountStatusOptions),
    },
  ];
  const columns: DataTableColumnsType<AccountRow> = [
    {
      title: '账号',
      dataIndex: 'account',
      width: 160,
      line: 1,
      render: (value) => (
        <UText>
          <code className="uj-code">{value}</code>
        </UText>
      ),
    },
    { title: '姓名', dataIndex: 'name', width: 130, line: 1 },
    { title: '手机号', dataIndex: 'mobile', width: 120 },
    { title: '所属组织', dataIndex: 'orgPath', width: 230, line: 1 },
    {
      title: '角色',
      dataIndex: 'roleNames',
      width: 290,
      render: (names: string[]) =>
        names.length ? (
          <span className="uj-tag-list">
            {names.map((name) => (
              <UTag key={name} color="blue">
                {name}
              </UTag>
            ))}
          </span>
        ) : (
          '—'
        ),
    },
    { title: '数据域', dataIndex: 'dataScopeLabel' },
    {
      title: '状态',
      width: 90,
      render: (_, row) => (
        <UTag color={row.status === 1 ? 'green' : 'default'}>
          {row.status === 1 ? '启用' : '停用'}
        </UTag>
      ),
    },
    { title: '最后登录', dataIndex: 'lastLoginAt', width: 170 },
  ];
  const rowActions: RowActionSchema<AccountRow>[] = [
    {
      label: '编辑',
      permission: P.SYSTEM_USER_UPDATE,
      onClick: (row) => {
        setEditingAccount(row.source);
        setAccountFormOpen(true);
      },
    },
    {
      label: '重置密码',
      permission: P.SYSTEM_USER_RESET,
      onClick: (row) => setResettingAccount(row.source),
    },
    {
      label: (row) => (row.status === 1 ? '停用' : '启用'),
      permission: P.SYSTEM_USER_STATUS,
      danger: (row) => row.status === 1,
      onClick: (row) => setChangingStatusAccount(row.source),
    },
  ];
  return (
    <PageShell
      fill
      title="账号管理"
      description="维护系统用户账号,分配角色与组织归属。"
      actions={
        <PermButton
          permission={P.SYSTEM_USER_SAVE}
          onClick={() => {
            setEditingAccount(undefined);
            setAccountFormOpen(true);
          }}
        >
          新增账号
        </PermButton>
      }
    >
      <UCard className="uj-filter-card" size="small">
        <SearchForm
          fields={fields}
          initialValues={{ orgId: [''], roleId: '', status: '' }}
          onSearch={(values, pagination) => {
            setParams(toParams(values, pagination));
            setQueryVersion((version) => version + 1);
          }}
          onReset={(values, pagination) => {
            setParams(toParams(values, pagination));
            setQueryVersion((version) => version + 1);
          }}
        />
      </UCard>
      <UCard size="small" fill>
        <DataTable<AccountRow>
          rowKey="id"
          fillHeight
          columns={columns}
          rowActions={rowActions}
          actionColumnWidth={220}
          loading={isLoading || isFetching}
          pageData={result ? { ...result, records: data } : undefined}
          pagination={{
            current: params.current ?? 1,
            pageSize: params.size,
            total: result?.total ?? 0,
            onChange: (current, size) => {
              setParams((previous) => ({ ...previous, current, size }));
              setQueryVersion((version) => version + 1);
            },
          }}
        />
      </UCard>
      <AccountFormDrawer
        open={accountFormOpen}
        account={editingAccount}
        orgTree={orgTree}
        roleOptions={roleOptions}
        onClose={() => setAccountFormOpen(false)}
        onSuccess={() => {
          setAccountFormOpen(false);
          setQueryVersion((version) => version + 1);
        }}
      />
      <ConfirmModal
        open={Boolean(resettingAccount)}
        content="是否重置该用户密码"
        confirmLoading={resetPasswordMutation.isPending}
        onCancel={() => setResettingAccount(undefined)}
        onConfirm={() => {
          if (resettingAccount) resetPasswordMutation.mutate(resettingAccount);
        }}
      />
      <ConfirmModal
        open={Boolean(changingStatusAccount)}
        content={`是否${changingStatusAccount?.status === 1 ? '停用' : '启用'}用户${
          changingStatusAccount ? `“${changingStatusAccount.account}”` : ''
        }`}
        confirmLoading={statusMutation.isPending}
        onCancel={() => setChangingStatusAccount(undefined)}
        onConfirm={() => {
          if (changingStatusAccount) statusMutation.mutate(changingStatusAccount);
        }}
      />
    </PageShell>
  );
}