import styles from "@components/GameSmallList/styles.module.scss";
import React, {useRef, useEffect, useState,Fragment} from "react";
import {NavLink} from "react-router-dom";
import symbol from "@assets/symbol-defs.svg";
import {LazyLoadImage} from "react-lazy-load-image-component";
import {useThemeProvider} from "@contexts/themeContext";
import GameItem, {GameImgAspectRatio} from "@components/GameItem";
import SvgIcon from "@components/SvgIcon";
import styled from 'styled-components/macro';
import GameRoom from "@components/GameRoom";
import {useWindowSize} from "react-use";
const i18n=global.i18n;
const StyledRoomCon=styled.div`
    position:absolute;
    left: 0;
    right: 0;
    ${(props) => {
        return `
        top:${props.top}px;
        `
    }}
`
const objInfo={
    timer:null
}
const GameSmallList=({data,user})=>{
    const {isMobile,fontScale} = useThemeProvider();
    const gridListRef=useRef(null);
    const gridListMRef=useRef(null);
    const gridConRef=useRef(null);
    //0 滚动条顶部 1滚动条中间 2滚动条底部
    const [pageState, setPageState] = useState(0);
    const [showPopRoom,setShowPopRoom]=useState(false);
    const [selected,setSelected]=useState(-1);
    const [roomRow,setRoomRow]=useState({});
    const {width} = useWindowSize();
    const roomHeight=5.2;
    const rowGap=0.75;
    const rowTop=roomHeight+rowGap*2;
    // data={
    //     title:"BC Originals",
    //     data:[
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/f76d3f4a-9712-4bd1-9426-f3ab7069b6a2.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:1006,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/ff0b0511-1f48-43d1-8dd3-294bb6437b4b.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/d33b3fad-b6df-450b-bd85-528a17383043.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/5b3a4099-9462-4d3c-a854-ade78aad0d60.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/f76d3f4a-9712-4bd1-9426-f3ab7069b6a2.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/ff0b0511-1f48-43d1-8dd3-294bb6437b4b.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/d33b3fad-b6df-450b-bd85-528a17383043.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //         {
    //             gid:0,//gameid
    //             img:"https://bc.imgix.net/game/image/5b3a4099-9462-4d3c-a854-ade78aad0d60.png?auto=format&dpr=3&w=200",//图片
    //             link:"",//跳转的链接
    //             online:100,//游戏人数
    //             desc:"BC Originals",//描述
    //         },
    //     ],
    //     link:""//view all
    // }
    let list=data.data;
    if (list==null)list=[];
    const gameListRef = useRef(null);
    const [gridInfo,setGridInfo]=useState({});
    const handleScroll=()=>{
        const gridList=gridListRef.current;
        if (gridList!=null){
            const { scrollLeft, clientWidth, scrollWidth } = gridList;
            if (scrollLeft==0)setPageState(0);
            else
            {
                if (scrollWidth-scrollLeft==clientWidth)setPageState(2);
                else setPageState(1);
            }
        }
    }
    const getRoomConTop=()=>{
        const gridList=gridListMRef.current;
        const gridCon=gridConRef.current;
        if (gridList!=null&&gridCon!=null){
            let rectP=gridCon.getBoundingClientRect();
            let rect=gridList.getBoundingClientRect();
            let gridListTop=rect.top-rectP.top;
            let height=0;
            let gap=0;
            if (gridList.children&&gridList.children.length>0){
                let first=gridList.children[0];
                if (first&&first.children.length>0)first=first.children[0];
                let cB=rect.top+first.clientHeight;
                let cH = document.documentElement.clientHeight;
                if (cH-cB>90){
                    height=first.clientHeight;
                    gap=rowGap*16*fontScale;
                }
            }
            let top=gridListTop+height+gap*2;
            return top;
        }
        return 0;
    }
    const handleReset=(e)=>{
        setSelected(-1);
        setRoomRow({});
    }
    const resetTimer=()=>{
        if (objInfo.timer!=null){
            clearTimeout(objInfo.timer);
            objInfo.timer=null;
        }
    }
    const checkSetRoom=(e,item)=>{
        let roomRowItem={
            data:item
        }
        if (roomRow.data!=null){
            setRoomRow({
                hide:true,
                ...roomRowItem
            });
            resetTimer();
            objInfo.timer=setTimeout(()=>{
                setRoomRow(roomRowItem);
            },10)
        }
        else setRoomRow(roomRowItem);
    }
    const handleSelect=(e,data)=>{
        e.stopPropagation();
        if (data.id===selected){
            handleReset();
        }
        else
        {
            setSelected(data.id);
            checkSetRoom(e,data);
        }
    }
    const handlePopSelected=(e,data)=>{
        e.stopPropagation();
        setRoomRow({
            row:-1,
            data:data
        });
        setShowPopRoom(true);
    }
    const handlePopClose=()=>{
        setRoomRow({});
        setShowPopRoom(false);
    }
    const getDesktopCol=()=>{
        if (width>=1264&&width<=1564)return 6;
        else if (width>=963&&width<=1263)return 5;
        else if (width>=622&&width<=962)return 4;
        else if (width<=621)return 3;
        return 7;
    }
    const initGridsInfo=()=>{
        let parent=isMobile()?gridListMRef.current:gridListRef.current;
        // if (parent!=null){
        let totalCol=3;
        if (!isMobile())totalCol=getDesktopCol();
        let gridBaseRatio=GameImgAspectRatio;
        let totalWidth=isMobile()?100*totalCol:160*totalCol;
        if (parent!=null)totalWidth=parent.clientWidth;
        let rowGap =parent!=null?window.getComputedStyle(parent).getPropertyValue('grid-row-gap'):"0px";
        let gap=Number(rowGap.replace("px",""));
        if (gap===0||isNaN(gap))gap=0.75*16*fontScale;
        let gridsData={};
        for (let i=1;i<=6;i++){
            let gridNum=i;
            let gridWidth=(totalWidth-(totalCol-1)*gap)/totalCol;
            let itemWidth=gridWidth*gridNum+(gridNum-1)*gap;
            let width=itemWidth+"px";
            let aspectRatio=gridBaseRatio*(itemWidth/gridWidth);
            gridsData[i]={width,aspectRatio};
        }
        setGridInfo(gridsData);
        // }
    }
    const formatMList = (list)=>{
        let mList = [];
        if (list!=null){
            const itemsPerRow = 3;
            for (let i = 0; i < list.length; i++) {
                let row = Math.floor(i / itemsPerRow);
                let rowList = mList[row];
                if (rowList == null) {
                    rowList = [];
                    mList[row] = rowList;
                }
                rowList.push(list[i]);
            }
        }
        return mList;
    }
    useEffect(() => {
        const gridList=gridListRef.current;
        if (gridList) {
            gridList.addEventListener('scroll', handleScroll);

            return () => {
                gridList.removeEventListener('scroll', handleScroll);
            };
        }
        document.addEventListener("click",handleReset);
        return ()=>{
            document.removeEventListener("click",handleReset);
            resetTimer();
        }
    }, []); // 空数组表示只在组件挂载和卸载时执行
    useEffect(()=>{
        initGridsInfo();
    },[gridListRef,gridListMRef,width])
    const onChagePage=(change=1)=>{
        const gridList=gridListRef.current;
        if (gridList){
            const { scrollLeft, clientWidth } = gridList;
            gridList.scrollLeft=scrollLeft+(change*clientWidth);
        }
    }
    const renderBtns=()=>{
        const preState=(pageState==0);
        const nextState=(pageState==2);
        return (
            <>
                <button className={styles.slide_btn} disabled={preState} onClick={()=>{
                    onChagePage(-1);
                }}>
                    <svg className={`${styles.btn_arrow} ${styles.btn_left}`}>
                        <use xlinkHref={`${symbol}#icon_Arrow`} />
                    </svg>
                </button>
                <button className={styles.slide_btn} disabled={nextState} onClick={()=>{
                    onChagePage(1);
                }}>
                    <svg className={`${styles.btn_arrow}`}>
                        <use xlinkHref={`${symbol}#icon_Arrow`} />
                    </svg>
                </button>
            </>
        );
    }
    const renderTop=()=>{
        return (
            <div className={styles.grid_top}>
                <div className={styles.grid_tit}>
                    <SvgIcon herf={data.icon}></SvgIcon>
                    <span>{i18n.t(data.title)}</span>
                </div>
                <div className={styles.grid_nav}>
                    <NavLink to={data.link}>
                        <span>{i18n.t('small_list.view_all')}</span>
                    </NavLink>
                    {
                        isMobile()?(<></>):renderBtns()
                    }
                </div>
            </div>
        );
    }
    const renderDeskList=()=>{
        return (
            <>
                <div className={styles.grid_list} ref={gridListRef}>
                    {
                        list.map((item, index) => {
                            let gridNum=item.gridNum!=null?item.gridNum:1;
                            // gridNum=Math.floor(Math.random()*3)+1;
                            let whStyle=gridInfo[gridNum];
                            if (whStyle==null)return (<></>);
                            return (
                                <GameItem whStyle={whStyle} key={index} data={item} handleRoom={handlePopSelected}></GameItem>
                            )
                        })
                    }
                </div>
                <GameRoom open={showPopRoom} data={roomRow.data} user={user} onClose={handlePopClose}></GameRoom>
            </>
        )
    }
    const renderRoom = () => {
        if (roomRow == null || roomRow.data == null) return (<></>);
        if (roomRow.hide) return (<></>);
        return (
            <GameRoom open={true} data={roomRow.data} height={roomHeight + "rem"} mobile={true} user={user}></GameRoom>
        )
    }
    const renderMobileList = () => {
        let gridStyle = {}
        let len=list.length;
        let roomTop=getRoomConTop();
        if (selected !== -1) {
            let top=roomTop;
            if (top<50){
                gridStyle.paddingTop=`${roomHeight+rowGap}rem`;
            }
            else
            {
                if (len<=3){
                    gridStyle.paddingBottom=`${roomHeight+rowGap}rem`;
                }
                else gridStyle.gap=`${rowTop}rem`;
            }
        }
        let rowlist=formatMList(list);
        return (
            <>
                <div className={`${styles.grid_list_m}`} ref={gridListMRef}>
                    <div className={styles.grid_row_con} style={gridStyle}>
                        {
                            rowlist.map((ritem,rindex)=>{
                                if (ritem==null)return (<></>);
                                return (
                                        <div key={rindex} className={styles.grid_row}>
                                            {
                                                ritem.map((item,index)=>{
                                                    let itemStyle={}
                                                    if (selected!==-1){
                                                        let row=index%2;
                                                        if (item.id!==selected){
                                                            itemStyle.filter="brightness(60%)";
                                                        }
                                                        else
                                                        {
                                                            itemStyle.transform="scale(1.02)";
                                                        }
                                                    }
                                                    let gridNum=item.gridNum!=null?item.gridNum:1;
                                                    // gridNum=Math.floor(Math.random()*3)+1;
                                                    let whStyle=gridInfo[gridNum];
                                                    if (whStyle==null)return (<Fragment key = {index}></Fragment>);
                                                    return (
                                                            <GameItem whStyle={whStyle} key={(ritem.length*rindex)+index} data={item} handleRoom={(e,data)=>{
                                                                handleSelect(e,data);
                                                                }} style={itemStyle}></GameItem>
                                                    )
                                                })
                                            }
                                        </div>
                                )
                            })
                        }
                    </div>
                    {/*{*/}
                    {/*    list.map((item, index) => {*/}
                    {/*        let itemStyle={}*/}
                    {/*        if (selected!==-1){*/}
                    {/*            let row=index%2;*/}
                    {/*            if (item.id!==selected){*/}
                    {/*                itemStyle.filter="brightness(60%)";*/}
                    {/*            }*/}
                    {/*            else*/}
                    {/*            {*/}
                    {/*                itemStyle.transform="scale(1.02)";*/}
                    {/*            }*/}
                    {/*        }*/}
                    {/*        let gridNum=item.gridNum!=null?item.gridNum:1;*/}
                    {/*        gridNum=Math.floor(Math.random()*3)+1;*/}
                    {/*        let whStyle=gridInfo[gridNum];*/}
                    {/*        if (whStyle==null)return (<></>);*/}
                    {/*        return (*/}
                    {/*            <GameItem whStyle={whStyle} key={index} data={item} handleRoom={(e,data)=>{*/}
                    {/*                handleSelect(e,data);*/}
                    {/*            }} style={itemStyle}></GameItem>*/}
                    {/*        )*/}
                    {/*    })*/}
                    {/*}*/}
                </div>
                <StyledRoomCon top={roomTop}>
                    {renderRoom()}
                </StyledRoomCon>
            </>
        )
    }
    const renderList = () => {
        if (isMobile()) return renderMobileList();
        else return renderDeskList();
    }
    return (
        <div className={`w-100 ${styles.list_container}`} ref={gridConRef}>
            {renderTop()}
            {renderList()}
        </div>
    )
}
export default GameSmallList;
