<template>
  <web-view v-if="url" :src="url" @message="onMessage"></web-view>
</template>

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

const url = ref('')

onLoad((options) => {
  if (options.url) {
    url.value = decodeURIComponent(options.url)
    console.log('Opening Game WebView:', url.value)
  } else {
    uni.showToast({ title: '游戏地址无效', icon: 'none' })
    setTimeout(() => uni.navigateBack(), 1500)
  }
})

function onMessage(e) {
  const data = e.detail.data || []
  data.forEach(msg => {
    if (msg.action === 'close') {
      uni.navigateBack()
    } else if (msg.action === 'playAgain') {
      uni.navigateBack({
        delta: 1,
        success: () => uni.$emit('refreshGame')
      })
    }
  })
}
</script>
