import { DataUsage, OrderDetail, OrderHistory, } from "../../services/product/type"; import { productApi } from "../../apis/productApi"; import { startLoading, stopLoading } from "../../features/loading/loadingSlice"; import { useAppDispatch } from "../../hooks/useRedux"; import { useMutation } from "@tanstack/react-query"; import React, { useState, useEffect } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import { openQRModal } from "../../features/popup/popupSlice"; import { convertOrderStatusToColor, convertOrderStatusToText, formatCurrency, formatNumber, } from "../../logic/loigicUtils"; import { useTranslation } from "react-i18next"; import { format } from "path"; const OrderDetailView = () => { const location = useLocation(); const dispatch = useAppDispatch(); const navigate = useNavigate(); const { t } = useTranslation(); const [activeTab, setActiveTab] = useState<"detail" | "manage">("detail"); const [orderDetails, setOrderDetails] = useState([]); const [dataUsage, setDataUsage] = useState([]); const state = location.state as { id: number; orderHistory: OrderHistory; }; useEffect(() => { getOrderDetailMutation.mutate(); }, []); const getOrderDetailMutation = useMutation({ mutationFn: async () => { dispatch(startLoading({})); const res = await productApi.getOrderDetail({ orderId: state.id, }); return res; }, onSuccess: (data) => { dispatch(stopLoading()); console.log("Get order detail response data:", data); if (data && data.errorCode === "0") { console.log("Get order detail successful"); setOrderDetails(data.data ?? []); } else { console.error("Get order detail failed, no token received"); } }, onError: (error: any) => { dispatch(stopLoading()); console.error("Get order detail error:", error.response.data); }, }); const handleTabChange = async (tab: "detail" | "manage") => { if (tab === "manage") { // Load manage data if needed dispatch(startLoading({})); try { const results = await Promise.all( orderDetails.map(async (element) => { const res = await productApi.checkDataUsage({ iccid: element?.iccid, }); if (res && res.errorCode === "0") { return res.data; } return null; }), ); const validResults = results.filter(Boolean); setDataUsage(validResults); console.log("All data usage results:", validResults); } catch (error) { console.error("Check data usage error:", error); } finally { dispatch(stopLoading()); } } setActiveTab(tab); }; // Circular Progress Component const CircularProgress = ({ dataUsage }: { dataUsage: DataUsage }) => { const size = 180; const strokeWidth = 14; const radius = (size - strokeWidth) / 2; const circumference = 2 * Math.PI * radius; // 240 degrees calculation const arcAngle = 240; const arcLength = (arcAngle / 360) * circumference; const percentage = Math.min( Math.max(dataUsage.usageData / dataUsage.totalData, 0), 1, ); const strokeDashoffset = arcLength - percentage * arcLength; // Rotate the SVG to center the 240-degree gap at the bottom // The gap is 120 degrees. We want it balanced. // Default SVG circle starts at 3 o'clock. // To have the 240 arc centered at top, we rotate. const rotation = 150; // (360 - 240) / 2 + 90 return (
{dataUsage.expiredTime ? `${t("expiredAt")}: ${dataUsage.expiredTime}` : ""}
{/* Background Path (240 degrees) */} {/* Progress Path (240 degrees) */} {/* Central Text */}
{dataUsage.totalData === 0 ? ( Unlimited ) : ( {formatNumber(dataUsage.usageData)} {dataUsage.dataUnit} )}
{/* Min Label (Approximate position for 240deg start) */} {dataUsage.totalData === 0 ? null : ( <>
{formatNumber(0)} {dataUsage.dataUnit}
{/* Max Label (Approximate position for 240deg end) */}
{formatNumber(dataUsage.totalData)} {dataUsage.dataUnit}
)}

{dataUsage.status === 0 ? t("notActive") : dataUsage.status === 1 ? t("active") : dataUsage.status === 2 ? t("finished") : dataUsage.status === 3 ? t("expired") : t("unknown")}

{/*

{100 - Math.round((used / total) * 100)}% {t("remaining")}

*/}
); }; return (
{/* Breadcrumb */}
{/* Back Button */} {/* Main Info Card */}
{/* Header */}
{state.orderHistory?.orderCode}
{convertOrderStatusToText(state.orderHistory?.status)}
{/* Tabs */}
{/* Divider with Total */}
{t("totalTotal")}:{" "} {formatCurrency( state.orderHistory?.paymentMoney, state.orderHistory?.curency, )}{" "} {/* ({state.orderHistory?.curency}) */}
{/* Customer Info Grid */}
{t("fullName")}
{state?.orderHistory.customerInfo.surName}{" "} {state?.orderHistory.customerInfo.lastName}
{t("phoneNumber")}
{state?.orderHistory.customerInfo.phoneNumber}
Email
{state?.orderHistory.customerInfo.email}
{t("paymentMethod")}
QR Code
{/* Product Section */}
{orderDetails.length > 0 && (

SIM {orderDetails[0].areaName}

)}
{activeTab === "detail" ? ( // DETAIL TAB CONTENT
{orderDetails.map((pkg, idx) => (

{pkg.packageName}

{/* {pkg.id} */}
{/* TikTok */}

{t("validityPeriod")}: {pkg.dayDuration} {t("days")}

{formatCurrency(pkg.paymentMoney, pkg.curency)} {/* {" "} đ */}
))}
) : ( // MANAGE TAB CONTENT - Grid of Circular Progress
{dataUsage.map((pkg, idx) => (

{orderDetails[idx].packageName}

))}
)}
); }; export default OrderDetailView;