import { ref, onMounted } from "vue";
import "@/assets/uni-webview"

export function useWebView() {
    const platform = ref("");
    const token = ref("");
    // 检测环境并通知父窗口加载完毕
    const handleBridgeReady = () => {
        if (platform.value) {
            h5PostMessage("loaded", true);
        }
    };


    const getFromUrl = () => {
        const urlParams = new URLSearchParams(window.location.search);
        const tokenFromUrl = urlParams.get("token");
        token.value = tokenFromUrl || ""; // 如果 URL 没有 token，返回空字符串
        if (token.value) {
            localStorage.setItem("token", token.value);
        }

        const env = urlParams.get("env");
        // 是在webview模式下
        if (env) {
            document.title = "全能查"
            platform.value = env
            localStorage.setItem("webview_env", env)
        }
    };

    // 封装 postMessage 方法
    const postMessage = (data) => {
        if (platform.value === "h5") {
            h5PostMessage("postMessage", data);
        } else if (uni && uni.webView.postMessage) {
            uni.webView.postMessage(data);
        } else {
            console.error("uni.webView.postMessage is not available.");
        }
    };

    const redirectTo = (data) => {
        if (platform.value === "h5") {
            h5PostMessage("redirectTo", data)
        } else if (uni && uni.webView.redirectTo) {
            // 非 H5 环境，调用 uni.webView.redirectTo
            uni.webView.redirectTo(data);
        } else {
            console.error("uni.webView.redirectTo is not available.");
        }
    };

    // 封装 navigateBack 方法
    const navigateBack = (data) => {
        if (platform.value === "h5") {
            window.top.history.back();
            // h5PostMessage("navigateBack", data)
        } else if (uni && uni.webView.navigateBack) {
            // 非 H5 环境，调用 uni.webView.navigateBack
            uni.webView.navigateBack(data);
        } else {
            console.error("uni.webView.navigateBack is not available.");
        }
    };

    // 封装 navigateTo 方法
    const navigateTo = (data) => {
        if (platform.value === "h5") {
            // h5PostMessage("navigateTo", data)
            window.top.location.href = "/app" + data.url
        } else if (uni && uni.webView.navigateTo) {
            uni.webView.navigateTo(data);
        } else {
            console.error("uni.webView.navigateTo is not available.");
        }
    };
    const payment = (data) => {
        if (platform.value === "h5") {
            h5PostMessage("payment", data)
        } else if (uni && uni.webView.navigateTo) {
            // 非 H5 环境，调用 uni.webView.navigateTo
            uni.webView.navigateTo(data);
        } else {
            console.error("uni.webView.navigateTo is not available.");
        }
    }
    const getEnv = () => {
        return new Promise((resolve, reject) => {
            let env = localStorage.getItem(platform)
            if (env) {
                platform.value = env
                resolve(env);
            } else {
                uni.webView.getEnv((env) => {
                    // 遍历 env 对象，找到值为 true 的键
                    const platformKey = Object.keys(env).find(key => env[key] === true);
                    platform.value = platformKey;
                    if (platformKey) {
                        resolve(platformKey); // 返回键名（如 'h5', 'mp-weixin' 等）
                    } else {
                        reject('未知平台');
                    }
                });
            }
        });
    };

    onMounted(() => {
        // try {
        //     const envValue = await getEnv();
        //     console.log("当前环境", envValue)
        //     // 将返回的键名（如 'h5', 'mp-weixin'）存储到 platform
        //     handleBridgeReady();
        // } catch (error) {
        //     console.error(error);
        // }
        // 获取 Token等
        getFromUrl();
    });

    return {
        platform,
        token,
        getEnv,
        redirectTo,
        postMessage,
        navigateTo,
        navigateBack,
        payment
    };
}
const h5PostMessage = (action, data) => {
    window.parent.postMessage({ action, data, messageId: generateUniqueId(action) }, "*");
}
const generateUniqueId = (action) => `msg_${action}_${new Date().getTime()}`;
