提交一下 换git仓库了

This commit is contained in:
linxd
2025-06-23 21:39:51 +08:00
parent 9eb1bed092
commit c74aefb93d
11 changed files with 741 additions and 672 deletions

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import { Input, Button, Badge, Avatar, Space, Tabs, Checkbox, Row, Col, Card, Empty, Divider, Alert } from 'antd';
import { SearchOutlined, UserOutlined, TeamOutlined, CheckCircleOutlined } from '@ant-design/icons';
import './EvaluateTaskPersonnelSelector.less';
@ -75,33 +75,19 @@ const EvaluateTaskPersonnelSelector: React.FC<EvaluateTaskPersonnelSelectorProps
* 部门数据列表
* 实际项目中可通过API获取
*/
const departments: Department[] = [
const departments: Department[] = useMemo(() => [
{ id: '1', name: '采购部' },
{ id: '2', name: '技术部' },
{ id: '3', name: '质量部' },
{ id: '4', name: '生产部' },
{ id: '5', name: '财务部' },
];
/**
* 初始化人员数据和已选状态
*/
useEffect(() => {
// 加载人员数据模拟API请求
fetchPersonnelData();
// 设置已选人员
if (selectedPersonnel && selectedPersonnel.length > 0) {
const selectedIds = selectedPersonnel.map(item => item.id);
setSelectedKeys(selectedIds);
}
}, [selectedPersonnel]);
], []);
/**
* 模拟获取人员数据
* 实际项目中替换为API调用
*/
const fetchPersonnelData = () => {
const fetchPersonnelData = useCallback(() => {
// 模拟API调用获取评价人员
const mockPersonnel: PersonnelItem[] = [
{ id: '1', name: '张三', department: '采购部', position: '采购经理' },
@ -119,46 +105,59 @@ const EvaluateTaskPersonnelSelector: React.FC<EvaluateTaskPersonnelSelectorProps
];
setPersonnel(mockPersonnel);
};
}, []);
/**
* 初始化人员数据和已选状态
*/
useEffect(() => {
// 加载人员数据模拟API请求
fetchPersonnelData();
// 设置已选人员
if (selectedPersonnel && selectedPersonnel.length > 0) {
const selectedIds = selectedPersonnel.map(item => item.id);
setSelectedKeys(selectedIds);
}
}, [fetchPersonnelData, selectedPersonnel]);
/**
* 处理搜索
* @param {string} value - 搜索关键词
*/
const handleSearch = (value: string) => {
const handleSearch = useCallback((value: string) => {
setKeyword(value);
};
}, []);
/**
* 处理Tab切换
* @param {string} key - 选中的Tab键值
*/
const handleTabChange = (key: string) => {
const handleTabChange = useCallback((key: string) => {
setActiveTab(key);
};
}, []);
/**
* 处理单个人员选择
* @param {string} personnelId - 人员ID
* @param {boolean} checked - 是否选中
*/
const handleSelect = (personnelId: string, checked: boolean) => {
let newSelectedKeys = [...selectedKeys];
if (checked) {
newSelectedKeys.push(personnelId);
} else {
newSelectedKeys = newSelectedKeys.filter(id => id !== personnelId);
}
setSelectedKeys(newSelectedKeys);
};
const handleSelect = useCallback((personnelId: string, checked: boolean) => {
setSelectedKeys(prevKeys => {
if (checked) {
return [...prevKeys, personnelId];
} else {
return prevKeys.filter(id => id !== personnelId);
}
});
}, []);
/**
* 处理部门人员全选
* @param {string} deptId - 部门ID
* @param {boolean} checked - 是否全选
*/
const handleSelectAll = (deptId: string, checked: boolean) => {
const handleSelectAll = useCallback((deptId: string, checked: boolean) => {
const deptName = departments.find(d => d.id === deptId)?.name || '';
const deptPersonnel = personnel.filter(p =>
p.department === deptName &&
@ -166,38 +165,64 @@ const EvaluateTaskPersonnelSelector: React.FC<EvaluateTaskPersonnelSelectorProps
);
const deptPersonnelIds = deptPersonnel.map(p => p.id);
let newSelectedKeys = [...selectedKeys];
if (checked) {
// 添加该部门所有人员
deptPersonnelIds.forEach(id => {
if (!newSelectedKeys.includes(id)) {
newSelectedKeys.push(id);
}
});
} else {
// 移除该部门所有人员
newSelectedKeys = newSelectedKeys.filter(id => !deptPersonnelIds.includes(id));
}
setSelectedKeys(newSelectedKeys);
};
setSelectedKeys(prevKeys => {
if (checked) {
// 添加该部门所有人员
const newKeys = new Set([...prevKeys, ...deptPersonnelIds]);
return Array.from(newKeys);
} else {
// 移除该部门所有人员
return prevKeys.filter(id => !deptPersonnelIds.includes(id));
}
});
}, [departments, keyword, personnel]);
/**
* 确认选择
* 将选中的人员ID列表转换为人员对象列表
*/
const handleConfirm = () => {
const handleConfirm = useCallback(() => {
const selectedItems = personnel.filter(item => selectedKeys.includes(item.id));
onSelect(selectedItems);
};
}, [onSelect, personnel, selectedKeys]);
/**
* 计算各部门已选人数
* @param {string} deptId - 部门ID
* @returns {number} - 已选人数
*/
const getSelectedCountByDept = useCallback((deptId: string) => {
const deptName = departments.find(d => d.id === deptId)?.name || '';
const deptPersonnel = personnel.filter(p => p.department === deptName);
const selectedCount = deptPersonnel.filter(p => selectedKeys.includes(p.id)).length;
return selectedCount;
}, [departments, personnel, selectedKeys]);
/**
* 渲染Tab标签
* @param {Department} dept - 部门信息
* @returns {React.ReactNode} - 渲染结果
*/
const renderTabTitle = useCallback((dept: Department) => {
const selectedCount = getSelectedCountByDept(dept.id);
return (
<Badge
count={selectedCount > 0 ? selectedCount : 0}
size="small"
offset={[5, -3]}
style={{ backgroundColor: selectedCount > 0 ? '#1890ff' : '#d9d9d9' }}
>
<span>{dept.name}</span>
</Badge>
);
}, [getSelectedCountByDept]);
/**
* 渲染部门下的人员列表
* @param {string} deptId - 部门ID
* @returns {React.ReactNode} - 渲染结果
*/
const renderDepartmentPersonnel = (deptId: string) => {
const renderDepartmentPersonnel = useCallback((deptId: string) => {
// 获取部门名称
const deptName = departments.find(d => d.id === deptId)?.name || '';
@ -273,38 +298,19 @@ const EvaluateTaskPersonnelSelector: React.FC<EvaluateTaskPersonnelSelectorProps
</Card>
</div>
);
};
}, [departments, handleSelect, handleSelectAll, keyword, personnel, selectedKeys]);
/**
* 计算各部门已选人数
* @param {string} deptId - 部门ID
* @returns {number} - 已选人数
*/
const getSelectedCountByDept = (deptId: string) => {
const deptName = departments.find(d => d.id === deptId)?.name || '';
const deptPersonnel = personnel.filter(p => p.department === deptName);
const selectedCount = deptPersonnel.filter(p => selectedKeys.includes(p.id)).length;
return selectedCount;
};
/**
* 渲染Tab标签
* @param {Department} dept - 部门信息
* @returns {React.ReactNode} - 渲染结果
*/
const renderTabTitle = (dept: Department) => {
const selectedCount = getSelectedCountByDept(dept.id);
return (
<Badge
count={selectedCount > 0 ? selectedCount : 0}
size="small"
offset={[5, -3]}
style={{ backgroundColor: selectedCount > 0 ? '#1890ff' : '#d9d9d9' }}
// 使用useMemo优化部门Tab的渲染
const departmentTabs = useMemo(() => {
return departments.map(dept => (
<TabPane
tab={renderTabTitle(dept)}
key={dept.id}
>
<span>{dept.name}</span>
</Badge>
);
};
{renderDepartmentPersonnel(dept.id)}
</TabPane>
));
}, [departments, renderDepartmentPersonnel, renderTabTitle]);
return (
<div className="evaluate-task-personnel-selector">
@ -346,14 +352,7 @@ const EvaluateTaskPersonnelSelector: React.FC<EvaluateTaskPersonnelSelectorProps
onChange={handleTabChange}
className="department-tabs"
>
{departments.map(dept => (
<TabPane
tab={renderTabTitle(dept)}
key={dept.id}
>
{renderDepartmentPersonnel(dept.id)}
</TabPane>
))}
{departmentTabs}
</Tabs>
{/* 底部确认按钮区域 */}

View File

@ -7,15 +7,11 @@ import {
Select,
Form,
InputNumber,
Upload,
message,
Divider,
Switch,
} from 'antd';
import {
PlusOutlined,
MinusCircleOutlined,
UploadOutlined,
PlusCircleOutlined,
DeleteOutlined,
} from '@ant-design/icons';
@ -24,14 +20,9 @@ import { StarLevel, StarLevelText } from '@/dicts/supplierTemplateDict';
import { generateUUID } from '@/utils/utils';
import './EvaluateTemplateTable.less';
// 注意这里我们使用SupplierEvaluate命名空间中的类型
// 类型定义已移动到 src/typings.d.ts 文件中
const { Option } = Select;
const { TextArea } = Input;
// 移除类型定义,使用全局命名空间中的类型
interface EvaluateTemplateTableProps {
value?: any[];
onChange?: (value: any[]) => void;
@ -133,7 +124,7 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
const convertTableDataToApiData = (tableData: TableRowItem[]): any[] => {
// 按一级指标分组
const groupedByLevel1 = tableData.reduce((acc: Record<string, TableRowItem[]>, item: TableRowItem) => {
// 为空的baseIndicator也需要分组使用特殊键标识 - 这是关键修复
// 为空的baseIndicator也需要分组使用特殊键标识
const groupKey = item.baseIndicator || `empty-${item.key}`;
if (!acc[groupKey]) {
@ -151,7 +142,6 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
// 生成唯一的临时ID
const tempStId = `temp-st-${generateUUID(16)}-${stIndex}`;
// 简化数据转换,使用可选链和短路评估
return {
id: firstItem.stId || tempStId,
baseIndicator: firstItem.baseIndicator || '',
@ -182,43 +172,36 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
fetchIndicatorTypes();
}, []);
// 确保数据中没有重复的key
const ensureUniqueKeys = (data: TableRowItem[]): TableRowItem[] => {
const keyMap = new Map<string, boolean>();
return data.map((item, index) => {
if (!item.key || item.key.includes('undefined') || keyMap.has(item.key)) {
const newKey = `fixed-${generateUUID(32)}-${index}`;
return { ...item, key: newKey };
}
keyMap.set(item.key, true);
return item;
});
};
// 单独处理value变化
useEffect(() => {
// 初始化表格数据或value变化时更新
if (value && value.length > 0) {
console.log('useEffect中接收到的value:', value);
// 避免不必要的状态更新,比较新旧数据是否相同
const currentValueStr = JSON.stringify(value);
// 注意当dataSource为空时避免调用convertTableDataToApiData
const currentDataSourceApiStr = dataSource.length > 0 ?
JSON.stringify(convertTableDataToApiData(dataSource)) : '';
if (currentValueStr !== currentDataSourceApiStr) {
const tableData = convertApiDataToTableData(value);
console.log('转换后的tableData:', tableData);
console.log('转换后的tableData key列表:', tableData.map(item => item.key));
// 保留现有项的key确保稳定性
if (dataSource && dataSource.length > 0) {
console.log('现有dataSource:', dataSource);
console.log('现有dataSource key列表:', dataSource.map(item => item.key));
// 检查现有dataSource中是否有重复的key
const existingKeyMap = new Map<string, boolean>();
const duplicateKeys = dataSource.filter(item => {
if (existingKeyMap.has(item.key)) {
return true;
}
existingKeyMap.set(item.key, true);
return false;
}).map(item => item.key);
if (duplicateKeys.length > 0) {
console.error('现有dataSource中发现重复的key:', duplicateKeys);
}
const updatedTableData = tableData.map((newItem, index) => {
const updatedTableData = tableData.map((newItem) => {
// 尝试查找对应的现有项通过stId和ndId匹配
const existingItem = dataSource.find(existing =>
(existing.stId === newItem.stId && existing.ndId === newItem.ndId) ||
@ -227,62 +210,17 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
// 如果找到现有项保留其key
if (existingItem) {
console.log(`保留现有项的key: ${existingItem.key}`);
return { ...newItem, key: existingItem.key };
}
// 生成唯一的key
const uniqueKey = `init-${generateUUID(32)}-${index}`;
console.log(`为新项生成key: ${uniqueKey}`);
return { ...newItem, key: uniqueKey };
return newItem;
});
console.log('更新后的tableData:', updatedTableData);
console.log('更新后的tableData key列表:', updatedTableData.map(item => item.key));
// 再次检查是否有重复的key
const finalKeyMap = new Map<string, boolean>();
const finalData = updatedTableData.map((item, index) => {
if (finalKeyMap.has(item.key)) {
// 如果仍然有重复的key强制生成新的key
console.warn(`useEffect中仍然发现重复的key: ${item.key},强制重新生成`);
const forceNewKey = `force-${generateUUID(32)}-${index}-${Date.now()}`;
return {
...item,
key: forceNewKey
};
} else {
finalKeyMap.set(item.key, true);
return item;
}
});
console.log('最终的tableData:', finalData);
console.log('最终的tableData key列表:', finalData.map(item => item.key));
setDataSource(finalData);
// 确保所有key都是唯一的
setDataSource(ensureUniqueKeys(updatedTableData));
} else {
// 确保初始数据的每一项都有唯一的key
const keyMap = new Map<string, boolean>();
const dataWithUniqueKeys = tableData.map((item, index) => {
const key = item.key || `init-${generateUUID(32)}-${index}`;
if (keyMap.has(key)) {
// 如果key重复生成新的key
const newKey = `unique-${generateUUID(32)}-${index}`;
console.log(`初始化时发现重复的key: ${key}生成新key: ${newKey}`);
keyMap.set(newKey, true);
return { ...item, key: newKey };
} else {
keyMap.set(key, true);
return { ...item, key };
}
});
console.log('初始化的dataWithUniqueKeys:', dataWithUniqueKeys);
console.log('初始化的key列表:', dataWithUniqueKeys.map(item => item.key));
setDataSource(dataWithUniqueKeys);
setDataSource(ensureUniqueKeys(tableData));
}
}
} else if (value && value.length === 0 && dataSource.length > 0) {
@ -293,62 +231,8 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
// 更新数据源
const updateDataSource = (newData: TableRowItem[]) => {
console.log('updateDataSource接收到的数据:', newData);
console.log('updateDataSource接收到的key列表:', newData.map(item => item.key));
// 检查是否有重复的key
const keyMap = new Map<string, number>();
newData.forEach(item => {
if (keyMap.has(item.key)) {
keyMap.set(item.key, keyMap.get(item.key)! + 1);
} else {
keyMap.set(item.key, 1);
}
});
// 打印重复的key
const duplicateKeys = Array.from(keyMap.entries())
.filter(([_, count]) => count > 1)
.map(([key]) => key);
if (duplicateKeys.length > 0) {
console.error('发现重复的key:', duplicateKeys);
console.error('重复key的详细信息:', newData.filter(item => duplicateKeys.includes(item.key)));
}
// 确保每行都有唯一稳定的key
const dataWithStableKeys = newData.map((item, index) => {
// 如果key不存在、包含undefined或者是重复的key使用工具函数生成新key
if (!item.key || item.key.includes('undefined') || duplicateKeys.includes(item.key)) {
console.log(`为项 ${index} 重新生成key原key: ${item.key}`);
const newKey = `fixed-${generateUUID(32)}-${index}`;
return {
...item,
key: newKey
};
}
return item;
});
// 再次检查是否有重复的key
const finalKeyMap = new Map<string, boolean>();
const finalData = dataWithStableKeys.map((item, index) => {
if (finalKeyMap.has(item.key)) {
// 如果仍然有重复的key强制生成新的key
console.warn(`仍然发现重复的key: ${item.key},强制重新生成`);
const forceNewKey = `force-${generateUUID(32)}-${index}-${Date.now()}`;
return {
...item,
key: forceNewKey
};
} else {
finalKeyMap.set(item.key, true);
return item;
}
});
console.log('最终的数据源:', finalData);
console.log('最终的key列表:', finalData.map(item => item.key));
const finalData = ensureUniqueKeys(newData);
setDataSource(finalData);
if (onChange) {
@ -413,10 +297,8 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
// 添加一级指标
const addLevel1Indicator = (currentRecord?: TableRowItem) => {
// 使用改进后的工具函数生成唯一key,不再需要额外的时间戳和随机数
// 使用改进后的工具函数生成唯一key
const newKey = `level1-${generateUUID(32)}`;
console.log('添加一级指标生成的key:', newKey);
console.log('当前数据源:', dataSource);
const newItem: TableRowItem = {
key: newKey,
@ -431,7 +313,6 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
orderBy: dataSource.length + 1, // 确保正确的排序
ndOrderBy: 1 // 设置二级指标初始排序
};
console.log('新建的一级指标项:', newItem);
// 制作数据源的副本,避免直接修改状态
const newData = [...dataSource];
@ -443,11 +324,9 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
const sameGroup = newData.filter((item) => item.baseIndicator === currentRecord.baseIndicator);
const lastOfGroup = sameGroup[sameGroup.length - 1];
insertIndex = newData.findIndex((item) => item.key === lastOfGroup.key);
console.log('插入位置(相同baseIndicator):', insertIndex);
} else if (currentRecord && currentRecord.key) {
// 如果是新增的空白行,直接在其后插入
insertIndex = newData.findIndex((item) => item.key === currentRecord.key);
console.log('插入位置(空白行后):', insertIndex);
}
// 如果找到了位置,在该位置后插入,否则添加到末尾
@ -456,8 +335,6 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
} else {
newData.push(newItem);
}
console.log('插入后的数据源:', newData);
console.log('插入后的数据源中的key列表:', newData.map(item => item.key));
updateDataSource(newData);
};
@ -827,31 +704,6 @@ const EvaluateTemplateTable: React.FC<EvaluateTemplateTableProps> = ({
return (
<div className="evaluate-template-table">
{console.log('渲染Table前的dataSource:', dataSource)}
{console.log('渲染Table前的dataSource中的key列表:', dataSource.map(item => item.key))}
{(() => {
// 检查是否有重复的key
const keyMap = new Map<string, number>();
dataSource.forEach(item => {
if (keyMap.has(item.key)) {
keyMap.set(item.key, keyMap.get(item.key)! + 1);
} else {
keyMap.set(item.key, 1);
}
});
// 打印重复的key
const duplicateKeys = Array.from(keyMap.entries())
.filter(([_, count]) => count > 1)
.map(([key]) => key);
if (duplicateKeys.length > 0) {
console.error('渲染Table前发现重复的key:', duplicateKeys);
console.error('重复key的详细信息:', dataSource.filter(item => duplicateKeys.includes(item.key)));
}
return null;
})()}
<Table
columns={columns}
dataSource={dataSource}