import { useTranslation } from "react-i18next"; import { Box, Typography, Button, Skeleton, IconButton, useTheme, } from "@mui/material"; import { LocationOnOutlined, RefreshOutlined, VisibilityOutlined, VisibilityOffOutlined, } from "@mui/icons-material"; import { EnhancedCard } from "./enhanced-card"; import { getIpInfo } from "@/services/api"; import { useState, useEffect, useCallback } from "react"; // 定义刷新时间(秒) const IP_REFRESH_SECONDS = 300; // IP信息卡片组件 export const IpInfoCard = () => { const { t } = useTranslation(); const theme = useTheme(); const [ipInfo, setIpInfo] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [showIp, setShowIp] = useState(false); const [countdown, setCountdown] = useState(IP_REFRESH_SECONDS); // 获取IP信息 const fetchIpInfo = useCallback(async () => { try { setLoading(true); setError(""); const data = await getIpInfo(); setIpInfo(data); setCountdown(IP_REFRESH_SECONDS); } catch (err: any) { setError(err.message || t("Failed to get IP info")); } finally { setLoading(false); } }, [t]); // 组件加载时获取IP信息 useEffect(() => { fetchIpInfo(); }, [fetchIpInfo]); // 倒计时自动刷新 useEffect(() => { const timer = setInterval(() => { setCountdown((prev) => { if (prev <= 1) { fetchIpInfo(); return IP_REFRESH_SECONDS; } return prev - 1; }); }, 1000); return () => clearInterval(timer); }, [fetchIpInfo]); // 刷新按钮点击处理 const handleRefresh = () => { fetchIpInfo(); }; // 切换显示/隐藏IP const toggleShowIp = () => { setShowIp(!showIp); }; // 获取国旗表情 const getCountryFlag = (countryCode: string) => { if (!countryCode) return ""; const codePoints = countryCode .toUpperCase() .split("") .map((char) => 127397 + char.charCodeAt(0)); return String.fromCodePoint(...codePoints); }; // 信息项组件 - 默认不换行,但在需要时可以换行 const InfoItem = ({ label, value }: { label: string; value: string }) => ( {label}: {value || t("Unknown")} ); return ( } iconColor="info" action={ } > {loading ? ( ) : error ? ( {error} ) : ( <> {/* 左侧:国家和IP地址 */} {getCountryFlag(ipInfo?.country_code)} {ipInfo?.country || t("Unknown")} {t("IP")}: {showIp ? ipInfo?.ip : "••••••••••"} {showIp ? ( ) : ( )} {/* 右侧:组织、ISP和位置信息 */} {t("Auto refresh")}: {countdown}s {ipInfo?.country_code}, {ipInfo?.longitude?.toFixed(2)},{" "} {ipInfo?.latitude?.toFixed(2)} )} ); };