index.vue 2.98 KB
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-09-19 20:19:12
 * @FilePath: /lls_program/src/pages/AdPage/index.vue
 * @Description: 广告页面
-->
<template>
  <view class="ad-page">
    <!-- 背景图片 -->
    <image
      :src="adImageUrl"
      class="ad-background"
      mode="scaleToFill"
      @tap="handleImageClick"
    />

    <!-- 右上角分享按钮 -->
    <view class="share-button-container" @tap.stop>
      <button
        class="share-button"
        open-type="share"
      >
        推荐给朋友
      </button>
    </view>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-container">
      <view class="loading-text">加载中...</view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from "vue";
import Taro from "@tarojs/taro";
import { getBootPageAPI } from "@/api";
import { getMyFamiliesAPI } from "@/api/family";
import { silentAuth } from "@/utils/authRedirect";
import "./index.less";

// 定义响应式数据
const adImageUrl = ref('');
const loading = ref(true);
const hasFamily = ref(false);

/**
 * 获取广告配置
 */
const fetchAdConfig = async () => {
  try {
    const { code, data } = await getBootPageAPI();
    if (code && data) {
      adImageUrl.value = data.adImageUrl;
    }
  } catch (error) {
    console.error('获取广告配置失败:', error);
  }
};

/**
 * 检查用户是否加入家庭
 */
const checkUserFamily = async () => {
  try {
    const { code, data } = await getMyFamiliesAPI();
    hasFamily.value = code && data && data.length > 0;
  } catch (error) {
    console.error('检查用户家庭状态失败:', error);
    hasFamily.value = false;
  }
};

/**
 * 静默授权
 */
const performSilentAuth = async () => {
  try {
    await silentAuth();
  } catch (error) {
    console.error('静默授权失败:', error);
  }
};

/**
 * 点击图片处理
 */
const handleImageClick = () => {
  if (hasFamily.value) {
    // 已加入家庭,跳转到dashboard页面
    Taro.redirectTo({
      url: '/pages/Dashboard/index'
    });
  } else {
    // 未加入家庭,跳转到welcome页面
    Taro.redirectTo({
      url: '/pages/Welcome/index'
    });
  }
};

/**
 * 页面初始化
 */
onMounted(async () => {
  try {
    // 执行静默授权
    await performSilentAuth();

    // 并行获取广告配置和检查家庭状态
    await Promise.all([
      fetchAdConfig(),
      checkUserFamily()
    ]);
  } catch (error) {
    console.error('页面初始化失败:', error);
  } finally {
    loading.value = false;
  }
});

/**
 * 定义分享给朋友的内容
 * @returns {Object} 分享配置对象
 */
const onShareAppMessage = (res) => {
    const shareData = {
        title: '和家人一起走路、一起打卡、一起兑换',
        path: `/pages/AdPage/index`,
        imageUrl: ''
    };

    return shareData;
}

// 使用Taro的useShareAppMessage Hook来处理分享
Taro.useShareAppMessage((res) => {
    return onShareAppMessage(res);
});
</script>