| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570 |
- import React, { useState, useEffect, useRef } from 'react';
- import { Plus, Search, Upload, Download, RefreshCw } from 'lucide-react';
- import { userApi } from '../api/user';
- import { userImportApi } from '../api/user/import';
- import { postApi, PostVO } from '../api/Post';
- import { UserVO, WorkstationNode } from '../types';
- import { toast } from 'sonner';
- import { Modal, Table, Input, Button, Switch, Dropdown, Space, Tooltip, Form } from 'antd';
- import { ExclamationCircleOutlined, EditOutlined, DeleteOutlined, KeyOutlined, UserSwitchOutlined, MoreOutlined } from '@ant-design/icons';
- import type { ColumnsType } from 'antd/es/table';
- import DeptTree from './user/DeptTree';
- import UserForm, { UserFormRef } from './user/UserForm';
- import UserImportForm, { UserImportFormRef } from './user/UserImportForm';
- import UserAssignRoleForm, { UserAssignRoleFormRef } from './user/UserAssignRoleForm';
- import FaceOrFingerForm, { FaceOrFingerFormRef } from './user/FaceOrFingerForm';
- interface UserManagementProps {
- subMenu: string;
- }
- export default function UserManagement({ subMenu }: UserManagementProps) {
- const [loading, setLoading] = useState(true);
- const [list, setList] = useState<UserVO[]>([]);
- const [total, setTotal] = useState(0);
- const [postList, setPostList] = useState<PostVO[]>([]);
- const [queryParams, setQueryParams] = useState({
- pageNo: 1,
- pageSize: 10,
- username: '',
- mobile: '',
- status: undefined as number | undefined,
- workstationId: undefined as number | undefined,
- createTime: [] as string[],
- });
- const [exportLoading, setExportLoading] = useState(false);
- const [resetPwdModalVisible, setResetPwdModalVisible] = useState(false);
- const [resetPwdUser, setResetPwdUser] = useState<UserVO | null>(null);
- const [resetPwdPassword, setResetPwdPassword] = useState('');
- const [resetPwdLoading, setResetPwdLoading] = useState(false);
- // 子组件引用
- const formRef = useRef<UserFormRef>(null);
- const importFormRef = useRef<UserImportFormRef>(null);
- const assignRoleFormRef = useRef<UserAssignRoleFormRef>(null);
- const faceOrFingerFormRef = useRef<FaceOrFingerFormRef>(null);
- // 获取用户列表
- const getList = async (params?: typeof queryParams) => {
- const currentParams = params || queryParams;
- setLoading(true);
- try {
- const response = await userApi.getUserPage(currentParams);
- setList(response.list || []);
- setTotal(response.total || 0);
- } catch (error: any) {
- toast.error(error.message || '获取用户列表失败');
- } finally {
- setLoading(false);
- }
- };
- // 加载岗位列表
- useEffect(() => {
- const loadPostList = async () => {
- try {
- const response = await postApi.getSimplePostList();
- // 处理响应数据,可能是直接返回数组,也可能包装在 data 中
- const posts = (response as any)?.data || response;
- setPostList(Array.isArray(posts) ? posts : []);
- } catch (error) {
- console.error('加载岗位列表失败:', error);
- setPostList([]);
- }
- };
- loadPostList();
- }, []);
- useEffect(() => {
- getList();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [queryParams.pageNo, queryParams.pageSize, queryParams.workstationId]);
- // 搜索
- const handleQuery = () => {
- const newParams = { ...queryParams, pageNo: 1 };
- setQueryParams(newParams);
- getList(newParams);
- };
- // 重置搜索
- const resetQuery = () => {
- // 先清空表格数据
- setList([]);
- setTotal(0);
- // 重置所有查询参数
- const resetParams = {
- pageNo: 1,
- pageSize: 10,
- username: '',
- mobile: '',
- status: undefined as number | undefined,
- workstationId: undefined as number | undefined,
- createTime: [] as string[],
- };
- setQueryParams(resetParams);
- // 立即使用重置后的参数获取列表,不需要等待状态更新
- getList(resetParams);
- };
- // 处理部门节点点击
- const handleDeptNodeClick = (node: WorkstationNode) => {
- setQueryParams(prev => ({ ...prev, workstationId: node.id, pageNo: 1 }));
- };
- // 打开表单
- const openForm = (type: string, id?: number) => {
- formRef.current?.open(type, id);
- };
- // 用户导入
- const handleImport = () => {
- importFormRef.current?.open();
- };
- // 导出用户
- const handleExport = async () => {
- Modal.confirm({
- title: '确认导出',
- icon: <ExclamationCircleOutlined />,
- content: '确定要导出用户数据吗?',
- okText: '确定导出',
- cancelText: '取消',
- onOk: async () => {
- setExportLoading(true);
- try {
- const blob = await userImportApi.exportUser(queryParams);
- const url = window.URL.createObjectURL(blob);
- const link = document.createElement('a');
- link.href = url;
- link.download = '用户数据.xls';
- document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
- window.URL.revokeObjectURL(url);
- toast.success('导出成功');
- } catch (error: any) {
- toast.error(error.message || '导出失败');
- } finally {
- setExportLoading(false);
- }
- },
- });
- };
- // 修改用户状态
- const handleStatusChange = async (row: UserVO, newChecked: boolean) => {
- const newStatus = newChecked ? 0 : 1; // 0是开启,1是关闭
- const text = newStatus === 0 ? '启用' : '停用';
-
- // 使用 antd 的确认弹框
- Modal.confirm({
- title: '确认操作',
- icon: <ExclamationCircleOutlined />,
- content: `确定要${text}用户"${row.username}"吗?`,
- okText: '确定',
- cancelText: '取消',
- onOk: async () => {
- try {
- await userApi.updateUserStatus(row.id, newStatus);
- toast.success(`用户${text}成功`);
- // 刷新列表以更新状态
- await getList();
- } catch (error: any) {
- toast.error(error.message || `用户${text}失败`);
- // 接口调用失败,刷新列表以恢复Switch状态
- await getList();
- }
- },
- onCancel: async () => {
- // 用户取消操作,立即刷新列表以恢复Switch状态
- // 由于Switch是受控组件,刷新列表后会自动恢复到原始状态(基于row.status)
- await getList();
- },
- });
- };
- // 删除用户
- const handleDelete = async (id: number, username?: string) => {
- Modal.confirm({
- title: '确认删除',
- icon: <ExclamationCircleOutlined />,
- content: (
- <div>
- <p>确定要删除用户 <strong>"{username || '该用户'}"</strong> 吗?</p>
- <p style={{ color: '#ff4d4f', marginTop: '8px' }}>删除后无法恢复,请谨慎操作!</p>
- </div>
- ),
- okText: '确定删除',
- okType: 'danger',
- cancelText: '取消',
- onOk: async () => {
- try {
- await userApi.deleteUser(id);
- toast.success('删除成功');
- await getList();
- } catch (error: any) {
- toast.error(error.message || '删除失败');
- }
- },
- });
- };
- // 重置密码
- const handleResetPwd = (row: UserVO) => {
- setResetPwdUser(row);
- setResetPwdPassword('');
- setResetPwdModalVisible(true);
- };
- // 提交重置密码
- const submitResetPassword = async () => {
- if (!resetPwdPassword.trim()) {
- toast.error('请输入新密码');
- return;
- }
- if (!resetPwdUser) {
- return;
- }
- setResetPwdLoading(true);
- try {
- await userApi.resetUserPassword(resetPwdUser.id, resetPwdPassword);
- toast.success(`修改成功,新密码是:${resetPwdPassword}`);
- setResetPwdModalVisible(false);
- setResetPwdPassword('');
- setResetPwdUser(null);
- } catch (error: any) {
- toast.error(error.message || '重置密码失败');
- } finally {
- setResetPwdLoading(false);
- }
- };
- // 分配角色
- const handleRole = (row: UserVO) => {
- assignRoleFormRef.current?.open(row);
- };
- // 打开指纹或人脸弹框
- const openFaceOrFingerForm = (type: string, row: UserVO) => {
- faceOrFingerFormRef.current?.open(type, row.id, row);
- };
- // 表格列配置
- const columns: ColumnsType<UserVO> = [
- {
- title: '序号',
- width: '5%',
- render: (_: any, __: UserVO, index: number) => {
- return (queryParams.pageNo - 1) * queryParams.pageSize + index + 1;
- },
- },
- {
- title: '用户编号',
- dataIndex: 'id',
- width: '8%',
- },
- {
- title: '账号',
- dataIndex: 'username',
- width: '10%',
- },
- {
- title: '用户昵称',
- dataIndex: 'nickname',
- width: '10%',
- },
- {
- title: '手机号码',
- dataIndex: 'mobile',
- width: '12%',
- render: (text: string) => text || '-',
- },
- {
- title: '部门',
- width: '10%',
- render: (_: any, record: UserVO) => {
- return (record as any).deptName || '-';
- },
- },
- {
- title: '岗位',
- width: '10%',
- render: (_: any, record: UserVO) => {
- // 根据 postIds 匹配岗位名称
- if (record.postIds && Array.isArray(record.postIds) && record.postIds.length > 0) {
- const postNames = record.postIds
- .map((postId: string | number) => {
- // 将 postId 转换为数字进行比较
- const id = typeof postId === 'string' ? Number(postId) : postId;
- const post = postList.find(p => p.id === id);
- return post ? post.name : null;
- })
- .filter((name: string | null) => name !== null);
-
- const displayText = postNames.length > 0 ? postNames.join(',') : '-';
-
- return (
- <Tooltip
- title={
- <div style={{ maxHeight: '200px', overflowY: 'auto', maxWidth: '300px' }}>
- {displayText}
- </div>
- }
- placement="topLeft"
- >
- <div
- style={{
- overflow: 'hidden',
- textOverflow: 'ellipsis',
- whiteSpace: 'nowrap',
- cursor: 'help',
- }}
- >
- {displayText}
- </div>
- </Tooltip>
- );
- }
- return '-';
- },
- },
- {
- title: '人脸',
- width: '8%',
- render: (_: any, record: UserVO) => (
- <Button
- type="link"
- onClick={() => openFaceOrFingerForm('face', record)}
- style={{ padding: 0 }}
- >
- 查看
- </Button>
- ),
- },
- {
- title: '状态',
- width: '8%',
- render: (_: any, record: UserVO) => (
- <Switch
- checked={record.status === 0}
- onChange={(checked) => handleStatusChange(record, checked)}
- />
- ),
- },
- {
- title: '操作',
- width: '10%',
- align: 'center',
- render: (_: any, record: UserVO) => {
- const menuItems = [
- {
- key: 'delete',
- label: '删除',
- icon: <DeleteOutlined />,
- onClick: () => handleDelete(record.id, record.username),
- },
- {
- key: 'resetPwd',
- label: '重置密码',
- icon: <KeyOutlined />,
- onClick: () => handleResetPwd(record),
- },
- {
- key: 'assignRole',
- label: '分配角色',
- icon: <UserSwitchOutlined />,
- onClick: () => handleRole(record),
- },
- ];
- return (
- <Space>
- <Button
- type="link"
- icon={<EditOutlined />}
- onClick={() => openForm('update', record.id)}
- title="编辑"
- />
- <Dropdown
- menu={{ items: menuItems }}
- trigger={['click']}
- >
- <Button
- type="link"
- icon={<MoreOutlined />}
- title="更多"
- />
- </Dropdown>
- </Space>
- );
- },
- },
- ];
- return (
- <div className="flex gap-6 h-full">
- {/* 左侧岗位树 */}
- <div className="w-80 flex-shrink-0">
- <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm h-full overflow-hidden flex flex-col">
- <DeptTree onNodeClick={handleDeptNodeClick} />
- </div>
- </div>
- {/* 右侧用户列表 */}
- <div className="flex-1 min-w-0">
- <div className="space-y-6">
- {/* 搜索栏 */}
- <div className="bg-white rounded-xl border border-gray-200/50 shadow-sm p-5">
- <div className="flex items-center justify-between gap-4 flex-wrap">
- {/* 搜索输入框 */}
- <div className="flex items-center gap-3 flex-wrap flex-1">
- <div className="flex items-center gap-3">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">账号:</label>
- <Input
- value={queryParams.username}
- onChange={(e) => setQueryParams({ ...queryParams, username: e.target.value })}
- onPressEnter={handleQuery}
- placeholder="请输入账号"
- style={{ width: 192 }}
- allowClear
- />
- </div>
- <div className="flex items-center gap-3">
- <label className="text-sm font-medium text-gray-700 whitespace-nowrap">手机号码:</label>
- <Input
- value={queryParams.mobile}
- onChange={(e) => setQueryParams({ ...queryParams, mobile: e.target.value })}
- onPressEnter={handleQuery}
- placeholder="请输入手机号码"
- style={{ width: 192 }}
- allowClear
- />
- </div>
- </div>
- {/* 操作按钮组 */}
- <Space>
- <Button
- type="primary"
- icon={<Search className="w-4 h-4" />}
- onClick={handleQuery}
- >
- 搜索
- </Button>
-
- <Button
- icon={<RefreshCw className="w-4 h-4" />}
- onClick={resetQuery}
- >
- 重置
- </Button>
-
- <Button
- type="primary"
- icon={<Plus className="w-4 h-4" />}
- onClick={() => openForm('create')}
- >
- 新增
- </Button>
-
- <Button
- icon={<Upload className="w-4 h-4" />}
- onClick={handleImport}
- >
- 导入
- </Button>
-
- <Button
- icon={<Download className="w-4 h-4" />}
- onClick={handleExport}
- loading={exportLoading}
- >
- 导出
- </Button>
- </Space>
- </div>
- </div>
- {/* 表格容器 */}
- <div className="bg-white rounded-2xl border border-gray-200/50 shadow-sm overflow-hidden">
- <Table
- columns={columns}
- dataSource={list}
- rowKey="id"
- loading={loading}
- pagination={false}
- scroll={{ x: 'max-content' }}
- />
- </div>
- {/* 分页 */}
- {!loading && list.length > 0 && (
- <div className="bg-white rounded-lg border border-gray-200 px-6 py-4">
- <div className="flex items-center justify-between">
- <div className="text-sm text-gray-600">
- 共 <span className="text-blue-600 font-medium">{total}</span> 条记录
- </div>
- <div className="flex gap-2">
- <Button
- onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo - 1 })}
- disabled={queryParams.pageNo <= 1}
- >
- 上一页
- </Button>
- <span className="px-4 py-2 text-sm text-gray-600 flex items-center">
- {queryParams.pageNo} / {Math.ceil(total / queryParams.pageSize) || 1}
- </span>
- <Button
- onClick={() => setQueryParams({ ...queryParams, pageNo: queryParams.pageNo + 1 })}
- disabled={queryParams.pageNo >= Math.ceil(total / queryParams.pageSize)}
- >
- 下一页
- </Button>
- </div>
- </div>
- </div>
- )}
- </div>
- </div>
- {/* 相关子组件 */}
- <UserForm ref={formRef} onSuccess={getList} />
- <UserImportForm ref={importFormRef} onSuccess={getList} />
- <UserAssignRoleForm ref={assignRoleFormRef} onSuccess={getList} />
- <FaceOrFingerForm ref={faceOrFingerFormRef} onSuccess={getList} />
- {/* 重置密码弹框 */}
- <Modal
- title="重置密码"
- open={resetPwdModalVisible}
- onOk={submitResetPassword}
- onCancel={() => {
- setResetPwdModalVisible(false);
- setResetPwdPassword('');
- setResetPwdUser(null);
- }}
- confirmLoading={resetPwdLoading}
- okText="确定"
- cancelText="取消"
- width={500}
- >
- <div style={{ marginTop: 16 }}>
- <p style={{ marginBottom: 12 }}>
- 请输入用户 <strong>"{resetPwdUser?.username}"</strong> 的新密码:
- </p>
- <Input.Password
- placeholder="请输入新密码"
- value={resetPwdPassword}
- onChange={(e) => setResetPwdPassword(e.target.value)}
- onPressEnter={submitResetPassword}
- autoFocus
- />
- </div>
- </Modal>
- </div>
- );
- }
|