<template>
  <view>
    <!-- <s-layout title="试衣间" navbar="custom" tabbar="" :bgStyle="{ color: '#fff' }"> -->
    <web-view :src="webviewUrl" ref="webviewRef" @message="handleMessage">
      <cover-view-tabbar activeUrl="/pages/index/room" />
    </web-view>
    <!-- </s-layout> -->
  </view>
</template>

<script setup>
  import { computed, ref } from 'vue';
  import { onLoad, onUnload, onPageScroll, onPullDownRefresh, onShow } 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 tokenCheckTimer = ref(null);
  const token = ref('');
  const webviewRef = ref();
  const webviewUrl = ref('');

  onShow(async () => {
    if (!sheep.$store('user').isLogin) {
      uni.redirectTo({ url: '/pages/login/index' });
    }
    const tryOnId = uni.getStorageSync('tryOnId');
    const modelId = uni.getStorageSync('modelId');
    if (tryOnId && modelId) {
      webviewUrl.value = `https://fitting-room.huimeimeta.com/pages/fittingRoom/index?token=${getAccessToken()}&t=${Date.now()}&id=${tryOnId}&modelId=${modelId}`;
      uni.setStorageSync('tryOnId', '');
      uni.setStorageSync('modelId', '');
    } else {
      webviewUrl.value = `https://fitting-room.huimeimeta.com/pages/fittingRoom/index?token=${getAccessToken()}&t=${Date.now()}`;
    }
  });

  onLoad(() => {
    token.value = getAccessToken();
    startTokenListener();
  });

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

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

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

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

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

  function handleMessage(e) {
    console.log('收到H5消息:', e.detail.data);
  }
</script>

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