<template>
    <cwg-page-wrapper>
        <view class="safe-wrapper">
            <web-view class="aaa" v-if="qrCodeUrl" :src="qrCodeUrl" :webview-styles="webviewStyles"></web-view>
        </view>

    </cwg-page-wrapper>
</template>

<script setup lang="ts">
import { ref } from "vue";
import { useI18n } from "vue-i18n";
import useRouter from "@/hooks/useRouter";
import { ucardApi } from "@/api/ucard";
import { onLoad } from '@dcloudio/uni-app'
import { computed, onMounted } from 'vue'
import useGlobalStore from '@/stores/use-global-store'
import { permission } from "@/js_sdk/wa-permission/permission.js"
const globalStore = useGlobalStore()
const statusBarHeight = computed(() => globalStore.statusBarHeight);
const cardId = ref("");
onLoad((options) => {
    // #ifdef APP-PLUS
    const isIos = (plus.os.name == "iOS")
    // #endif

    // #ifdef APP-PLUS
    if (isIos) {
        const camera = permission.judgeIosPermission('camera')
        console.log(camera, 'iOS camera permission');
        if (!camera) {
            permission.gotoAppPermissionSetting()
        }
    } else {
        permission.requestAndroidPermission('android.permission.CAMERA').then((result) => {
            console.log(result, 'Android camera permission result');
            if (result !== 1) {
                permission.gotoAppPermissionSetting()
            }
        })
    }
    // #endif

    cardId.value = options?.cardId
    getWebsdkLink();
});
const webviewStyles = ref({
    progress: {
        color: '#ea002a'
    },
    bounce: 'none',
    scrollIndicator: 'none',
    top: statusBarHeight.value + 60 + 'px',
    bottom: '0px'
})
const { t } = useI18n();
const router = useRouter();
// 二维码链接
const qrCodeUrl = ref("");
// API 响应码
const responseCode = ref(200);
// 设备元信息
const metaInfo = ref<Record<string, any> | null>(null);

/**
 * 获取设备元信息
 */
function getMetaInfo() {
    try {
        // 安全获取 metaInfo，兼容不同环境
        if (typeof window !== "undefined" && (window as any).getMetaInfo) {
            metaInfo.value = (window as any).getMetaInfo();
            metaInfo.value = { ...metaInfo.value, deviceType: "h5" };
        } else {
            // 默认值
            metaInfo.value = { deviceType: "h5" };
        }
    } catch (error) {
        console.warn("获取设备信息失败:", error);
        metaInfo.value = { deviceType: "h5" };
    }
}

/**
 * 获取 WebSDK 链接
 * @param cardId 卡片ID
 */
async function getWebsdkLink() {
    if (!cardId.value) {
        console.warn("cardId 为空，无法获取 WebSDK 链接");
        return;
    }
    try {
        // 获取设备信息
        getMetaInfo();
        // 调用 API
        const res = await ucardApi.getWebsdkLink({
            cardId: String(cardId.value),
            metaInfo: metaInfo.value,
        });

        responseCode.value = res.code || 201;
        if (res.code === 200 && res.data) {
            try {
                // 安全解析 JSON
                const data = typeof res.data === "string" ? JSON.parse(res.data) : res.data;
                qrCodeUrl.value = data.url || data.link || "";
            } catch (parseError) {
                console.error("解析响应数据失败:", parseError);
                responseCode.value = 201;
            }
        } else {
            qrCodeUrl.value = "";
        }
    } catch (error: any) {
        console.error("获取 WebSDK 链接失败:", error);
        responseCode.value = 201;
        qrCodeUrl.value = "";
    }
}

</script>

<style scoped lang="scss">
@import "@/uni.scss";

.aaa {
    background-color: var(--color-white);
    position: absolute;
    top: env(safe-area-inset-top);
    left: 0;
    right: 0;
    bottom: env(safe-area-inset-bottom);
}

.safe-wrapper {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding-top: env(safe-area-inset-top);
    padding-bottom: env(safe-area-inset-bottom);
    background-color: var(--color-white);
}
</style>
