<script setup>
// 接受父组件传递的 props 参数
const props = defineProps({
  webviewSrc: {
    type: String,
    required: true,
  },
  navigationBarTitleText: {
    type: String,
    required: true,
  },
})
onMounted(() => {
  uni.setNavigationBarTitle({
    title: props.navigationBarTitleText,
  })
})
const token = uni.getStorageSync('token') // 从本地缓存中获取 token

const webviewUrl = computed(() => {
  const url = new URL(props.webviewSrc)
  if (token) {
    url.searchParams.set('token', token) // 在 URL 中添加 token 参数
  }
  return url.toString()
})

const isLoading = ref(true) // 控制加载动画显示状态

// 页面加载完成时，隐藏加载动画
function handleLoaded(e) {
  console.log('webview loaded', e)
  isLoading.value = false
}
// 监听消息事件，隐藏加载动画
window.addEventListener('message', (event) => {
  const data = event.data
  if (data.hello || data.wappalyzer)
    return
  console.log('message', data)

  if (data?.loaded) {
    console.log('loaded')
    isLoading.value = false
  }
  else if (data?.type === 'payment') {
    payment(data)
  }
})

function payment(data) {
  window.location.href = data.data
}
</script>

<template>
  <view v-if="isLoading" class="loading">
    <view class="spinner" />
    <view class="loading-text">
      加载中，请稍候...
    </view>
  </view>
  <web-view :src="webviewUrl" class="webview" @load="handleLoaded" />
</template>

<style scoped>
.loading {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  z-index: 10;
}
.spinner {
  width: 50px;
  height: 50px;
  border: 5px solid rgba(0, 106, 255, 0.2); /* 背景圆环颜色 */
  border-top-color: rgba(0, 106, 255, 0.8); /* 高亮部分颜色 */
  border-radius: 50%;
  animation: spin 1s linear infinite;
}
.loading-text {
  margin-top: 16px;
  font-size: 16px;
  font-weight: bold;
  background: linear-gradient(to right, #167ff6, #4a90e2);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-align: center;
}
@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.webview {
  width: 100%;
  height: 100%;
}
</style>
