<template>
  <web-view :src="url" />
</template>

<script setup>
import { ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { addArticleReadRecord } from "@/utils/api";
import useUser from "@/hooks/useUser";

const url = ref("");
const articleId = ref("");
const { logined, userInfo } = useUser();

onLoad((options) => {
  if (options.url) {
    url.value = decodeURIComponent(options.url);
  }
  if (options.id) {
    articleId.value = options.id;
  }
  if (options.title) {
    uni.setNavigationBarTitle({
      title: decodeURIComponent(options.title),
    });
  }

  // 阅读打点（不阻塞）
  recordArticleRead();
});

function getArticleVisitorId() {
  let visitorId = uni.getStorageSync("articleVisitorId");
  if (!visitorId) {
    visitorId = `mp_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 10)}`;
    uni.setStorageSync("articleVisitorId", visitorId);
  }
  return visitorId;
}

async function recordArticleRead() {
  try {
    if (!articleId.value) return;
    const accountId = logined.value && userInfo.value && userInfo.value.userId ? String(userInfo.value.userId) : "";
    await addArticleReadRecord(
      accountId
        ? { articleId: articleId.value, accountId }
        : { articleId: articleId.value, unionid: getArticleVisitorId() }
    );
  } catch (e) {
    console.warn("文章阅读打点失败", e);
  }
}
</script>
