This commit is contained in:
Rao 2025-03-25 10:47:18 +08:00
commit fe0bc8d8d7
6 changed files with 694 additions and 6 deletions

View File

@ -1,3 +1,181 @@
import { Table, Select, Form, Button, Space, InputNumber, Modal } from 'antd';
import { useState } from 'react';
// 模拟接口调用函数
const addAgeRangeApi = async (start: number, end: number | null) => {
// 这里替换为实际的接口调用
console.log(`调用接口添加年龄范围: start=${start}, end=${end}`);
};
const addScoreStandardApi = async (score: number, standards: (number | null)[]) => {
// 这里替换为实际的接口调用
console.log(`调用接口添加分数标准: score=${score}, standards=${standards}`);
};
export default function AssessmentStandardPage() { export default function AssessmentStandardPage() {
return <div>AssessmentStandardPage</div>; const [form] = Form.useForm();
const [ageRanges, setAgeRanges] = useState<{ start: number; end: number; label: string; }[]>([
{ start: 18, end: 24, label: '18-24岁' },
{ start: 25, end: 34, label: '25-34岁' },
{ start: 35, end: 44, label: '35-44岁' },
{ start: 45, end: null, label: '45岁以上' },
]);
const [isAgeModalVisible, setIsAgeModalVisible] = useState(false);
const [isScoreModalVisible, setIsScoreModalVisible] = useState(false);
const columns = [
{
title: '分数',
dataIndex: 'score',
key: 'score',
width: 100,
},
...ageRanges.map((range, index) => ({
title: range.label,
dataIndex: `standard_${index}`,
key: `standard_${index}`,
render: (_: any, record: any) => (
<InputNumber
style={{ width: '100%' }}
value={record[`standard_${index}`]}
onChange={(value) => handleStandardChange(record.score, index, value)}
/>
),
})),
];
const handleStandardChange = (score: number, ageIndex: number, value: number | null) => {
// 处理标准值变化
};
const showAgeModal = () => {
setIsAgeModalVisible(true);
};
const handleAgeOk = async (values: any) => {
const { start, end } = values;
await addAgeRangeApi(start, end);
const newRange = {
start,
end,
label: end ? `${start}-${end}` : `${start}岁以上`,
};
setAgeRanges([...ageRanges, newRange]);
setIsAgeModalVisible(false);
};
const handleAgeCancel = () => {
setIsAgeModalVisible(false);
};
const showScoreModal = () => {
setIsScoreModalVisible(true);
};
const handleScoreOk = async (values: any) => {
const { score, standards } = values;
await addScoreStandardApi(score, standards);
// 这里可以更新表格的数据源
setIsScoreModalVisible(false);
};
const handleScoreCancel = () => {
setIsScoreModalVisible(false);
};
return (
<div className="p-6">
<h1 className="text-2xl font-bold mb-6"></h1>
<Button onClick={showAgeModal} className="mb-2"></Button>
<Button onClick={showScoreModal} className="mb-2 ml-2"></Button>
<Form form={form} layout="vertical">
<Space size="large" className="mb-6">
<Form.Item label="项目" name="projectId">
<Select
style={{ width: 200 }}
placeholder="选择考核项目"
options={[
{ value: '1', label: '引体向上' },
{ value: '2', label: '3000米跑' },
// 更多项目...
]}
/>
</Form.Item>
<Form.Item label="性别" name="gender">
<Select
style={{ width: 120 }}
placeholder="选择性别"
options={[
{ value: true, label: '男' },
{ value: false, label: '女' },
]}
/>
</Form.Item>
<Form.Item label="人员类型" name="personType">
<Select
style={{ width: 160 }}
placeholder="选择人员类型"
options={[
{ value: 'OFFICER', label: '警员' },
{ value: 'STAFF', label: '职工' },
]}
/>
</Form.Item>
</Space>
<Table
columns={columns}
dataSource={[
{ score: 100, standard_0: 20, standard_1: 18, standard_2: 15, standard_3: 12 },
{ score: 90, standard_0: 18, standard_1: 16, standard_2: 13, standard_3: 10 },
{ score: 80, standard_0: 16, standard_1: 14, standard_2: 11, standard_3: 8 },
// 更多分数标准...
]}
bordered
pagination={false}
scroll={{ x: 'max-content' }}
/>
<div className="mt-6">
<Button type="primary"></Button>
</div>
</Form>
<Modal
title="添加年龄范围"
visible={isAgeModalVisible}
onOk={form.submit}
onCancel={handleAgeCancel}
>
<Form form={form} onFinish={handleAgeOk}>
<Form.Item name="start" label="起始年龄" rules={[{ required: true }]}>
<InputNumber min={1} />
</Form.Item>
<Form.Item name="end" label="结束年龄">
<InputNumber min={1} />
</Form.Item>
</Form>
</Modal>
<Modal
title="添加分数标准"
visible={isScoreModalVisible}
onOk={form.submit}
onCancel={handleScoreCancel}
>
<Form form={form} onFinish={handleScoreOk}>
<Form.Item name="score" label="分数" rules={[{ required: true }]}>
<InputNumber min={0} />
</Form.Item>
{ageRanges.map((range, index) => (
<Form.Item key={index} name={`standards[${index}]`} label={range.label}>
<InputNumber min={0} />
</Form.Item>
))}
</Form>
</Modal>
</div>
);
} }

View File

@ -0,0 +1,64 @@
import React, { useContext, useEffect, useState } from "react";
import { Form,Input } from "antd";
// 创建可编辑单元格组件
export const EditableContext = React.createContext(null);
export const EditableRow = ({ index, ...props }) => {
const [form] = Form.useForm();
return (
<Form form={form} component={false}>
<EditableContext.Provider value={form}>
<tr {...props} />
</EditableContext.Provider>
</Form>
);
};
export const EditableCell = ({
title,
editable,
children,
dataIndex,
record,
handleSave,
...restProps
}) => {
const form = useContext(EditableContext);
useEffect(() => {
if (editable) {
form.setFieldsValue({ [dataIndex]: record[dataIndex] });
}
}, [form, dataIndex, record, editable]);
const save = async () => {
try {
const values = await form.validateFields();
handleSave({ ...record, ...values });
} catch (errInfo) {
console.log('保存失败:', errInfo);
}
};
let childNode = children;
if (editable) {
childNode = (
<Form.Item
style={{ margin: 0 }}
name={dataIndex}
rules={[
{
required: true,
message: `${title}不能为空!`,
},
]}
>
<Input onPressEnter={save} onBlur={save} />
</Form.Item>
);
}
return <td {...restProps}>{childNode}</td>;
};

View File

@ -0,0 +1,448 @@
import { Button, Select, Table, Modal, Form, Input, InputNumber, Upload, message } from "antd";
import { MagnifyingGlassIcon, ArrowUpTrayIcon, ArrowDownTrayIcon } from "@heroicons/react/24/outline";
import { useEffect, useState, useCallback, useContext } from "react";
import toast from "react-hot-toast";
import React from "react";
import _ from "lodash";
import { useMainContext } from "../layout/MainProvider";
import { EditableRow, EditableContext, EditableCell } from '../sport/context/EditableContext';
import * as XLSX from 'xlsx';
import { UploadOutlined, DownloadOutlined } from '@ant-design/icons';
export default function SportPage() {
const { form, setVisible, searchValue, setSearchValue } = useMainContext();
const { editingRecord, setEditingRecord } = useMainContext();
// 模拟数据实际使用时应替换为API调用
const [isLoading, setIsLoading] = useState(false);
const [sportsData, setSportsData] = useState([
{
id: 1,
name: "张三",
gender: "男",
age: 25,
unit: "信息部",
threeKm: "85",
pullUp: 72,
shuttle: "65",
sitUp: 90,
bodyType: "标准",
totalScore: 85
},
{
id: 2,
name: "李四",
gender: "女",
age: 22,
unit: "市场部",
threeKm: "79",
pullUp: 58,
shuttle: "81",
sitUp: 63,
bodyType: "偏瘦",
totalScore: 78
},
{
id: 3,
name: "王五",
gender: "男",
age: 28,
unit: "技术部",
threeKm: "92",
pullUp: 85,
shuttle: "77",
sitUp: 88,
bodyType: "标准",
totalScore: 90
},
{
id: 4,
name: "赵六",
gender: "女",
age: 24,
unit: "人力资源部",
threeKm: "75",
pullUp: 56,
shuttle: "71",
sitUp: 67,
bodyType: "偏瘦",
totalScore: 75
},
{
id: 5,
name: "钱七",
gender: "男",
age: 30,
unit: "财务部",
threeKm: "68",
pullUp: 77,
shuttle: "59",
sitUp: 82,
bodyType: "偏胖",
totalScore: 82
},
{
id: 6,
name: "孙八",
gender: "男",
age: 26,
unit: "销售部",
threeKm: "93",
pullUp: 88,
shuttle: "84",
sitUp: 95,
bodyType: "标准",
totalScore: 92
},
{
id: 7,
name: "周九",
gender: "女",
age: 23,
unit: "客服部",
threeKm: "73",
pullUp: 60,
shuttle: "65",
sitUp: 75,
bodyType: "标准",
totalScore: 79
},
{
id: 8,
name: "吴十",
gender: "男",
age: 32,
unit: "研发部",
threeKm: "82",
pullUp: 70,
shuttle: "68",
sitUp: 79,
bodyType: "偏胖",
totalScore: 80
},
{
id: 9,
name: "郑十一",
gender: "女",
age: 27,
unit: "市场营销部",
threeKm: "62",
pullUp: 53,
shuttle: "69",
sitUp: 71,
bodyType: "偏瘦",
totalScore: 76
},
{
id: 10,
name: "刘十二",
gender: "男",
age: 29,
unit: "产品部",
threeKm: "87",
pullUp: 82,
shuttle: "78",
sitUp: 86,
bodyType: "标准",
totalScore: 88
}
]);
// 新增搜索功能
const filteredData = sportsData.filter(item =>
item.name.toLowerCase().includes(searchValue.toLowerCase()) ||
item.unit.toLowerCase().includes(searchValue.toLowerCase())
);
const handleNew = () => {
form.resetFields();
setEditingRecord(null);
setVisible(true);
};
// 计算总成绩的函数
const calculateTotalScore = (record) => {
// 确保所有值都转为数字
const threeKmScore = parseInt(record.threeKm, 10) || 0;
const pullUpScore = parseInt(record.pullUp, 10) || 0;
const shuttleScore = parseInt(record.shuttle, 10) || 0;
const sitUpScore = parseInt(record.sitUp, 10) || 0;
// 计算总分
return threeKmScore + pullUpScore + shuttleScore + sitUpScore;
};
// 初始化时计算所有记录的总成绩
useEffect(() => {
const updatedData = sportsData.map(record => ({
...record,
totalScore: calculateTotalScore(record)
}));
setSportsData(updatedData);
}, []);
const handleSave = (row) => {
const newData = [...sportsData];
const index = newData.findIndex(item => row.id === item.id);
const item = newData[index];
// 创建更新后的记录
const updatedRecord = { ...item, ...row };
// 重新计算总成绩
updatedRecord.totalScore = calculateTotalScore(updatedRecord);
// 更新数据
newData.splice(index, 1, updatedRecord);
setSportsData(newData);
toast.success("保存成功");
};
const columns = [
{
title: "姓名",
dataIndex: "name",
key: "name",
},
{
title: "性别",
dataIndex: "gender",
key: "gender",
},
{
title: "年龄",
dataIndex: "age",
key: "age",
},
{
title: "单位",
dataIndex: "unit",
key: "unit",
},
{
title: "三公里",
dataIndex: "threeKm",
key: "threeKm",
editable: true,
},
{
title: "单杠",
dataIndex: "pullUp",
key: "pullUp",
editable: true,
},
{
title: "30x2折返跑",
dataIndex: "shuttle",
key: "shuttle",
editable: true,
},
{
title: "仰卧卷腹",
dataIndex: "sitUp",
key: "sitUp",
editable: true,
},
{
title: "BMI",
dataIndex: "bodyType",
key: "bodyType",
editable: true,
},
{
title: "总成绩",
dataIndex: "totalScore",
key: "totalScore",
editable: true,
},
{
title: "操作",
key: "action",
render: (_, record) => (
<div className="flex space-x-2">
<Button
type="primary"
key={record.id}
onClick={() => handleEdit(record)}
>
</Button>
<Button
danger
onClick={() => handleDelete(record.id)}
>
</Button>
</div>
),
}
];
const mergedColumns = columns.map(col => {
if (!col.editable) {
return col;
}
return {
...col,
onCell: record => ({
record,
editable: col.editable,
dataIndex: col.dataIndex,
title: col.title,
handleSave,
}),
};
});
useEffect(() => {
if (editingRecord) {
form.setFieldsValue(editingRecord);
}
}, [editingRecord, form]);
const handleEdit = (record) => {
setEditingRecord(record);
form.setFieldsValue(record);
setVisible(true);
};
const handleDelete = (id) => {
Modal.confirm({
title: '确认删除',
content: '确定要删除该记录吗?',
okText: '确定',
cancelText: '取消',
onOk: async () => {
try {
// 模拟删除操作
setSportsData(sportsData.filter(item => item.id !== id));
toast.success("删除成功");
} catch (error) {
console.error('删除记录时出错:', error);
toast.error("删除失败");
}
}
});
};
const components = {
body: {
row: EditableRow,
cell: EditableCell,
},
};
// 导出成绩为Excel
const handleExport = () => {
// 创建工作簿
const wb = XLSX.utils.book_new();
// 准备导出数据移除id字段
const exportData = sportsData.map(({ id, ...rest }) => rest);
// 转换为工作表
const ws = XLSX.utils.json_to_sheet(exportData);
// 将工作表添加到工作簿
XLSX.utils.book_append_sheet(wb, ws, "成绩数据");
// 生成Excel文件并下载
XLSX.writeFile(wb, "体育成绩表.xlsx");
toast.success("成绩导出成功");
};
// 导入成绩
const handleImport = (file) => {
const reader = new FileReader();
reader.onload = (e) => {
try {
const data = new Uint8Array(e.target.result);
const workbook = XLSX.read(data, { type: 'array' });
// 获取第一个工作表
const worksheet = workbook.Sheets[workbook.SheetNames[0]];
// 转换为JSON
const jsonData = XLSX.utils.sheet_to_json(worksheet);
// 添加id字段
const importedData = jsonData.map((item, index) => ({
id: sportsData.length + index + 1,
...item,
// 确保totalScore是计算所有项目成绩的和
totalScore: calculateTotalScore(item)
}));
// 更新数据
setSportsData([...sportsData, ...importedData]);
toast.success(`成功导入${importedData.length}条记录`);
} catch (error) {
console.error('导入失败:', error);
toast.error("导入失败,请检查文件格式");
}
};
reader.readAsArrayBuffer(file);
// 防止自动上传
return false;
};
return (
<div className="p-2 min-h-screen bg-gradient-to-br">
<Form>
<div className="p-4 h-full flex flex-col">
<div className="max-w-full mx-auto flex-1 flex flex-col">
<div className="flex justify-between mb-4 space-x-4 items-center">
<div className="text-2xl"></div>
<div className="relative w-1/3">
<Input
placeholder="输入姓名搜索"
onChange={(e) => setSearchValue(e.target.value)}
className="pl-10 w-full border"
/>
<MagnifyingGlassIcon className="absolute left-3 top-1/2 transform -translate-y-1/2 h-5 w-5 " />
</div>
<div className="flex space-x-2">
<Upload
beforeUpload={handleImport}
showUploadList={false}
accept=".xlsx,.xls"
>
<Button icon={<UploadOutlined />}></Button>
</Upload>
<Button
icon={<DownloadOutlined />}
onClick={handleExport}
>
</Button>
<Button
type="primary"
onClick={handleNew}
className="font-bold py-2 px-4 rounded"
>
</Button>
</div>
</div>
{isLoading ? (
<div>...</div>
) : (
<Table
components={components}
rowClassName={() => 'editable-row'}
columns={mergedColumns}
dataSource={filteredData}
tableLayout="fixed"
rowKey="id"
pagination={{
position: ["bottomCenter"],
className: "flex justify-center mt-4",
pageSize: 10,
}}
/>
)}
</div>
</div>
</Form>
</div>
);
}

View File

@ -5,7 +5,6 @@ import _ from "lodash";
import { useMainContext } from "../layout/MainProvider"; import { useMainContext } from "../layout/MainProvider";
import StaffTable from "./stafftable/page"; import StaffTable from "./stafftable/page";
import StaffModal from "./staffmodal/page"; import StaffModal from "./staffmodal/page";
export default function StaffMessage() { export default function StaffMessage() {
const {form, formValue, setFormValue, setVisible, setSearchValue, editingRecord} = useMainContext(); const {form, formValue, setFormValue, setVisible, setSearchValue, editingRecord} = useMainContext();
useEffect(()=>{ useEffect(()=>{
@ -24,14 +23,12 @@ export default function StaffMessage() {
console.log(editingRecord); console.log(editingRecord);
setVisible(true); setVisible(true);
}; };
const handleSearch = useCallback( const handleSearch = useCallback(
_.debounce((value: string) => { _.debounce((value: string) => {
setSearchValue(value); setSearchValue(value);
}, 500), }, 500),
[] []
); );
return ( return (
<div className="p-2 min-h-screen bg-gradient-to-br"> <div className="p-2 min-h-screen bg-gradient-to-br">
<Form> <Form>

View File

@ -15,6 +15,7 @@ import Dashboard from "../app/main/home/page";
import WeekPlanPage from "../app/main/plan/weekplan/page"; import WeekPlanPage from "../app/main/plan/weekplan/page";
import AdminLayout from "../components/layout/admin/AdminLayout"; import AdminLayout from "../components/layout/admin/AdminLayout";
import { adminRoute } from "./admin-route"; import { adminRoute } from "./admin-route";
import SportPage from "../app/main/sport/page";
interface CustomIndexRouteObject extends IndexRouteObject { interface CustomIndexRouteObject extends IndexRouteObject {
name?: string; name?: string;
breadcrumb?: string; breadcrumb?: string;
@ -87,7 +88,7 @@ export const routes: CustomRouteObject[] = [
}, },
{ {
path:"sportsassessment", path:"sportsassessment",
element:<DailyPage></DailyPage> element:<SportPage></SportPage>
} }
] ]
}, },

View File

@ -100,7 +100,7 @@ server {
# 仅供内部使用 # 仅供内部使用
internal; internal;
# 代理到认证服务 # 代理到认证服务
proxy_pass http://192.168.252.77:3000/auth/file; proxy_pass http://192.168.252.77:3001/auth/file;
# 请求优化:不传递请求体 # 请求优化:不传递请求体
proxy_pass_request_body off; proxy_pass_request_body off;