//桌面游戏容器
import Spring from "@components/Spring";
import styles from "./styles.module.scss";
import {LOCAL_GAME_INFO, LOCAL_GAME_URL, LOCAL_SIGN} from "@constants/localkey";
import {localStorageGet, openFullScreen} from "@utils/helpers";
import React, {useEffect, useState} from "react";
import {useDispatch, useSelector} from "react-redux";
import {getGameCardInfo, getGameLike, getRoute, isLogined, updateGameLike} from "@features/mainSlice";
import BreadCrumb from "@layout/BreadCrumb";
import {useThemeProvider} from "@contexts/themeContext";
import {getHallConnState} from "@features/socketSlice";
import Imgix from "@components/Imgix";
import SmallLoading from "@components/SmallLoading";
import SvgIcon from "@components/SvgIcon";
import useGameIFrame from "@hooks/useGameIFrame";
import MTooltip from "@components/MTooltip";
import {updatePageGameLike} from "@features/pageSlice";
import {reqGameCardInfo, reqUpdateFavoInfo} from "@features/api";
import Popup from "@components/Popup";
import LoadingIn from "@components/Loading/LoadingIn";
const i18n=global.i18n;

const WDGame=()=>{
    // const {pathname}=useLocation();
    const {preLocation,gameID} = useThemeProvider();
    const gameid=gameID;
    const gameCardInfo=useSelector(getGameCardInfo(gameid))
    const [gameURL, setGameURL] = useState("");
    const [gameInfo, setGameInfo] = useState({});
    const prePathname=preLocation.pathname==null?"/casino":preLocation.pathname;
    const preRoute=useSelector(getRoute(prePathname));
    const isConnected=useSelector(getHallConnState);
    const {isGameLoad,setIsGameLoad,iFrameRef}=useGameIFrame();
    const [movieMode,setMovieMode]=useState(false);
    const isLike=useSelector(getGameLike(gameID));
    const dispatch = useDispatch();
    const isLogin=useSelector(isLogined);
    const [openShare,setOpenShare]=useState(false);
    const shareData=[
        {type:'fb',icon:'3'},
        {type:'twitter',icon:'8'},
        {type:'tg',icon:'7'},
        {type:'vk',icon:'11'},
        {type:'line',icon:'12'},
        {type:'skype',icon:'13'},
        {type:'ok',icon:'14'},
        {type:'in',icon:'16'},
        {type:'ws',icon:'17'},
    ]
    const onShare=(item)=>{
        let type=item.type;
        let title="";
        if (gameInfo!=null)title=gameInfo.title;
        let text="";
        let link=window.location.href;
        let url="";
        switch(type){
            case 'fb':
                url=`https://www.facebook.com/sharer.php?title=${title}&text=${text}&u=${link}`;
                break
            case 'twitter':
                url=`https://twitter.com/share?title=${title}&text=${text}&url=${link}`;
                break
            case 'tg':
                url=`https://t.me/share?title=${title}&text=${text}&url=${link}`;
                break
            case 'vk':
                url=`http://vk.com/share.php?url=${link}&title=${title}&text=${text}`;
                break
            case 'line':
                url=`https://lineit.line.me/share/ui?url=${link}&title=${title}&text=${text}`;
                break
            case 'skype':
                url=`https://web.skype.com/share?url=${link}&title=${title}&text=${text}`;
                break
            case 'ok':
                url=`https://connect.ok.ru/offer?url=url=${link}&title=${title}`;
                break
            case 'in':
                url=`https://www.linkedin.com/sharing/share-offsite/?url=${link}`;
                break
            case 'ws':
                url=`https://api.whatsapp.com/send?url=${link}&title=${title}&text=${text}`;
                break
        }
        window.open(url);
    }
    const parseURL=()=>{
        let key=LOCAL_GAME_URL+gameid;
        let sign=localStorageGet(LOCAL_SIGN);
        // let url=localStorageGet(key);
        let url=gameCardInfo.link;
        if (gameCardInfo.level>0)url+="&level="+gameCardInfo.level;
        if (url==null)return;
        let _d=global.device;
        let _t=Date.now()+"_"+global.width+"_"+global.height;
        if (url.indexOf("?")===-1)url=url+"?sign="+sign+"&_d="+_d+"&_t="+_t;
        else url=url+"&sign="+sign+"&_d="+_d+"&_t="+_t;
        setGameURL(url);
    }
    const parseInfo=()=>{
        if (gameid==="")return;
        // let local=localStorageGet(LOCAL_GAME_INFO+gameid);
        // if (local!=null&&local!==""){
        //     let info=JSON.parse(local);
        //     if (info!=null){
        //         setGameInfo(info.data);
        //     }
        // }
        setGameInfo(gameCardInfo);
    }
    const getRouteChain=()=>{
        let chain=[];
        if (preRoute!=null)chain.push(preRoute);
        if (gameInfo!=null){
            chain.push({
                title:gameInfo.title,
                path:""
            })
        }
        return chain;
    }
    const onGameFullScreen=()=>{
        const iframe = iFrameRef.current;
        if (iframe) {
            if (iframe.requestFullscreen) {
                iframe.requestFullscreen();
            } else if (iframe.mozRequestFullScreen) { /* Firefox */
                iframe.mozRequestFullScreen();
            } else if (iframe.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
                iframe.webkitRequestFullscreen();
            } else if (iframe.msRequestFullscreen) { /* IE/Edge */
                iframe.msRequestFullscreen();
            }
        }
    }
    const onChangeMovieMode=()=>{
        setMovieMode(!movieMode);
    }
    const handleLike=()=>{
        let info={id:gameID,data:gameInfo,like:(1-isLike)}
        dispatch(updateGameLike(info));
        dispatch(updatePageGameLike(info));
        if(isLogin)dispatch(reqUpdateFavoInfo(info));
    }
    useEffect(()=>{
        if (Number(gameid)>0&&gameCardInfo==null){
            dispatch(reqGameCardInfo(gameid));
        }
        return ()=>{
        }
    },[gameid])
    useEffect(()=>{
        if (!isConnected){
            setIsGameLoad(false);
        }
    },[isConnected])
    useEffect(()=>{
        if (gameCardInfo!=null){
            parseURL();
            parseInfo();
        }
    },gameCardInfo);
    const renderTopNavBar=()=>{
        let chain=getRouteChain();
        let brand=gameInfo.brand?gameInfo.brand:"";
        return (
            <div className={styles.game_top_nav_wrap}>
                <BreadCrumb customChain={chain}></BreadCrumb>
                <div className={styles.brand_con}>
                    {i18n.t("game.brand_by")}
                    <span className={styles.brand}>{brand}</span>
                </div>
            </div>
        )
    }
    const renderGame=()=>{
        let title="game";
        if (gameInfo&&gameInfo.title!=null){
            title=gameInfo.title;
        }
        let play_num=gameInfo.play_num!=null?gameInfo.play_num:0;
        return (
            <div className={`${styles.game_area} ${movieMode?styles.movie_mode:''}`}>
                {/*<div className={`${styles.game_action_wrap} ${styles.game_action_wrap_top}`}></div>*/}
                <div className={styles.game_main}>
                    <div className={styles.game_iframe_wrap}>
                        {
                            isConnected?(
                                <iframe
                                    ref={iFrameRef}
                                    id={"game"}
                                    title={title}
                                    src={gameURL}
                                    allow="fullscreen"
                                    sandbox='allow-scripts allow-same-origin allow-popups allow-top-navigation allow-top-navigation-by-user-activation'
                                >
                                </iframe>
                            ):(<></>)
                        }
                        {renderLoading()}
                    </div>
                </div>
                <div className={`${styles.game_action_wrap} ${styles.game_action_wrap_bottom}`}>
                    <div className={styles.action_item_con}>
                        <button className={`${styles.action_item} ${isLike===1?styles.active_star:''}`} onClick={handleLike}>
                            <SvgIcon className={styles.icon} herf={"icon_Favorites1"}></SvgIcon>
                            {
                                play_num>0?play_num:''
                            }
                        </button>
                        <button className={styles.action_item} onClick={()=>{
                            setOpenShare(true);
                        }}>
                            <SvgIcon className={styles.icon} herf={"icon_Send"}></SvgIcon>
                        </button>
                    </div>
                    <div className={styles.action_item_con}>
                        <MTooltip title={i18n.t('game.tips.movie_mode')} placement="top">
                            <button className={`${styles.action_item} ${movieMode ? styles.active : ''}`}
                                    onClick={onChangeMovieMode}>
                                <SvgIcon className={styles.icon} herf={"icon_Movie"}></SvgIcon>
                            </button>
                        </MTooltip>
                        <MTooltip title={i18n.t('game.tips.full_screen')} placement="top">
                            <button className={`${styles.action_item}`} onClick={onGameFullScreen}>
                                <SvgIcon className={styles.icon} herf={"icon_FullScreen"}></SvgIcon>
                            </button>
                        </MTooltip>
                    </div>
                </div>
            </div>
        )
    }
    const renderLoading = () => {
        if (isGameLoad) return (<></>);
        let imgsrc = gameInfo.img ? gameInfo.img:"";
        return (
            <div className={styles.loading_wrap}>
                {
                    imgsrc!==""?(
                        <Imgix className={styles.loading_bg} src={imgsrc} width={1024} imgixParams={{blur:150}} />
                    ):(<></>)
                }
                <div className={styles.loading}>
                    <SmallLoading />
                </div>
            </div>
        )
    }
    const renderShareBox=()=>{
        return (
            <Popup onClose={()=>{
                setOpenShare(false);
            }} open={openShare}>
                <div className={styles.share_box}>
                    <span className={styles.title}>
                        {i18n.t("game.share_title")}
                    </span>
                    <div className={styles.content}>
                        {
                            shareData.map((item,index)=>{
                                return (
                                    <button key={index} className={styles.share_btn} onClick={()=>{
                                        onShare(item);
                                    }}>
                                        <img src={require("@assets/share/share_"+item.icon+".png")}/>
                                    </button>
                                )
                            })
                        }
                    </div>
                </div>
            </Popup>
        )
    }
    return (
        <>
            {
                gameCardInfo==null?<LoadingIn></LoadingIn>:(
                    <Spring type={"slideUp"}>
                        <div className={`${styles.container} page-max-width-wrap`}>
                            {renderTopNavBar()}
                            {renderGame()}
                            {renderShareBox()}
                        </div>
                    </Spring>
                )
            }
        </>
    )
}
export default WDGame;