505 lines
16 KiB
TypeScript
505 lines
16 KiB
TypeScript
// src/renderer/pages/Marketplace.tsx
|
||
import { useEffect, useState } from 'react';
|
||
import {
|
||
Box,
|
||
Typography,
|
||
CircularProgress,
|
||
Button,
|
||
Grid,
|
||
Card,
|
||
CardContent,
|
||
CardMedia,
|
||
Pagination,
|
||
Tabs,
|
||
Tab,
|
||
Alert,
|
||
Snackbar,
|
||
} from '@mui/material';
|
||
import { isPlayerOnline, getPlayerServer } from '../utils/playerOnlineCheck';
|
||
import { buyItem, fetchMarketplace, MarketplaceResponse, Server } from '../api';
|
||
import PlayerInventory from '../components/PlayerInventory';
|
||
|
||
interface TabPanelProps {
|
||
children?: React.ReactNode;
|
||
index: number;
|
||
value: number;
|
||
}
|
||
|
||
function TabPanel(props: TabPanelProps) {
|
||
const { children, value, index, ...other } = props;
|
||
|
||
return (
|
||
<div
|
||
role="tabpanel"
|
||
hidden={value !== index}
|
||
id={`marketplace-tabpanel-${index}`}
|
||
aria-labelledby={`marketplace-tab-${index}`}
|
||
{...other}
|
||
>
|
||
{value === index && <Box sx={{ pt: 3 }}>{children}</Box>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export default function Marketplace() {
|
||
const [loading, setLoading] = useState<boolean>(true);
|
||
const [marketLoading, setMarketLoading] = useState<boolean>(false);
|
||
const [isOnline, setIsOnline] = useState<boolean>(false);
|
||
const [username, setUsername] = useState<string>('');
|
||
const [playerServer, setPlayerServer] = useState<Server | null>(null);
|
||
const [marketItems, setMarketItems] = useState<MarketplaceResponse | null>(
|
||
null,
|
||
);
|
||
const [page, setPage] = useState<number>(1);
|
||
const [totalPages, setTotalPages] = useState<number>(1);
|
||
const [tabValue, setTabValue] = useState<number>(0);
|
||
const [notification, setNotification] = useState<{
|
||
open: boolean;
|
||
message: string;
|
||
type: 'success' | 'error';
|
||
}>({
|
||
open: false,
|
||
message: '',
|
||
type: 'success',
|
||
});
|
||
|
||
const translateServer = (server: Server) => {
|
||
switch (server.name) {
|
||
case 'Server minecraft.hub.popa-popa.ru':
|
||
return 'Хаб';
|
||
case 'Server survival.hub.popa-popa.ru':
|
||
return 'Выживание';
|
||
case 'Server minecraft.minigames.popa-popa.ru':
|
||
return 'Миниигры';
|
||
default:
|
||
return server.name;
|
||
}
|
||
};
|
||
|
||
// Функция для проверки онлайн-статуса игрока и определения сервера
|
||
const checkPlayerStatus = async () => {
|
||
if (!username) return;
|
||
|
||
try {
|
||
setLoading(true);
|
||
// Проверяем, онлайн ли игрок и получаем сервер, где он находится
|
||
const { online, server } = await getPlayerServer(username);
|
||
setIsOnline(online);
|
||
setPlayerServer(server);
|
||
|
||
// Если игрок онлайн и на каком-то сервере, загружаем предметы рынка
|
||
if (online && server) {
|
||
await loadMarketItems(server.ip, 1);
|
||
}
|
||
} catch (error) {
|
||
console.error('Ошибка при проверке онлайн-статуса:', error);
|
||
setIsOnline(false);
|
||
setPlayerServer(null);
|
||
} finally {
|
||
setLoading(false);
|
||
}
|
||
};
|
||
|
||
// Функция для загрузки предметов маркетплейса
|
||
const loadMarketItems = async (serverIp: string, pageNumber: number) => {
|
||
try {
|
||
setMarketLoading(true);
|
||
const marketData = await fetchMarketplace(serverIp, pageNumber, 10); // 10 предметов на страницу
|
||
setMarketItems(marketData);
|
||
setPage(marketData.page);
|
||
setTotalPages(marketData.pages);
|
||
} catch (error) {
|
||
console.error('Ошибка при загрузке предметов рынка:', error);
|
||
setMarketItems(null);
|
||
} finally {
|
||
setMarketLoading(false);
|
||
}
|
||
};
|
||
|
||
// Обработчик смены страницы
|
||
const handlePageChange = (
|
||
_event: React.ChangeEvent<unknown>,
|
||
newPage: number,
|
||
) => {
|
||
if (playerServer) {
|
||
loadMarketItems(playerServer.ip, newPage);
|
||
}
|
||
};
|
||
|
||
// Обработчик смены вкладок
|
||
const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
|
||
setTabValue(newValue);
|
||
};
|
||
|
||
// Обновляем функцию handleBuyItem в Marketplace.tsx
|
||
const handleBuyItem = async (itemId: string) => {
|
||
try {
|
||
if (username) {
|
||
const result = await buyItem(username, itemId);
|
||
|
||
setNotification({
|
||
open: true,
|
||
message:
|
||
result.message ||
|
||
'Предмет успешно куплен! Он будет добавлен в ваш инвентарь.',
|
||
type: 'success',
|
||
});
|
||
|
||
// Обновляем список предметов
|
||
if (playerServer) {
|
||
loadMarketItems(playerServer.ip, page);
|
||
}
|
||
}
|
||
} catch (error) {
|
||
console.error('Ошибка при покупке предмета:', error);
|
||
setNotification({
|
||
open: true,
|
||
message:
|
||
error instanceof Error
|
||
? error.message
|
||
: 'Ошибка при покупке предмета',
|
||
type: 'error',
|
||
});
|
||
}
|
||
};
|
||
|
||
// Закрытие уведомления
|
||
const handleCloseNotification = () => {
|
||
setNotification({ ...notification, open: false });
|
||
};
|
||
|
||
// Получаем имя пользователя из localStorage при монтировании компонента
|
||
useEffect(() => {
|
||
const savedConfig = localStorage.getItem('launcher_config');
|
||
if (savedConfig) {
|
||
const config = JSON.parse(savedConfig);
|
||
if (config.username) {
|
||
setUsername(config.username);
|
||
}
|
||
}
|
||
}, []);
|
||
|
||
// Проверяем статус при изменении username
|
||
useEffect(() => {
|
||
if (username) {
|
||
checkPlayerStatus();
|
||
}
|
||
}, [username]);
|
||
|
||
// Показываем loader во время проверки
|
||
if (loading) {
|
||
return (
|
||
<Box
|
||
sx={{
|
||
display: 'flex',
|
||
flexDirection: 'column',
|
||
alignItems: 'center',
|
||
justifyContent: 'center',
|
||
height: '100%',
|
||
gap: 2,
|
||
}}
|
||
>
|
||
<CircularProgress size={60} />
|
||
<Typography variant="h6" color="white">
|
||
Проверяем, находитесь ли вы на сервере...
|
||
</Typography>
|
||
</Box>
|
||
);
|
||
}
|
||
|
||
// Если игрок не онлайн
|
||
if (!isOnline) {
|
||
return (
|
||
<Box
|
||
sx={{
|
||
display: 'flex',
|
||
flexDirection: 'column',
|
||
alignItems: 'center',
|
||
justifyContent: 'center',
|
||
height: '100%',
|
||
gap: 3,
|
||
padding: 4,
|
||
textAlign: 'center',
|
||
}}
|
||
>
|
||
<Typography variant="h4" color="error">
|
||
Доступ к рынку ограничен
|
||
</Typography>
|
||
<Typography variant="h6" color="white">
|
||
Для доступа к рынку вам необходимо находиться на одном из серверов
|
||
игры.
|
||
</Typography>
|
||
<Typography variant="body1" color="white" sx={{ opacity: 0.8 }}>
|
||
Зайдите на любой сервер и обновите страницу.
|
||
</Typography>
|
||
<Button
|
||
variant="contained"
|
||
onClick={checkPlayerStatus}
|
||
sx={{
|
||
mt: '1%',
|
||
borderRadius: '20px',
|
||
p: '10px 25px',
|
||
color: 'white',
|
||
backgroundColor: 'rgb(255, 77, 77)',
|
||
'&:hover': {
|
||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||
},
|
||
fontFamily: 'Benzin-Bold',
|
||
}}
|
||
>
|
||
Проверить снова
|
||
</Button>
|
||
</Box>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<Box sx={{ padding: 3, width: '95%', height: '80%' }}>
|
||
<Box sx={{ display: 'flex', alignItems: 'center', gap: '1vw' }}>
|
||
<Typography variant="h4" color="white" gutterBottom>
|
||
Рынок сервера{' '}
|
||
</Typography>
|
||
<Typography
|
||
style={{
|
||
color: 'white',
|
||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||
padding: '0vw 2vw',
|
||
borderRadius: '5vw',
|
||
fontFamily: 'Benzin-Bold',
|
||
textAlign: 'center',
|
||
fontSize: '2vw',
|
||
}}
|
||
>
|
||
{translateServer(playerServer || { name: '' })}
|
||
</Typography>
|
||
</Box>
|
||
|
||
{/* Вкладки */}
|
||
<Box sx={{ borderBottom: 1, borderColor: 'transparent' }}>
|
||
<Tabs
|
||
value={tabValue}
|
||
onChange={handleTabChange}
|
||
aria-label="marketplace tabs"
|
||
disableRipple={true}
|
||
sx={{
|
||
'& .MuiTabs-indicator': {
|
||
backgroundColor: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
}}
|
||
>
|
||
<Tab
|
||
label="Товары"
|
||
disableRipple={true}
|
||
sx={{
|
||
fontFamily: 'Benzin-Bold',
|
||
color: 'white',
|
||
'&.Mui-selected': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
'&:hover': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
transition: 'all 0.3s ease',
|
||
}}
|
||
/>
|
||
<Tab
|
||
label="Мой инвентарь"
|
||
disableRipple={true}
|
||
sx={{
|
||
fontFamily: 'Benzin-Bold',
|
||
color: 'white',
|
||
'&.Mui-selected': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
'&:hover': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
transition: 'all 0.3s ease',
|
||
}}
|
||
/>
|
||
<Tab
|
||
label="Мои товары"
|
||
disableRipple={true}
|
||
sx={{
|
||
fontFamily: 'Benzin-Bold',
|
||
color: 'white',
|
||
'&.Mui-selected': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
'&:hover': {
|
||
color: 'rgba(255, 77, 77, 1)',
|
||
},
|
||
transition: 'all 0.3s ease',
|
||
}}
|
||
/>
|
||
</Tabs>
|
||
</Box>
|
||
|
||
{/* Содержимое вкладки "Товары" */}
|
||
<TabPanel value={tabValue} index={0}>
|
||
{marketLoading ? (
|
||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: '50vw' }}>
|
||
<CircularProgress />
|
||
</Box>
|
||
) : !marketItems || marketItems.items.length === 0 ? (
|
||
<Box sx={{ mt: 4, textAlign: 'center' }}>
|
||
<Typography variant="h6" color="white" sx={{ mt: '10vw' }}>
|
||
На данный момент на рынке нет предметов.
|
||
</Typography>
|
||
<Button
|
||
variant="contained"
|
||
color="primary"
|
||
onClick={() =>
|
||
playerServer && loadMarketItems(playerServer.ip, 1)
|
||
}
|
||
sx={{
|
||
mt: 2,
|
||
borderRadius: '20px',
|
||
p: '10px 25px',
|
||
color: 'white',
|
||
backgroundColor: 'rgb(255, 77, 77)',
|
||
'&:hover': {
|
||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||
},
|
||
fontFamily: 'Benzin-Bold',
|
||
fontSize: '1vw',
|
||
}}
|
||
>
|
||
Обновить
|
||
</Button>
|
||
</Box>
|
||
) : (
|
||
<>
|
||
<Grid container spacing={2} sx={{ mt: 2 }}>
|
||
{marketItems.items.map((item) => (
|
||
<Grid item xs={12} sm={6} md={4} lg={3} key={item.id}>
|
||
<Card
|
||
sx={{
|
||
bgcolor: 'rgba(255, 255, 255, 0.05)',
|
||
borderRadius: '1vw',
|
||
}}
|
||
>
|
||
<CardMedia
|
||
component="img"
|
||
sx={{
|
||
minWidth: '10vw',
|
||
minHeight: '10vw',
|
||
maxHeight: '10vw',
|
||
objectFit: 'contain',
|
||
bgcolor: 'white',
|
||
p: '1vw',
|
||
imageRendering: 'pixelated',
|
||
}}
|
||
image={`/minecraft/${item.material.toLowerCase()}.png`}
|
||
alt={item.material}
|
||
/>
|
||
<CardContent>
|
||
<Typography variant="h6" color="white">
|
||
{item.display_name ||
|
||
item.material
|
||
.replace(/_/g, ' ')
|
||
.toLowerCase()
|
||
.replace(/\b\w/g, (l) => l.toUpperCase())}
|
||
</Typography>
|
||
<Typography variant="body2" color="white">
|
||
Количество: {item.amount}
|
||
</Typography>
|
||
<Typography variant="body2" color="white">
|
||
Цена: {item.price} монет
|
||
</Typography>
|
||
<Typography
|
||
variant="body2"
|
||
color="white"
|
||
sx={{ opacity: 0.7 }}
|
||
>
|
||
Продавец: {item.seller_name}
|
||
</Typography>
|
||
<Button
|
||
variant="contained"
|
||
color="primary"
|
||
fullWidth
|
||
sx={{
|
||
mt: '1vw',
|
||
borderRadius: '20px',
|
||
p: '0.3vw 0vw',
|
||
color: 'white',
|
||
backgroundColor: 'rgb(255, 77, 77)',
|
||
'&:hover': {
|
||
backgroundColor: 'rgba(255, 77, 77, 0.5)',
|
||
},
|
||
fontFamily: 'Benzin-Bold',
|
||
fontSize: '1vw',
|
||
}}
|
||
onClick={() => handleBuyItem(item.id)}
|
||
>
|
||
Купить
|
||
</Button>
|
||
</CardContent>
|
||
</Card>
|
||
</Grid>
|
||
))}
|
||
</Grid>
|
||
|
||
{totalPages > 1 && (
|
||
<Box sx={{ display: 'flex', justifyContent: 'center', mt: 4 }}>
|
||
<Pagination
|
||
count={totalPages}
|
||
page={page}
|
||
onChange={handlePageChange}
|
||
color="primary"
|
||
/>
|
||
</Box>
|
||
)}
|
||
</>
|
||
)}
|
||
</TabPanel>
|
||
|
||
{/* Содержимое вкладки "Мой инвентарь" */}
|
||
<TabPanel value={tabValue} index={1}>
|
||
{playerServer && username ? (
|
||
<PlayerInventory
|
||
username={username}
|
||
serverIp={playerServer.ip}
|
||
onSellSuccess={() => {
|
||
// После успешной продажи, обновляем список товаров
|
||
if (playerServer) {
|
||
loadMarketItems(playerServer.ip, 1);
|
||
}
|
||
|
||
// Показываем уведомление
|
||
setNotification({
|
||
open: true,
|
||
message: 'Предмет успешно выставлен на продажу!',
|
||
type: 'success',
|
||
});
|
||
}}
|
||
/>
|
||
) : (
|
||
<Typography
|
||
variant="body1"
|
||
color="white"
|
||
sx={{ textAlign: 'center', my: 4 }}
|
||
>
|
||
Не удалось загрузить инвентарь.
|
||
</Typography>
|
||
)}
|
||
</TabPanel>
|
||
|
||
{/* Уведомления */}
|
||
<Snackbar
|
||
open={notification.open}
|
||
autoHideDuration={6000}
|
||
onClose={handleCloseNotification}
|
||
>
|
||
<Alert
|
||
onClose={handleCloseNotification}
|
||
severity={notification.type}
|
||
sx={{ width: '100%' }}
|
||
>
|
||
{notification.message}
|
||
</Alert>
|
||
</Snackbar>
|
||
</Box>
|
||
);
|
||
}
|