import WSport from "@widgets/WSport";
import {useEffect, useState} from "react";
import {reqGameInfo} from "@features/api";
import LoadingIn from "@components/Loading/LoadingIn";
import {useDispatch, useSelector} from "react-redux";
import {useLocation} from "react-router-dom";
import {ROUTE_PATH} from "@constants/routes";
import {isLogined} from "@features/mainSlice";
import {getDomainSuffix} from "@utils/helpers";

const Sport = ({...props}) => {
    const [isReToken, setIsReToken] = useState(false);
    const [isSrcLoaded, setIsSrcLoaded] = useState(false);
    const dispatch = useDispatch();
    const {pathname} = useLocation();
    const isLogin=useSelector(isLogined);
    const initSport=()=>{
        setIsReToken(false);
        if (isLogin){
            dispatch(reqGameInfo()).then(({payload})=>{
                setIsReToken(true);
            });
        }
        else
        {
            setIsReToken(true);
        }
    }
    const resetSport=()=>{
        initSport();
    }
    // const getDomainSuffix=()=>{
    //     // 获取当前域名
    //     let hostname = window.location.hostname;
    //     // 使用点分隔符分割域名
    //     let parts = hostname.split('.');
    //     // 取得最后一个部分，即后缀
    //     let suffix = parts[parts.length - 1];
    //
    //     return suffix;
    // }
    const checkShowSport=()=>{
        return isReToken&&isSrcLoaded;
    }
    const checkLoadScript=()=>{
        if (window.BTRenderer!=null){
            setIsSrcLoaded(true);
            return;
        }
        let suffix = getDomainSuffix();
        let script=document.createElement('script');
        if (suffix==="pro"){
            script.src="https://ui.invisiblesport.com/bt-renderer.min.js";
        }
        else
        {
            script.src="https://24680.sptpub.com/bt-renderer.min.js";
        }
        script.onload = function() {
            setIsSrcLoaded(true);
        };

        script.onerror = function() {

        };
        document.head.appendChild(script);
    }
    // useEffect(()=>{
    //     if (pathname===ROUTE_PATH.SPORTS||pathname===ROUTE_PATH.RACING){
    //         initSport();
    //     }
    //     else
    //     {
    //         if (!isReToken)setIsReToken(true);
    //     }
    // },[pathname])
    useEffect(()=>{
        checkLoadScript();
        if (pathname===ROUTE_PATH.SPORTS||pathname===ROUTE_PATH.RACING){
            initSport();
        }
        else
        {
            if (!isReToken)setIsReToken(true);
        }
    },[])
    return (
        <>
            {
                // !isReToken?(<LoadingIn></LoadingIn>):(<WSport {...props} resetSport={resetSport}/>)
                !checkShowSport()?(<LoadingIn></LoadingIn>):(<WSport {...props} resetSport={resetSport}/>)
            }
        </>
    )
}
export default Sport;