collect-system/apps/web/src/app/admin/sharecode/sharecodevalidator.tsx

75 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-04-08 09:29:14 +08:00
import React, { useCallback, useEffect, useState } from 'react';
2025-04-02 16:14:30 +08:00
import { Input, Button, message } from 'antd';
import styles from './ShareCodeValidator.module.css';
2025-04-02 21:59:19 +08:00
import { api } from '@nice/client';
2025-04-08 09:29:14 +08:00
import dayjs from 'dayjs';
2025-04-02 16:14:30 +08:00
interface ShareCodeValidatorProps {
onValidSuccess: (fileId: string, fileName: string) => void;
}
2025-04-08 09:29:14 +08:00
import utc from 'dayjs/plugin/utc';
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(utc);
dayjs.extend(timezone);
2025-04-02 16:14:30 +08:00
export const ShareCodeValidator: React.FC<ShareCodeValidatorProps> = ({
onValidSuccess,
}) => {
const [code, setCode] = useState('');
const [loading, setLoading] = useState(false);
2025-04-08 09:29:14 +08:00
const { data: result, isLoading,refetch } = api.shareCode.getFileByShareCode.useQuery(
2025-04-02 21:59:19 +08:00
{ code: code.trim() },
{
2025-04-08 09:29:14 +08:00
enabled: false
2025-04-02 21:59:19 +08:00
}
)
2025-04-08 09:29:14 +08:00
const validateCode = useCallback(async () => {
2025-04-02 21:59:19 +08:00
2025-04-02 16:14:30 +08:00
if (!code.trim()) {
2025-04-03 13:27:58 +08:00
message.warning('请输入正确的分享码');
2025-04-02 16:14:30 +08:00
return;
}
setLoading(true);
try {
2025-04-08 09:29:14 +08:00
const { data: latestResult } = await refetch();
console.log('验证分享码返回数据:', latestResult);
onValidSuccess(latestResult.url, latestResult.fileName);
2025-04-02 16:14:30 +08:00
} catch (error) {
console.error('验证分享码失败:', error);
message.error('分享码无效或已过期');
} finally {
setLoading(false);
}
2025-04-08 09:29:14 +08:00
}, [refetch, code, onValidSuccess]);
2025-04-02 16:14:30 +08:00
return (
2025-04-08 09:29:14 +08:00
<>
<div className={styles.container}>
<Input
className={styles.input}
value={code}
onChange={(e) => setCode(e.target.value.toUpperCase())}
placeholder="请输入分享码"
maxLength={8}
onPressEnter={validateCode}
/>
<Button
type="primary"
onClick={validateCode}
loading={loading}
disabled={!code.trim()}
>
</Button>
</div>
{
!loading && result && (
<div className='w-full flex justify-between my-2 p-1 antialiased text-secondary-600'>
<span >{`分享码:${result?.code ? result.code : ''}`}</span>
<span >{`文件名:${result?.fileName ? result.fileName : ''}`}</span>
<span >{`过期时间:${result?.expiresAt ? dayjs(result.expiresAt).tz('Asia/Shanghai').toDate().toLocaleString() : ''}`}</span>
<span >{`剩余使用次数:${result?.canUseTimes ? result.canUseTimes : ''}`}</span>
</div>
)
}
</>
2025-04-02 16:14:30 +08:00
);
};