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, memo } from "react";
// 定义刷新时间(秒)
const IP_REFRESH_SECONDS = 300;
// 提取InfoItem子组件并使用memo优化
const InfoItem = memo(({ label, value }: { label: string; value: string }) => (
{label}:
{value || "Unknown"}
));
// 获取国旗表情
const getCountryFlag = (countryCode: string) => {
if (!countryCode) return "";
const codePoints = countryCode
.toUpperCase()
.split("")
.map((char) => 127397 + char.charCodeAt(0));
return String.fromCodePoint(...codePoints);
};
// IP信息卡片组件
export const IpInfoCard = () => {
const { t } = useTranslation();
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();
// 倒计时实现优化,减少不必要的重渲染
let timer: number | null = null;
let currentCount = IP_REFRESH_SECONDS;
// 只在必要时更新状态,减少重渲染次数
const startCountdown = () => {
timer = window.setInterval(() => {
currentCount -= 1;
if (currentCount <= 0) {
fetchIpInfo();
currentCount = IP_REFRESH_SECONDS;
}
// 每5秒或倒计时结束时才更新UI
if (currentCount % 5 === 0 || currentCount <= 0) {
setCountdown(currentCount);
}
}, 1000);
};
startCountdown();
return () => {
if (timer) clearInterval(timer);
};
}, [fetchIpInfo]);
const toggleShowIp = useCallback(() => {
setShowIp(prev => !prev);
}, []);
// 渲染加载状态
if (loading) {
return (
}
iconColor="info"
action={
}
>
);
}
// 渲染错误状态
if (error) {
return (
}
iconColor="info"
action={
}
>
{error}
);
}
// 渲染正常数据
return (
}
iconColor="info"
action={
}
>
{/* 左侧:国家和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)}
);
};