<template>
  <view class="webview-container">
    <web-view :src="url" @message="onMessage"></web-view>
  </view>
</template>

<script setup>
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue";
import { set } from "@/utils/cache";
import { toast } from "@/utils/widget";
const url = ref("");
const purpose = ref("");

onLoad((options) => {
  if (options.url) {
    url.value = decodeURIComponent(options.url);
    console.log('url2', url.value);
  }
  purpose.value = options.purpose || "";
});

function onMessage(e) {
  // H5(公众号OAuth回调页) 可通过 wx.miniProgram.postMessage 传回 mpCode
  // 参考：wx.miniProgram.postMessage({ data: { mpCode: '<code>' } })
  const msg = e && e.detail && e.detail.data;
  const payload = Array.isArray(msg) ? msg[msg.length - 1] : msg;
  const mpCode = payload && payload.mpCode;
  if (!mpCode) return;
  console.log('mpCode', mpCode);
  set("mp-oauth-code", mpCode, 300); // 5分钟过期，供后续登录透传给后端映射
  toast("公众号授权成功");

  // 返回上一页（通常是登录页）
  setTimeout(() => {
    uni.navigateTo({ url: '/pages/login/login' });
  }, 300);
}
</script>

<style scoped>
.webview-container {
  width: 100%;
  height: 100vh;
}
</style>
