import { ROUTE_PATH } from "@constants/routes";
import WITHDRAW_TYPE from "@constants/withdraw_types";
import { useWithdrawMission } from "@contexts/withdrawMissionContext";
import { reqFreeWithdraw, reqFreeWithdrawClaim, reqWithdrawBaseInfo } from "@features/api";
import { getFreeWithdraw, getFreeWithdrawMission, getIsBindPhone, isLogined } from "@features/mainSlice";
import { getWithdrawBaseInfo } from "@features/paySlice";
import { useEffect, useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router";

const useFreeWithdraw = () => {
    const isBindPhone = useSelector(getIsBindPhone);
    const freeWithdraw = useSelector(getFreeWithdraw);
    const withdrawBase = useSelector(getWithdrawBaseInfo);
    const withdrawMission = useSelector(getFreeWithdrawMission);
    const isLogin = useSelector(isLogined);
    const { open: withdrawMissionOpen, setOpen: setWithdrawMissionOpen } = useWithdrawMission();
    const navigate = useNavigate();
    const dispatch = useDispatch();

    const withdrawBaseRef = useRef(null);
    useEffect(() => { withdrawBaseRef.current = withdrawBase; }, [withdrawBase]);

    useEffect(() => {
        if (!withdrawBase && isLogin) {
            dispatch(reqWithdrawBaseInfo());
        }
    }, [withdrawBase, isLogin]);


    const openWithdrawMission = () => {
        if (withdrawMissionOpen) return;

        global.ignorePopup = true;
        navigate(ROUTE_PATH.HOME, { replace: true });
        setWithdrawMissionOpen(true);
    };

    const checkWithdrawInfo = () => {
        //const withdrawBase = withdrawBaseRef.current;
        switch (parseInt(withdrawBase.PixType)) {
            case 1:
                //cash app
                if (!withdrawBase.BankUserName || withdrawBase.BankUserName.length == 0) {
                    return false;
                }

                if (!withdrawBase.PixNum || withdrawBase.PixNum.length == 0) {
                    return false;
                }

                return true;
            case 2:
                //paypal
                if (!withdrawBase.EmailAddress || withdrawBase.EmailAddress.length == 0) {
                    return false;
                }
                return true;
        }

        return false;
    };

    const openWithdrawInGame = () => {
        // 完成充值  绑定手机信息后  打开任务页面
        if (checkWithdrawInfo() && freeWithdraw.state > 2) {
            openWithdrawMission();
            return;
        }

        global.ignorePopup = true;
        navigate(ROUTE_PATH.FREEWITHDRAW, { replace: true });
    };

    const checkMissionStatus = () => {
        var stage = -1;
        var task_id = -1;
        const misson_list = [withdrawMission.stage1, withdrawMission.stage2, withdrawMission.stage3];
        const misson_idx = misson_list.findIndex((mission, idx) => {
            if (idx == 2) return mission?.tasks[0]?.reward_status == 1;
            //已完成未领取的任务
            return mission?.reward_status == 1;
        });

        if (misson_idx > -1) {
            var misson = misson_list[misson_idx];
            //amount = misson.reward;
            stage = misson_idx + 1;

            if (stage === 3) {
                task_id = misson.tasks.findIndex((task) => {
                    return task.reward_status == 1;
                });
                task_id = misson.tasks[task_id].id;
            }
        }

        if (stage <= 0 || (stage === 3 && task_id === -1)) {
            // console.error(`stage:${stage} task_id:${task_id} 有任务没有完成`);
            openWithdrawMission();
            return false;
        }
        // console.error(`stage:`, stage, "task_id:", task_id);

        return { stage, task_id };
    };

    const claimFreeWithdraw = async (score) => {
        if (!isBindPhone) {
            let result = await new Promise((resolve, reject) => {
                global.bindPhoneRes = resolve;
                global.showBindPhone();
            });
            if (!result) return false;
        }

        // if (!checkWithdrawInfo() || freeWithdraw.state <= 2) {
        //     let result = await new Promise((resolve, reject) => {
        //         global.withdrawRes = resolve;
        //         // 未填写信息
        //         navigate(ROUTE_PATH.FREEWITHDRAW);
        //         setWithdrawMissionOpen(false);
        //     });
        //     if (!result) return false;
        // }

        let missonState = checkMissionStatus();
        if (!missonState) {
            openWithdrawMission(true);
            return false;
        }

        global.openFixedWithdraw({
            type: WITHDRAW_TYPE.MISSION,
            score,
            callback: async () => {
                await dispatch(reqFreeWithdrawClaim(missonState)).unwrap();
                await dispatch(reqFreeWithdraw()).unwrap();

                navigate(ROUTE_PATH.HOME, { replace: true });
            }
        });

        return true;
    };

    return {
        openWithdrawInGame,
        claimFreeWithdraw,
    };
};

export default useFreeWithdraw;;