<template>
  <view></view>
</template>

<script setup>
import { onMounted, onUnmounted } from "vue";
import { watchAdStart } from "@/api/system.js";

const props = defineProps({
  adUnitId: {
    type: String,
    default: "adunit-d7a28e0357d98947",
  },
});

const emit = defineEmits(["onReward", "onError", "onClose"]);

let videoAd = null;
let rewardToken = "";

const onLoadHandler = () => {
  console.log("Ad Loaded");
};

const onErrorHandler = (err) => {
  console.error("Ad Load Error", err);
  emit("onError", err);
};

const onCloseHandler = (res) => {
  if (res && res.isEnded) {
    emit("onReward", rewardToken);
  } else {
    uni.showToast({ title: "观看完整广告才能获取奖励哦", icon: "none" });
    emit("onClose");
  }
};

onMounted(() => {
  if (uni.createRewardedVideoAd) {
    videoAd = uni.createRewardedVideoAd({
      adUnitId: props.adUnitId,
    });

    videoAd.onLoad(onLoadHandler);
    videoAd.onError(onErrorHandler);
    videoAd.onClose(onCloseHandler);
  }
});

onUnmounted(() => {
  if (videoAd) {
    videoAd.offLoad(onLoadHandler);
    videoAd.offError(onErrorHandler);
    videoAd.offClose(onCloseHandler);
  }
});

const show = async () => {
  try {
    // Step 1: Start Ad Session to get Token
    const res = await watchAdStart();
    if (res && res.rewardToken) {
      rewardToken = res.rewardToken;

      // Step 2: Show Ad
      if (videoAd) {
        videoAd.show().catch(() => {
          videoAd
            .load()
            .then(() => videoAd.show())
            .catch((err) => {
              console.error("Ad show failed", err);
              uni.showToast({
                title: "广告加载失败，请稍后再试",
                icon: "none",
              });
              emit("onError", err);
            });
        });
      } else {
        uni.showToast({ title: "当前环境不支持广告", icon: "none" });
      }
    } else {
      uni.showToast({ title: "广告启动失败，请稍后再试", icon: "none" });
    }
  } catch (e) {
    console.error("watchAdStart failed", e);
    uni.showToast({ title: "广告启动失败，请稍后再试", icon: "none" });
  }
};

defineExpose({ show });
</script>
