<script lang="ts" setup>
    const page = reactive({
        security: false,
        title: '',
        link: '',
        styles: {
            progress: {
                color: '#42c02e',
                height: '1%',
            },
        },
    })

    onLoad(({ title, link, sub }) => {
        page.title = title ? decodeURIComponent(title) : ''
        page.link = decodeURIComponent(link)

        // 嵌入页面进行二级子页面跳转时，参数会被多次 encode
        if (sub) {
            page.title = decodeURIComponent(page.title)
            page.link = decodeURIComponent(page.link)
        }

        if (!link) {
            Message.toast('页面打开失败，参数错误')
            uni.navigateBack()
            return
        }

        // 设置标题栏为文件名
        if (page.title && page.title !== 'undefined') {
            uni.setNavigationBarTitle({
                title: page.title,
            })
        }

        Message.loading()
        // #ifdef APP-PLUS
        const system = uni.getSystemInfoSync()
        // 对于不安全或不信任的网站地址或可能触发 plus API 的来源，采用手动创建 webview 的方式打开
        const webview = plus.webview.create(page.link, 'no-security-webview', {
            progress: page.styles.progress,
        })

        // FIXED: 处理 iOS 下意外的高度兼容性问题
        if (system.platform === 'ios') {
            webview.setStyle({
                popGesture: 'none',
                scrollIndicator: 'none',
                // top: `${system.statusBarHeight}px`,
                bottom: `${system.safeAreaInsets.bottom}px`,
                background: 'transparent',
                statusbar: { background: '#ffffff' },
            })
        }

        webview.addEventListener(
            'loaded',
            () => {
                // FIX: classId 可能随着每个 Web SDK 版本会更新，需要注意，一旦发生变更可能会丢失部分样式（用户头像）
                const classId = 'ca5e07ec94ad125e02ca'
                let paddingTop = `${system.statusBarHeight}px`
                if (system.platform === 'ios') {
                    paddingTop = '0px'
                }

                webview.appendJsFile('_www/static/uni.webview.1.5.6.js')
                webview.evalJS(`
                    document.addEventListener('UniAppJSBridgeReady', function() {
                        uni.getEnv(function(res) {
                            console.log('当前环境：' + JSON.stringify(res));
                        })
                    })

                    // 禁止页面缩放
                    var meta = document.createElement('meta')
                    meta.name = 'viewport'
                    meta.content = 'width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no'
                    document.head.appendChild(meta)

                    // 隐藏底部描述和图片上传能力
                    var style = document.createElement('style')
                    style.id = 'no-security-webview-style'
                    style.innerHTML = 'footer { display: none !important; } .close-btn { z-index: 99999; position: absolute; right: 12px; top: calc(18px + ${paddingTop}); padding: 8px; } html { padding-top: ${paddingTop}; background: white; } .semi-avatar>img { border-radius: 50% !important; } .${classId}-content>div:last-child .semi-avatar-img img { opacity: 0; } .${classId}-content>div:last-child .semi-avatar-img { position: relative; background-image: url(https://hntq.yiring.com/minio/public/system/ai/hntq-ai-user-2.png); background-size: cover; background-position: center; }'
                    document.body.appendChild(style)

                    // 添加关闭按钮
                    var div = document.createElement('div')
                    div.className = 'close-btn'
                    div.innerHTML = '<svg xmlns="http://www.w3.org/2000/svg" width="28" height="28" viewBox="0 0 24 24"><path fill="#666" d="m12 13.4l-4.9 4.9q-.275.275-.7.275t-.7-.275t-.275-.7t.275-.7l4.9-4.9l-4.9-4.9q-.275-.275-.275-.7t.275-.7t.7-.275t.7.275l4.9 4.9l4.9-4.9q.275-.275.7-.275t.7.275t.275.7t-.275.7L13.4 12l4.9 4.9q.275.275.275.7t-.275.7t-.7.275t-.7-.275z"/></svg>'
                    div.onclick = function() {
                        uni.navigateBack()
                    }
                    document.body.appendChild(div)

                    setTimeout(() => {
                        var header = document.querySelector('header')
                        if (!header) {
                            var ok = confirm('抱歉，发现了不兼容的问题，请您检查系统版本是否过于旧，欢迎升级后再尝试体验，感谢您的支持~')
                            uni.navigateBack()
                        }
                    }, 5000);
                `)
            },
            false,
        )

        const pages = getCurrentPages()
        const currentPage = pages[pages.length - 1]
        const currentWebview = currentPage.$getAppWebview()
        currentWebview.setStyle({ progress: page.styles.progress, popGesture: 'none' })
        currentWebview.append(webview)
        // #endif
        // #ifndef APP-PLUS
        page.security = true
        // #endif
        setTimeout(() => {
            Message.hideLoading()
        }, 2000)
    })
</script>

<template>
    <view class="wrap" v-if="page.link">
        <template v-if="page.security">
            <web-view :src="page.link" :update-title="!page.title" :webview-styles="page.styles" />
        </template>
    </view>
</template>
