<template>
  <view>
    <!-- <s-layout title="首页" navbar="custom" tabbar="" :bgStyle="{ color: '#fff' }"> -->
    <web-view :src="url">
      <cover-view-tabbar activeUrl="/pages/index/index" />
    </web-view>
    <!-- </s-layout> -->
  </view>
</template>

<script setup>
  import { computed, ref } from 'vue';
  import { onLoad, onUnload, onShow, onPageScroll, onPullDownRefresh } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import $share from '@/sheep/platform/share';
  import CoverViewTabbar from '@/pages/index/components/cover-view-tabbar.vue';
  import { getAccessToken } from '@/sheep/request';

  // 隐藏原生tabBar
  uni.hideTabBar({
    fail: () => {},
  });

  const tabbar = computed(() => {
    return sheep.$store('app').template.basic?.tabbar;
  });

  const template = computed(() => sheep.$store('app').template?.home);

  const tokenCheckTimer = ref(null);
  const token = ref('');

  const url = ref(
    `https://fitting-room.huimeimeta.com/pages/index/custom?token=${getAccessToken()}&t=${Date.now()}`,
  );

  const isLogin = computed(() => sheep.$store('user').isLogin);

  onShow(() => {
    if (!isLogin.value) {
      uni.redirectTo({ url: '/pages/login/index' });
    }
  });

  onLoad((options) => {
    // #ifdef MP
    // 小程序识别二维码
    if (options.scene) {
      const sceneParams = decodeURIComponent(options.scene).split('=');
      console.log('sceneParams=>', sceneParams);
      options[sceneParams[0]] = sceneParams[1];
    }
    // #endif

    // 预览模板
    if (options.templateId) {
      sheep.$store('app').init(options.templateId);
    }

    // 解析分享信息
    if (options.spm) {
      $share.decryptSpm(options.spm);
    }

    // 进入指定页面(完整页面路径)
    if (options.page) {
      sheep.$router.go(decodeURIComponent(options.page));
    }

    token.value = getAccessToken();
    startTokenListener();
  });

  onUnload(() => {
    stopTokenListener();
  });

  function checkTokenUpdate() {
    const currentToken = getAccessToken() || '';

    if (currentToken !== token.value) {
      console.log('检测到token变化，更新H5页面');
      token.value = currentToken;
      url.value = `https://fitting-room.huimeimeta.com/pages/index/custom?token=${currentToken}&t=${Date.now()}`;
    }
  }

  function stopTokenListener() {
    if (tokenCheckTimer.value) {
      clearInterval(tokenCheckTimer.value);
      tokenCheckTimer.value = null;
    }
  }

  function startTokenListener() {
    tokenCheckTimer.value = setInterval(() => {
      checkTokenUpdate();
    }, 1000);
  }
</script>

<style lang="scss" scoped></style>
