/**
 * @description 自定义pwa 安装hooks
 */
import { useRouter } from "@/i18n/routing";
import { isIOS } from "@/utils/methods";
import { Dialog } from "antd-mobile";
import { useEffect, useRef, useState } from "react";

const useDesktop = (source: "page" | "components") => {
    const prompt = useRef<Event | null>(null);

    const router = useRouter();
    const [isHasDesktop, setHasDesktop] = useState(false);

    const downloadHandler = () => {
        sessionStorage.setItem("pwa_install", "cancel");
        if (prompt.current) {
            // @ts-ignore
            prompt.current?.prompt();
        } else {
            Dialog.show({
                closeOnMaskClick: true,
                header: (
                    <div className={"text-[white]"} onClick={Dialog.clear}>
                        <i className={"iconfont icon-guanbi"}></i>
                    </div>
                ),
                image: isIOS() ? "/store/ios.webp" : "/store/android.webp",
                actions: [],
            });
        }
        // 不判断是否真的包含
        setHasDesktop(false);
    };

    const initDesktop = (e: Event) => {
        if (window.matchMedia("(display-mode: standalone)").matches) {
            setHasDesktop(false);
            return;
        }
        // 有pwa 则不会触发
        prompt.current = e;
        //sessionStorage.getItem("pwa_install") === null
        if (source === "page") {
            setHasDesktop(true);
        }
    };

    //  取消
    const cancel = () => {
        sessionStorage.setItem("pwa_install", "cancel");
        setHasDesktop(false);
    };

    useEffect(() => {
        window.addEventListener("beforeinstallprompt", (evt) => {
            evt.preventDefault();
            initDesktop(evt);
        });
        // @ts-ignore
        window.onappinstalled = function (ev) {
            // 安装完成
            router.replace("/");
        };
        return () => window.removeEventListener("beforeinstallprompt", initDesktop);
    }, []);

    return {
        cancel,
        isHasDesktop,
        downloadHandler,
        setHasDesktop,
    };
};

export default useDesktop;
