blob: ee9611a34b69d33b043c40586e20c57f3d9e8cd3 [file] [log] [blame] [edit]
import { ExclamationCircleOutlined, PlusOutlined, DeleteOutlined, UploadOutlined, TrophyOutlined, CheckCircleOutlined, CloseCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import { Button, message, Modal, Switch, Upload, Form, Tag } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import { FooterToolbar, PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import type { FormInstance } from 'antd';
import type { UploadFile } from 'antd/es/upload/interface';
import { getRewardList, removeReward, updateReward, addReward, getTorrentID, submitReward } from './service';
import UpdateForm from './components/UpdateForm';
import { getDictValueEnum } from '@/services/system/dict';
import DictTag from '@/components/DictTag';
import { useAccess } from 'umi';
import { RewardItem, RewardListParams } from './data';
import { BtTorrent } from '../Torrent/data';
import { uploadTorrent } from '../Torrent/service';
import { downloadTorrent } from '../Torrent/service';
/**
* 删除节点
*
* @param selectedRows
*/
const handleRemove = async (selectedRows: RewardItem[]) => {
const hide = message.loading('正在删除');
if (!selectedRows) return true;
try {
await removeReward(selectedRows.map((row) => row.rewardId).join(','));
hide();
message.success('删除成功');
return true;
} catch (error) {
hide();
message.error('删除失败,请重试');
return false;
}
};
const handleUpdate = async (fields: RewardItem) => {
const hide = message.loading('正在更新');
try {
const resp = await updateReward(fields);
hide();
if (resp.code === 200) {
message.success('更新成功');
} else {
message.error(resp.msg);
}
return true;
} catch (error) {
hide();
message.error('配置失败请重试!');
return false;
}
};
const handleAdd = async (fields: RewardItem) => {
const hide = message.loading('正在添加');
try {
const resp = await addReward(fields);
hide();
if (resp.code === 200) {
message.success('添加成功');
} else {
message.error(resp.msg);
}
return true;
} catch (error) {
hide();
message.error('配置失败请重试!');
return false;
}
};
/**
* 下载已提交的种子文件
* @param rewardId 悬赏ID
*/
const handleDownloadSubmitted = async (rewardId: number) => {
const hide = message.loading('正在下载...');
try {
const torrentID = await getTorrentID(rewardId);
// 这里需要调用下载接口,假设接口为 downloadRewardFile
const blob = await downloadTorrent(torrentID.torrentId);
const url = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${blob.name}.torrent`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
message.success('下载成功');
} catch (error: any) {
message.error('下载失败');
}
};
const RewardTableList: React.FC = () => {
const formTableRef = useRef<FormInstance>();
const [uploadForm] = Form.useForm();
const [modalVisible, setModalVisible] = useState<boolean>(false);
const [readOnly, setReadOnly] = useState<boolean>(false);
// 接悬赏相关状态
const [acceptModalVisible, setAcceptModalVisible] = useState<boolean>(false);
const [currentAcceptReward, setCurrentAcceptReward] = useState<RewardItem>();
const [fileList, setFileList] = useState<UploadFile[]>([]);
const actionRef = useRef<ActionType>();
const [currentRow, setCurrentRow] = useState<RewardItem>();
const [selectedRows, setSelectedRows] = useState<RewardItem[]>([]);
const [statusOptions, setStatusOptions] = useState<any>([]);
const access = useAccess();
/** 国际化配置 */
const intl = useIntl();
useEffect(() => {
getDictValueEnum('reward_status').then((data) => {
setStatusOptions(data);
});
}, []);
/**
* 处理接悬赏提交
* @param rewardId 悬赏ID
* @param file 上传的文件
*/
const handleAcceptReward = async (rewardId: number, file: File) => {
const hide = message.loading('正在提交悬赏...');
try {
// 直接传递File对象给uploadTorrent函数
const resp = await submitReward(file);
hide();
if (resp.code === 200) {
message.success('悬赏提交成功!');
return true;
} else {
message.error(resp.msg || '提交失败');
return false;
}
} catch (error) {
hide();
message.error('提交失败,请重试!');
console.error('上传错误:', error);
return false;
}
};
// 修复后的提交处理函数
const handleAcceptSubmit = async () => {
if (!currentAcceptReward) {
message.warning('无效的悬赏信息!');
return;
}
if (fileList.length === 0) {
message.warning('请选择一个种子文件!');
return;
}
// 获取原始File对象
const uploadFile = fileList[0];
let file: File;
if (uploadFile.originFileObj) {
// 如果有originFileObj,使用它(这是真正的File对象)
file = uploadFile.originFileObj;
} else {
message.error('文件信息异常,请重新选择文件!');
return;
}
const success = await handleAcceptReward(currentAcceptReward.rewardId, file);
if (success) {
setAcceptModalVisible(false);
setCurrentAcceptReward(undefined);
setFileList([]);
uploadForm.resetFields();
// 刷新表格数据
if (actionRef.current) {
actionRef.current.reload();
}
}
};
// 文件上传前的检查
const beforeUpload = (file: File) => {
console.log('上传前检查文件:', file.name, file.type, file.size);
// 检查文件类型
const isTorrent = file.name.toLowerCase().endsWith('.torrent');
if (!isTorrent) {
message.error('只能上传.torrent格式的文件!');
return false;
}
// 检查文件大小
const isValidSize = file.size / 1024 / 1024 < 50; // 限制50MB
if (!isValidSize) {
message.error('文件大小不能超过50MB!');
return false;
}
// 检查是否已经有文件了
if (fileList.length >= 1) {
message.warning('只能上传一个文件,当前文件将替换已选择的文件!');
}
return false; // 阻止自动上传,我们手动处理
};
// 处理文件列表变化
const handleFileChange = ({ fileList: newFileList }: { fileList: UploadFile[] }) => {
// 只保留最后一个文件
const latestFileList = newFileList.slice(-1);
setFileList(latestFileList);
if (latestFileList.length > 0) {
console.log('已选择文件:', latestFileList[0].name);
}
};
const columns: ProColumns<RewardItem>[] = [
{
title: '悬赏ID',
dataIndex: 'rewardId',
valueType: 'text',
hideInSearch: true,
},
{
title: '悬赏标题',
dataIndex: 'title',
valueType: 'text',
},
{
title: (
<span>
<TrophyOutlined style={{ marginRight: 4, color: '#faad14' }} />
悬赏积分
</span>
),
dataIndex: 'amount',
valueType: 'digit',
hideInSearch: true,
render: (_, record) => (
<span style={{ color: '#faad14', fontWeight: 'bold' }}>
<TrophyOutlined style={{ marginRight: 4 }} />
{record.amount}
</span>
),
},
{
title: '完成状态',
dataIndex: 'status',
valueType: 'select',
valueEnum: {
'0': { text: '进行中', status: 'Processing' },
'1': { text: '已完成', status: 'Success' },
'2': { text: '已取消', status: 'Error' },
},
render: (_, record) => {
const status = record.status;
let color = 'default';
let icon = <CloseCircleOutlined />;
let text = '进行中';
if (status === '1') {
color = 'success';
icon = <CheckCircleOutlined />;
text = '已完成';
} else if (status === '2') {
color = 'error';
icon = <CloseCircleOutlined />;
text = '已取消';
} else {
color = 'processing';
icon = <TrophyOutlined />;
text = '进行中';
}
return (
<Tag
color={color}
icon={icon}
>
{text}
</Tag>
);
},
},
{
title: '发布时间',
dataIndex: 'createTime',
valueType: 'dateRange',
render: (_, record) => {
return (<span>{record.createTime?.toString()}</span>);
},
search: {
transform: (value) => {
return {
'params[beginTime]': value[0],
'params[endTime]': value[1],
};
},
},
},
{
title: '备注',
dataIndex: 'remark',
valueType: 'text',
hideInSearch: true,
},
{
title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
dataIndex: 'option',
width: '350px',
valueType: 'option',
render: (_, record) => {
// 根据status判断:0进行中 1已完成 2已取消
const status = record.status;
const isCompleted = status === '1'; // 已完成
const isInProgress = status === '0'; // 进行中
const isCancelled = status === '2'; // 已取消
return [
<Button
type="link"
size="small"
key="view"
onClick={() => {
setModalVisible(true);
setCurrentRow(record);
setReadOnly(true);
}}
>
查看
</Button>,
// 只有进行中的悬赏才显示"接悬赏"按钮
isInProgress && (
<Button
type="link"
size="small"
key="accept"
style={{ color: '#52c41a' }}
icon={<TrophyOutlined />}
onClick={() => {
setCurrentAcceptReward(record);
setAcceptModalVisible(true);
setFileList([]);
}}
>
接悬赏
</Button>
),
// 只有已完成的悬赏才显示"下载"按钮
isCompleted && (
<Button
type="link"
size="small"
key="download"
style={{ color: '#1890ff' }}
icon={<DownloadOutlined />}
onClick={() => {
handleDownloadSubmitted(record.rewardId);
}}
>
下载
</Button>
),
<Button
type="link"
size="small"
key="edit"
hidden={!access.hasPerms('reward:reward:edit')}
onClick={() => {
setModalVisible(true);
setCurrentRow(record);
setReadOnly(false);
}}
>
编辑
</Button>,
<Button
type="link"
size="small"
danger
key="batchRemove"
hidden={!access.hasPerms('reward:reward:remove')}
onClick={async () => {
Modal.confirm({
title: '删除',
content: '确定删除该项吗?',
okText: '确认',
cancelText: '取消',
onOk: async () => {
const success = await handleRemove([record]);
if (success) {
if (actionRef.current) {
actionRef.current.reload();
}
}
},
});
}}
>
删除
</Button>,
].filter(Boolean) // 过滤掉 false 值
},
},
];
return (
<PageContainer>
<div style={{ width: '100%', float: 'right' }}>
<ProTable<RewardItem>
headerTitle={intl.formatMessage({
id: 'pages.searchTable.title',
defaultMessage: '信息',
})}
actionRef={actionRef}
formRef={formTableRef}
rowKey="rewardId"
key="rewardList"
search={{
labelWidth: 120,
}}
toolBarRender={() => [
<Button
type="primary"
key="add"
hidden={!access.hasPerms('reward:reward:add')}
onClick={async () => {
setCurrentRow(undefined);
setModalVisible(true);
}}
>
<PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
</Button>,
<Button
type="primary"
key="remove"
danger
hidden={selectedRows?.length === 0 || !access.hasPerms('reward:reward:remove')}
onClick={async () => {
Modal.confirm({
title: '是否确认删除所选数据项?',
icon: <ExclamationCircleOutlined />,
content: '请谨慎操作',
async onOk() {
const success = await handleRemove(selectedRows);
if (success) {
setSelectedRows([]);
actionRef.current?.reloadAndRest?.();
}
},
onCancel() { },
});
}}
>
<DeleteOutlined />
<FormattedMessage id="pages.searchTable.delete" defaultMessage="删除" />
</Button>,
]}
request={(params) =>
getRewardList({ ...params } as RewardListParams).then((res) => {
return {
data: res.rows,
total: res.total,
success: true,
};
})
}
columns={columns}
rowSelection={{
onChange: (_, selectedRows) => {
setSelectedRows(selectedRows);
},
}}
/>
</div>
{selectedRows?.length > 0 && (
<FooterToolbar
extra={
<div>
<FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />
<a style={{ fontWeight: 600 }}>{selectedRows.length}</a>
<FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
</div>
}
>
<Button
key="remove"
danger
hidden={!access.hasPerms('reward:reward:remove')}
onClick={async () => {
Modal.confirm({
title: '删除',
content: '确定删除该项吗?',
okText: '确认',
cancelText: '取消',
onOk: async () => {
const success = await handleRemove(selectedRows);
if (success) {
setSelectedRows([]);
actionRef.current?.reloadAndRest?.();
}
},
});
}}
>
<FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
</Button>
</FooterToolbar>
)}
{/* 原有的编辑/新增模态框 */}
<UpdateForm
readOnly={readOnly}
onSubmit={async (values) => {
let success = false;
if (values.rewardId) {
success = await handleUpdate({ ...values } as RewardItem);
} else {
success = await handleAdd({ ...values } as RewardItem);
}
if (success) {
setModalVisible(false);
setCurrentRow(undefined);
if (actionRef.current) {
actionRef.current.reload();
}
}
}}
onCancel={() => {
setModalVisible(false);
setCurrentRow(undefined);
setReadOnly(false);
}}
open={modalVisible}
values={currentRow || {}}
statusOptions={statusOptions}
/>
{/* 接悬赏模态框 */}
<Modal
title={
<span>
<TrophyOutlined style={{ color: '#faad14', marginRight: 8 }} />
接悬赏 - {currentAcceptReward?.title || ''}
</span>
}
open={acceptModalVisible}
onOk={handleAcceptSubmit}
onCancel={() => {
setAcceptModalVisible(false);
setCurrentAcceptReward(undefined);
setFileList([]);
}}
width={600}
okText="提交悬赏"
cancelText="取消"
>
<div style={{ marginBottom: 16 }}>
<p><strong>悬赏标题:</strong>{currentAcceptReward?.title}</p>
<p>
<strong>悬赏积分:</strong>
<span style={{ color: '#faad14', fontWeight: 'bold' }}>
<TrophyOutlined style={{ marginRight: 4 }} />
{currentAcceptReward?.amount}
</span>
</p>
<p><strong>备注:</strong>{currentAcceptReward?.remark || '无'}</p>
</div>
<div>
<p style={{ marginBottom: 8, fontWeight: 'bold' }}>上传种子文件:</p>
<Upload
fileList={fileList}
onChange={handleFileChange}
beforeUpload={beforeUpload}
onRemove={(file) => {
setFileList([]);
}}
maxCount={1}
accept=".torrent"
>
<Button icon={<UploadOutlined />}>选择种子文件</Button>
</Upload>
<p style={{ marginTop: 8, color: '#666', fontSize: '12px' }}>
只能上传一个种子文件,文件大小不超过50MB
</p>
</div>
</Modal>
</PageContainer>
);
};
export default RewardTableList;