<template>
	<web-view :src="webviewSrc" @message="onMessage" />
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const webviewSrc = ref('')
let eventChannel = null

onLoad((query) => {
	const captchaId = decodeURIComponent(query.captchaId || '')
	webviewSrc.value = `/static/html/geetest-captcha.html?captchaId=${encodeURIComponent(captchaId)}`
	const pages = getCurrentPages()
	const page = pages[pages.length - 1]
	eventChannel = page.getOpenerEventChannel?.()
})

function onMessage(e) {
	const payload = (e.detail && e.detail.data && e.detail.data[0]) || {}
	if (payload.type === 'success') {
		eventChannel?.emit('geetestSuccess', payload.result || {})
		uni.navigateBack()
		return
	}
	eventChannel?.emit('geetestFail', payload.msg || '人机验证未通过')
	uni.navigateBack()
}
</script>
