index.vue 11.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
<!--
 * @Date: 2022-09-19 14:11:06
 * @LastEditors: hookehuyr hookehuyr@gmail.com
 * @LastEditTime: 2025-09-28 14:08:23
 * @FilePath: /lls_program/src/pages/AdPage/index.vue
 * @Description: 广告页面
-->
<template>
  <view class="ad-page">
    <!-- 骨架屏 -->
    <view v-if="imageLoading" class="skeleton-container">
      <view class="skeleton-image">
        <view class="skeleton-shimmer"></view>
        <view class="skeleton-text">
          <view class="loading-title">
            {{ retryCount > 0 ? `正在重试加载 (${retryCount}/${maxRetries})` : '正在加载精彩内容' }}
          </view>
          <view class="loading-subtitle">请稍候...</view>
        </view>
      </view>
    </view>

    <!-- 手动刷新提示 -->
    <view v-if="showManualRefresh" class="manual-refresh-container">
      <view class="refresh-content">
        <view class="refresh-icon">⚠️</view>
        <view class="refresh-title">网络连接异常</view>
        <view class="refresh-subtitle">请检查网络连接后重新进入小程序</view>
        <view class="refresh-steps">
          <view class="step-item">1. 点击右上角 ⋯ 菜单</view>
          <view class="step-item">2. 选择重新进入小程序</view>
        </view>
      </view>
    </view>

    <!-- 背景图片 -->
    <image
      v-show="!imageLoading && !imageLoadError"
      :src="adImageUrl"
      class="ad-background"
      mode="scaleToFill"
      @tap="handleImageClick"
      @load="handleImageLoad"
      @error="handleImageError"
    />

    <!-- 图片加载失败提示 -->
    <view v-if="imageLoadError" class="error-container">
      <view class="error-text">图片加载失败</view>
      <view class="retry-button" @tap="retryLoadImage">重试</view>
    </view>

    <!-- 右上角分享按钮 -->
    <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 v-if="showNetworkErrorPopup" class="network-error-popup">
      <view class="popup-overlay" @tap="closeNetworkErrorPopup"></view>
      <view class="popup-content">
        <view class="popup-icon">⚠️</view>
        <view class="popup-title">网络不稳定</view>
        <view class="popup-message">
          当前网络连接不稳定,建议您:
        </view>
        <view class="popup-steps">
          <view class="step-item">1. 检查网络连接</view>
          <view class="step-item">2. 删除小程序后重新进入</view>
        </view>
        <view class="popup-buttons">
          <view class="popup-button cancel" @tap="closeNetworkErrorPopup">
            我知道了
          </view>
          <view class="popup-button confirm" @tap="deleteAndReenter">
            删除重进
          </view>
        </view>
      </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 defaultAdImage = 'https://cdn.ipadbiz.cn/space_34093/%E5%BC%95%E5%AF%BC%E9%A1%B51_Fu2ZY_Tm6TL1OzbyrqQkeVRAdVfU.jpg?imageMogr2/strip/quality/60';

// 定义响应式数据
const adImageUrl = ref(defaultAdImage); // 初始化为默认图片
const loading = ref(true);
const hasFamily = ref(false);
const imageLoading = ref(true); // 图片加载状态
const imageLoadError = ref(false); // 图片加载错误状态
const loadingTimeout = ref(null); // 加载超时定时器
const retryCount = ref(0); // 重试次数
const maxRetries = ref(3); // 最大重试次数
const isTimeout = ref(false); // 是否超时
const showManualRefresh = ref(false); // 是否显示手动刷新按钮
const showNetworkErrorPopup = ref(false); // 是否显示网络错误弹窗
const useFallbackImage = ref(false); // 是否使用降级图片

/**
 * 获取广告配置
 */
const fetchAdConfig = async () => {
  try {
    const { code, data } = await getBootPageAPI();
    if (code && data && data.adImageUrl) {
      adImageUrl.value = data.adImageUrl;
      useFallbackImage.value = false;
      return true;
    } else {
      throw new Error('广告配置数据无效');
    }
  } catch (error) {
    console.error('获取广告配置失败:', error);
    // 使用降级图片
    adImageUrl.value = defaultAdImage;
    useFallbackImage.value = true;
    throw error;
  }
};

/**
 * 关闭网络错误弹窗
 */
const closeNetworkErrorPopup = () => {
  showNetworkErrorPopup.value = false;
};

/**
 * 删除小程序并重新进入的提示
 */
const deleteAndReenter = () => {
  Taro.showModal({
    title: '操作提示',
    content: '请按以下步骤操作:\n1. 点击右上角"..."菜单\n2. 选择"删除"小程序\n3. 重新搜索进入小程序',
    showCancel: false,
    confirmText: '我知道了',
    success: () => {
      closeNetworkErrorPopup();
    }
  });
};

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

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

/**
 * 点击图片处理
 */
const handleImageClick = async () => {
  try {
    // 重新查询家庭状态
    const { code, data } = await getMyFamiliesAPI();
    const currentHasFamily = code && data && data?.families?.length > 0;
    
    if (currentHasFamily) {
      // 已加入家庭,跳转到dashboard页面
      Taro.redirectTo({
        url: '/pages/Dashboard/index'
      });
    } else {
      // 未加入家庭,跳转到welcome页面
      Taro.redirectTo({
        url: '/pages/Welcome/index'
      });
    }
  } catch (error) {
    console.error('查询家庭状态失败:', error);
    // 查询失败时,使用之前的状态进行跳转
    if (hasFamily.value) {
      // 已加入家庭,跳转到dashboard页面
      Taro.redirectTo({
        url: '/pages/Dashboard/index'
      });
    } else {
      // 未加入家庭,跳转到welcome页面
      Taro.redirectTo({
        url: '/pages/Welcome/index'
      });
    }
  }
};

/**
 * 图片加载完成处理
 */
const handleImageLoad = () => {
  console.log('图片加载成功');
  clearLoadingTimeout();
  imageLoading.value = false;
  imageLoadError.value = false;
  isTimeout.value = false;
  showManualRefresh.value = false;
  loading.value = false;
  retryCount.value = 0;
};

/**
 * 图片加载失败处理
 */
const handleImageError = () => {
  console.log('图片加载失败');
  clearLoadingTimeout();
  imageLoading.value = false;
  imageLoadError.value = true;
  // 不要在这里直接调用handleLoadingTimeout,让重试逻辑统一处理
  setTimeout(() => {
    handleLoadingTimeout();
  }, 100);
};

/**
 * 重试加载图片
 */
const retryLoadImage = async () => {
  // 重置状态
  imageLoading.value = true;
  imageLoadError.value = false;
  isTimeout.value = false;
  showManualRefresh.value = false;
  loading.value = true;

  try {
    // 开始超时检测
    startLoadingTimeout();

    // 重新获取广告配置
    await fetchAdConfig();

    // 广告配置成功后,清除超时定时器
    clearLoadingTimeout();
    imageLoading.value = false;

  } catch (error) {
    console.error('重试获取广告配置失败:', error);
    // 重试失败时触发超时处理
    handleLoadingTimeout();
  } finally {
    loading.value = false;
  }
};

/**
 * 开始加载超时检测
 */
const startLoadingTimeout = () => {
  // 清除之前的定时器
  clearLoadingTimeout();

  // 设置10秒超时
  loadingTimeout.value = setTimeout(() => {
    if (imageLoading.value || loading.value) {
      console.warn('图片加载超时');
      isTimeout.value = true;
      handleLoadingTimeout();
    }
  }, 10000);
};

/**
 * 处理加载超时
 */
const handleLoadingTimeout = () => {
  // 清除超时定时器
  clearLoadingTimeout();

  if (retryCount.value < maxRetries.value) {
    // 自动重试
    retryCount.value++;
    console.log(`第${retryCount.value}次自动重试加载`);

    // 延迟1秒后重试,避免频繁请求
    setTimeout(() => {
      retryLoadImage();
    }, 1000);
  } else {
    // 超过最大重试次数
    imageLoading.value = false;
    loading.value = false;

    // 如果使用的是降级图片,显示网络错误弹窗
    if (useFallbackImage.value) {
      showNetworkErrorPopup.value = true;
      console.log('使用降级图片,显示网络错误提示');
    } else {
      // 否则显示手动刷新选项
      showManualRefresh.value = true;
      console.error('图片加载失败,已达到最大重试次数');
    }
  }
};

/**
 * 清除加载超时定时器
 */
const clearLoadingTimeout = () => {
  if (loadingTimeout.value) {
    clearTimeout(loadingTimeout.value);
    loadingTimeout.value = null;
  }
};

/**
 * 页面初始化逻辑
 */
const initializePage = async () => {
  try {
    // 重置重试计数
    retryCount.value = 0;

    // 开始超时检测
    startLoadingTimeout();

    // 执行静默授权
    await performSilentAuth();

    // 先获取广告配置
    let adConfigSuccess = false;
    try {
      await fetchAdConfig();
      adConfigSuccess = true;
    } catch (adError) {
      console.error('获取广告配置失败,使用降级图片:', adError);
      adConfigSuccess = false; // 使用降级图片也算是一种"成功"
    }

    // 无论广告配置是否成功,都要检查家庭状态
    try {
      await checkUserFamily();

      // 如果广告配置失败了(使用降级图片),再次尝试获取广告配置
      if (!adConfigSuccess) {
        try {
          await fetchAdConfig();
          adConfigSuccess = true;
          console.log('重试获取广告配置成功');
        } catch (retryError) {
          console.error('重试获取广告配置仍然失败,继续使用降级图片:', retryError);
        }
      }

      // 清除超时定时器并设置成功状态
      clearLoadingTimeout();
      imageLoading.value = false;
      imageLoadError.value = false;

      // 如果最终还是使用降级图片,显示网络错误提示
      if (useFallbackImage.value) {
        setTimeout(() => {
          showNetworkErrorPopup.value = true;
        }, 1000); // 延迟1秒显示,让用户先看到页面
      }

    } catch (familyError) {
      console.error('检查家庭状态失败:', familyError);
      // 家庭状态检查失败,但仍然尝试显示广告
      clearLoadingTimeout();
      imageLoading.value = false;

      // 如果使用降级图片,显示网络错误提示
      if (useFallbackImage.value) {
        setTimeout(() => {
          showNetworkErrorPopup.value = true;
        }, 1000);
      }
    }
  } catch (error) {
    console.error('页面初始化失败:', error);
    // 初始化失败时处理超时
    handleLoadingTimeout();
  } finally {
    loading.value = false;
  }
};

/**
 * 页面初始化
 */
onMounted(() => {
  initializePage();
});

/**
 * 定义分享给朋友的内容
 * @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>