import styles from './styles.module.scss';
import React, {useEffect, useRef, useState} from "react";
import {reqFirstPayConfig, reqFirstPayMulti, reqGameInfo, reqProtectCheck, reqRechargeConfig} from "@features/api";
import {useDispatch, useSelector} from "react-redux";
import {getFirstBonus, getOpenRelief, getPopBindPhone, getUpgradeBonus, getUserInfo} from "@features/mainSlice";
import {APP_WELFARE} from "@constants/app";
import {getBonusPack, getCurrPayOrder, getFirstPayMulti, getOFirstPay} from "@features/paySlice";
import {getProtectInfo} from "@features/protectSlice";
import {formatCash, formatTime, localStorageGet, localStorageSet} from "@utils/helpers";
import {useThemeProvider} from "@contexts/themeContext";
import {useSidebar} from "@contexts/sidebarContext";
import {useLocation} from "react-router-dom";
import {ROUTE_PATH} from "@constants/routes";
const i18n=global.i18n;
const WelfareBtn=({children,open=false,pressDown=false,...props})=>{
    const [bopen,setBopen]=useState(false);
    const [show,setShow]=useState(false);
    useEffect(()=>{
        if (open){
            setShow(true);
            setTimeout(()=>{
                setBopen(true);
            },100)
        }
        else
        {
            setBopen(false);
            setShow(false);
        }
    },[open])
    return (
        <>
            {
                show? (
                    <button
                        className={`${styles.wlf_btn} ${bopen ? styles.wlf_btn_open : styles.wlf_btn_close} ${pressDown ? styles.wlf_btn_press : ''}`}
                        {...props}
                    >
                        {
                            children == null ? (<></>) : children
                        }
                    </button>
                ):(<></>)
            }
        </>
    )
}
const WWelfarebar = () => {
    const dispatch = useDispatch();
    const user = useSelector(getUserInfo);
    //0:1,1:1,2:1
    // const [openState, setOpenState] = useState({});
    const [openProtect, setOpenProtect] = useState(0);
    const [openFirst, setOpenFirst] = useState(0);
    const [openBind, setOpenBind] = useState(0);
    const firstPayConf = useSelector(getOFirstPay);
    const popBindPhone=useSelector(getPopBindPhone);
    const firstBonus=useSelector(getFirstBonus);
    const openRelief=useSelector(getOpenRelief);
    const protectInfo=useSelector(getProtectInfo);
    const orderInfo=useSelector(getCurrPayOrder);
    const {welfTabState,isMobile}=useThemeProvider();
    const {open} = useSidebar();
    const {pathname} = useLocation();
    const starPRef=useRef(null);
    const upgradBonus=useSelector(getUpgradeBonus);
    const regCoins=formatCash(upgradBonus,0);
    const firstPayMulti=useSelector(getFirstPayMulti);
    //bonus pack
    const [openBonusPack, setOpenBonusPack] = useState(0);
    const bonusPack=useSelector(getBonusPack);
    const getWelfTabState=(key)=>{
        if (welfTabState===key)return true;
        return false;
    }
    const changeNewState=(key,state)=>{
        // let newOpenState= Object.assign({},openState);
        // newOpenState[key]=state;
        // setOpenState(newOpenState);
        // state=1;
        switch (key){
            case APP_WELFARE.PROTECT:
                setOpenProtect(state);
                break;
            case APP_WELFARE.FIRST_PAY:
                setOpenFirst(state);
                break;
            case APP_WELFARE.BIND:
                setOpenBind(state);
                break;
            case APP_WELFARE.BONUS_PACK:
                setOpenBonusPack(state);
                break;
        }
    }
    const checkProtect=()=>{
        let state=0;
        if (openRelief){
            if (protectInfo!=null){
                if (user.UserID>0){
                    // let CurProtectTimes=protectInfo.CurProtectTimes!=null?parseInt(protectInfo.CurProtectTimes):0;
                    // if (CurProtectTimes>0)state=1;
                    state=1;
                }
            }
        }
        changeNewState(APP_WELFARE.PROTECT,state);
    }
    const checkProtectLimit=()=>{
        if (protectInfo!=null){
            let ProtectLimit=protectInfo.ProtectLimit;
            if (ProtectLimit!=null){
                ProtectLimit=Number(ProtectLimit);
                ProtectLimit=Number(formatCash(ProtectLimit))
                let Score=user.Score;
                if (Score<=ProtectLimit){
                    dispatch(reqProtectCheck());
                }
            }
        }
    }
    const checkFirstPay=()=>{
        let state=0;
        if (firstBonus){
            // if (user.UserID>0){
            //     if (firstPayConf!=null)state=1;
            // }
            if (firstPayMulti!=null){
                state=1;
                let firstOpen=localStorageGet("IS_FIRST_PAY_OPEN","");
                //充值成功弹一下
                if (firstPayMulti.pay_sucess&&firstOpen===""){
                    global.showFirstPay();
                    localStorageSet("IS_FIRST_PAY_OPEN","1");
                }
            }
        }
        changeNewState(APP_WELFARE.FIRST_PAY,state);
    }
    const checkFirstPayStatus=()=>{
        if (orderInfo!=null){
            if (orderInfo.status==="success"){
                // dispatch(reqFirstPayConfig());
                //pay_success
                //dispatch(reqFirstPayMulti(1));
            }
        }
    }
    const checkBind=()=>{
        let state=0;
        if (popBindPhone){
            let bonus=Number(upgradBonus);
            if (user.UserID>0&&bonus>0){
                if (user.Phone==null||user.Phone===""){
                    state=1;
                }
            }
        }
        changeNewState(APP_WELFARE.BIND,state);
    }
    const getSymbol=()=>{
        let symbols=['$','€','₽','M$','R$'];
        let dollar=global.DOLLAR;
        if (symbols.indexOf(dollar)===-1)dollar=symbols[0];
        return dollar;
    }
    const getFirstCD=()=>{
        let timeleft=-1;
        if (firstPayMulti!=null&&firstPayMulti.leftitem!=null){
            timeleft=Number(firstPayMulti.leftitem.timeleft);
        }
        return timeleft;
    }
    const formatFirstCD=(firstCD)=>{
        let cdStr=formatTime(firstCD);
        cdStr=cdStr.substring(0,cdStr.length-3);
        return cdStr;
    }
    //bonus pack
    const checkBonusPack=()=>{
        let state=0;
        if (bonusPack&&bonusPack.timeleft>0){
            state=1;
        }
        changeNewState(APP_WELFARE.BONUS_PACK,state);
    }
    const getBonusPackCD=()=>{
        let timeleft=-1;
        if (bonusPack!=null){
            timeleft=Number(bonusPack.timeleft);
        }
        return timeleft;
    }
    const formatBonusPackCD=(bonusCD)=>{
        let cdStr=formatTime(bonusCD);
        // cdStr=cdStr.substring(0,cdStr.length-3);
        return cdStr;
    }
    useEffect(()=>{
        let UserID=user.UserID;
        if (UserID>0){
            dispatch(reqProtectCheck());
            // dispatch(reqGameInfo());
        }
        dispatch(reqRechargeConfig());
        // dispatch(reqFirstPayConfig());
        //dispatch(reqFirstPayMulti());
    },[user.UserID]);
    useEffect(() => {
        checkProtectLimit();
    }, [user.Score]);
    // useEffect(()=>{
    //     checkFirstPay();
    // },[firstPayConf]);
    useEffect(()=>{
        checkFirstPay();
    },[firstPayMulti]);
    useEffect(()=>{
        checkBind();
    },[popBindPhone,user.Phone]);
    useEffect(()=>{
        checkProtect();
    },[protectInfo])
    useEffect(()=>{
        checkFirstPayStatus();
    },[orderInfo])
    //bonus pack
    useEffect(()=>{
        checkBonusPack();
    },[bonusPack])
    const renderBar=()=>{
        let extra='';
        if (!isMobile()){
            if (open)extra='sidebar-open';
            else extra='sidebar-close';
        }
        let isClose=false;
        if (pathname.startsWith(ROUTE_PATH.SPORTS)){
            isClose=true;
        }
        else if(pathname.startsWith(ROUTE_PATH.RACING)){
            isClose=true;
        }
        const stars=Array.from({ length: 5 }, (_, index) => index);
        let symbol=getSymbol();
        let firstCD=getFirstCD();
        let bonusCD=getBonusPackCD();
        return (
            <div className={`${styles.container} ${extra}`}>
                <div className={`${styles.content} ${isClose?styles.content_close:''}`}>
                    <WelfareBtn key={"protect"} open={openProtect} pressDown={getWelfTabState(APP_WELFARE.PROTECT)}
                                onClick={() => {
                                    global.showProtectReward();
                                }}>
                        <div className={styles.wlf_protect}>
                            {/*<img src={require("@assets/welfare/fundos_" + i18n.language + ".png")}/>*/}
                            <img className={styles.p_img} src={require("@assets/welfare/fundos_" + symbol + ".png")}/>
                            <div ref={starPRef} className={styles.p_stars}>
                                {
                                    stars.map((item,index)=>{
                                        return (
                                            <div key={index} className={`${styles.star} ${styles['star_ani_'+index]}`}></div>
                                        )
                                    })
                                }
                            </div>
                            <img className={styles.p_txt} src={require("@assets/welfare/fundos_title_" + i18n.language + ".png")}/>
                        </div>
                    </WelfareBtn>
                    <WelfareBtn key={"first_pay"} open={openFirst} pressDown={getWelfTabState(APP_WELFARE.FIRST_PAY)}
                                onClick={() => {
                                    global.showFirstPay();
                                }}>
                        <div className={styles.wlf_first}>
                            <div className={styles.wlf_first_mask} style={{
                                WebkitMask:`url(${require("@assets/welfare/bag_"+symbol+".png")}) 0 0/100%`
                            }}>
                                <img className={styles.f_img} src={require("@assets/welfare/bag_"+symbol+".png")}/>
                            </div>
                            {
                                firstCD<=0? (<img className={styles.f_txt}
                                                 src={require("@assets/welfare/first_" + i18n.language + ".png")}/>): (
                                    <span data-title={formatFirstCD(firstCD)}
                                          className={styles.f_cdtxt}>{formatFirstCD(firstCD)}</span>
                                )
                            }

                        </div>
                    </WelfareBtn>
                    <WelfareBtn key={"bind"} open={openBind} pressDown={getWelfTabState(APP_WELFARE.BIND)}
                                onClick={() => {
                                    global.showBindPhone();
                                }}>
                        <div className={styles.wlf_bind}>
                            {/*<img className={`${styles.b_icon} iconshake`}*/}
                            {/*     src={require("@assets/welfare/veri_" + i18n.language + ".png")}/>*/}
                            <div className={`${styles.b_icon} iconshake`}>
                                <img className={styles.b_bg} src={require("@assets/welfare/otp_" + symbol + ".png")}/>
                                <img className={styles.b_get}
                                     src={require("@assets/welfare/get_" + i18n.language + ".png")}/>
                                <span data-title={regCoins}
                                      className={styles.b_num}>{regCoins}</span>
                            </div>
                            <img className={`${styles.b_txt}`}
                                 src={require("@assets/welfare/bind_txt_" + i18n.language + ".png")}/>
                        </div>
                    </WelfareBtn>
                    <WelfareBtn key={"bonus_pack"} open={openBonusPack}
                                pressDown={getWelfTabState(APP_WELFARE.BONUS_PACK)}
                                onClick={() => {
                                    global.showBonusPack();
                                }}>
                        <div className={styles.wlf_bpack}>
                            <div className={styles.wlf_bpack_mask} style={{
                                WebkitMask: `url(${require("@assets/welfare/bonuspack.png")}) 0 0/100%`
                            }}>
                                <img className={styles.f_img} src={require("@assets/welfare/bonuspack.png")}/>
                            </div>
                            <span data-title={formatBonusPackCD(bonusCD)}
                                  className={styles.f_cdtxt}>{formatBonusPackCD(bonusCD)}</span>
                        </div>
                    </WelfareBtn>
                </div>
            </div>
        )
    }
    return (
        <>
            {renderBar()}
        </>
    )
}
export default WWelfarebar;
