import {createGlobalState, useEventListener, useStorage} from "@vueuse/core";
import {computed, ref} from "vue";
import mxConst from "@/common/mxConst";
import {sys} from "@/uni_modules/uv-ui-tools/libs/function";

export const useEnvStore = createGlobalState(() => {
    // 平台判断，和调用bridge有关，如视频控制、下载等。
    const platform = ref(window.platform || "");
    const isH5 = computed(() => platform.value === "h5");
    const isWap2App = computed(() => platform.value === "wap2app");

    const systemInfo = computed(() => {
        const {
            platform,
            model,
            deviceId,
            deviceModel,
            deviceType,
            appId,
            version,
            appVersion,
            appVersionCode,
        } = sys();
        return {
            platform,
            model,
            deviceId,
            deviceModel,
            deviceType,
            appId,
            version,
            appVersion,
            appVersionCode,
        };
    });

    const isAndroid = computed(() => systemInfo.value.platform.toLowerCase() == 'android')
    const isIOS = computed(() => systemInfo.value.platform.toLowerCase() == 'ios')

    // TODO: isParent 表示这个应用是从微信公众号启动的。
    // 但这个判断受限于调用时机，不如上面的 platform 有一定封装来保证和运行环境契合。
    const isParent = ref(
        window?.location?.href.includes(mxConst.keyParentIdentifier)
    );

    // 引导页已读标志。
    const isGuideRead = useStorage(mxConst.keyGuideRead, false);

    // 访问相册权限初次提示标志
    const isDisplayedPermission = useStorage(
        mxConst.keyDisplayPermission,
        false
    );

    // hook
    useEventListener(window, "platformChange", (evt) => {
        // @/index.html 中定义的 window.platform 会在不同环境下被赋值，此时需要更新 platform 状态
        // 我们在 setPlatform 中暴露了 platformChange 事件用来让 vue 组件监听平台变化
        platform.value = window?.platform || "";
    });

    return {
        platform,
        isH5,
        isWap2App,
        isParent,
        isGuideRead,
        isDisplayedPermission,
        systemInfo,
        isAndroid,
        isIOS
    };
});
