"use client";
import { PromotionRep } from "@/api/home";
import Agent, { AgentSuffix } from "@/components/Agent";
import { ModalEnum } from "@/components/Box/types";
import feedback from "@/feedback";
import { usePathname } from "@/i18n/routing";
import { useUserInfoStore } from "@/stores/useUserInfoStore";
import useWheelStore from "@/stores/useWheelStore";
import { commonMask, sleep } from "@/utils";
import { server } from "@/utils/client";
import { getToken } from "@/utils/Cookies";
import { Local } from "@/utils/storage";
import { useDebounceEffect } from "ahooks";
import dayjs from "dayjs";
import React from "react";
import dialogManage from "./manager";

const keyMap: any = {
    0: "ban_pop_type_0",
    1: "ban_pop_type_1",
    2: "pop_type_2",
    3: "pop_type_3",
};

const doFun = async (data: PromotionRep) => {
    switch (data.action_type) {
        case 2:
            window.open(data.action_params, "_blank");
            break;
        case 3:
            let path = data.action_params;
            if (data.activity_id) {
                path = `${data.action_params}?activity_id=${data.activity_id}`;
            }
            if (path) {
                window.nextRouter.push(path);
            }
            break;
        case 4:
            if (data.action_params === ModalEnum.red_packet) {
                dialogManage.showDialog("RedPacket");
            }
            if (data.action_params === ModalEnum.pwa_install) {
                dialogManage.showDialog("PwaInstall");
            }
            break;
        case 5:
            data?.action_params ? await eval(data?.action_params || "") : "";
            break;
        default:
            break;
    }
};

export const showProxy1 = async () => {
    await feedback.showModal({
        content: () => <Agent step={1}></Agent>,
        width: "90%",
        useDefaultFooter: false,
        suffix: () => <AgentSuffix></AgentSuffix>,
    });
};

export const showProxy2 = async () => {
    await feedback.showModal({
        content: <Agent step={2}></Agent>,
        width: "90%",
        useDefaultFooter: false,
        suffix: <AgentSuffix></AgentSuffix>,
    });
};

const getPromotions = async () => {
    return server
        .request<PromotionRep[], { summery: { showType: 1 | 2 } }>({
            url: "/v1/api/front/pop_list",
            method: "POST",
        })
        .then((res) => {
            if (res.code === 200) return res;
        });
};

const AutoShowDialog = () => {
    const pathName = usePathname();
    const [data, setData] = React.useState<PromotionRep[]>([]);
    const { userInfo } = useUserInfoStore();
    const wheelState = useWheelStore((state) => state);
    const [cacheUserInfo, setCacheUserInfo] = React.useState<any>({});

    useDebounceEffect(() => {
        if (cacheUserInfo?.id !== userInfo?.id || !userInfo?.id) {
            getData();
            if (userInfo?.id) {
                setCacheUserInfo(userInfo);
            }
        }
    }, [userInfo, cacheUserInfo]);

    React.useEffect(() => {
        if (!data?.length) {
            return;
        }
        setTimeout(() => {
            doShow();
        }, 300);
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [data]);

    const getData = async () => {
        commonMask.show();
        try {
            const res = await getPromotions();
            if (res?.code === 200 && res?.data?.length) {
                setData(res.data);
                if (!res.data?.length) {
                    commonMask.hide();
                }
            } else {
                throw new Error(res?.code?.toString());
            }
        } catch {
            commonMask.hide();
        }
    };

    React.useEffect(() => {
        data.forEach((item) => {
            if (item.content_type === 1) {
                const img = new Image();
                if (item?.content?.image) img.src = item?.content?.image;
            }
        });
    }, [data]);

    const checkIsCanShow = (data: PromotionRep) => {
        const toId = userInfo?.id || "-1";
        // debugger;
        if (!data?.id) return false;
        if (data.pop_type === 2 && !getToken()) return false;
        if (data.pop_type === 3) {
            const popSession = sessionStorage.getItem(`pupupNotShow_${data.id}`);
            // 今天不再展示
            if (popSession && dayjs(Number(popSession)).add(1, "day").isAfter(dayjs(), "day")) {
                return false;
            }
        }
        if (data.pop_type === 1) {
            let popData = Local.getKey(keyMap[data.pop_type]);
            if (!popData) return true;
            try {
                const isCurDay = dayjs(popData.date).add(1, "day").isAfter(dayjs(), "day");
                if (isCurDay && popData[toId][data.id]) {
                    return false;
                }
            } catch {}
        }
        return true;
    };

    const saveCache = (type: 1 | 2 | 3 | 0, popid: number) => {
        const toId = userInfo?.id || -1;
        const cachedData = Local.getKey(keyMap[type]);
        let popData: any = {
            date: Date.now(),
        };
        if (cachedData) {
            try {
                if (dayjs(cachedData.date).isSame(Date.now(), "day")) {
                    popData = cachedData;
                } else {
                    Local.removeKey(keyMap[type]);
                }
            } catch {}
        }
        if (!popData[toId]) {
            popData[toId] = {};
        }
        popData[toId][popid] = true;
        Local.setKey(keyMap[type], JSON.stringify(popData));
    };

    const saveShowIndex = (idx: number) => {
        sessionStorage.setItem("dialogShow", `${idx + 1}`);
    };

    const doShow = async () => {
        setTimeout(() => {
            commonMask.hide();
        }, 500);
        //记录点击的索引
        let showIndex = sessionStorage.getItem("dialogShow");

        let startShow = showIndex ? Number(showIndex) : 0;
        if (startShow > data.length - 1) {
            startShow = 0;
        }

        for (let i = startShow; i < data.length; i++) {
            if (window.location.pathname.length > 3) break;
            const curData = data[i];
            if (!checkIsCanShow(curData)) {
                // saveShowIndex(i);
                continue;
            }

            // await dialogManage.showDialog("ReceiveGift", curData); //周返现
            // await dialogManage.showDialog('WheelSection', curData);  //轮盘
            // await dialogManage.showDialog('SignInSection', curData);  //签到
            // await dialogManage.showDialog("SignInSection", curData);
            try {
                let res: any = "";
                switch (curData.content_type) {
                    // 图片展示
                    case 1:
                        // res = await dialogManage.showDialog("ImgDialog", {
                        //     ...curData,
                        //     isShowNotShow: curData.pop_type === 3,
                        // });
                        const imgUrl = curData?.content?.image;
                        if (imgUrl) {
                            res = await feedback.showImage({
                                imgUrl,
                                showAgain: true,
                            });
                        }
                        break;
                    // 富文本展示
                    case 2:
                        // res = await dialogManage.showDialog("TextDialog", curData);
                        const text = curData?.content?.text;
                        if (text) {
                            res = await feedback.showText({
                                text,
                                showAgain: true,
                            });
                        }
                        break;
                    case 3:
                        // 轮盘特殊处理 dialogManage.showDialog('WheelSection')
                        if (curData?.action_params?.includes("WheelSection")) {
                            await wheelState.setWheel();
                            console.log(useWheelStore.getState());
                            if (useWheelStore.getState().status != 1) {
                                break;
                            }
                        }

                        if (curData.action_type === 5) {
                            res = curData?.action_params
                                ? await eval(curData?.action_params || "")
                                : "";
                        }
                        break;
                }

                if (res.isCheck) {
                    sessionStorage.setItem(`pupupNotShow_${curData.id}`, `${Date.now()}`);
                }
                if (res.bodyClick) {
                    doFun(curData);
                    return;
                }
                // if (Array.isArray(res)) {
                //     const [_, closeType] = res[0].split("_");
                //     if (closeType == 1) {
                //         sessionStorage.setItem(`pupupNotShow_${curData.id}`, `${Date.now()}`);
                //     }
                // }
                if (res === "target") {
                    return;
                }
            } catch (err) {
                // saveShowIndex(i);
                continue;
            }
            // 记录当前展示到几个了
            // saveShowIndex(i);
            if (curData.id) saveCache(curData.pop_type, curData.id);
            await sleep(300);
        }
    };

    return null;
};

export default AutoShowDialog;
