<!-- src/views/Ranking/KingAndQueen/TopList.vue -->
<template>
  <div class="fullPage">
    <div class="bg" :style="{ '--bg-url': `url(${imageUrl('bg')})` }">
      <!-- 状态栏占位区域（仅在APP中显示） -->
      <div v-if="isInAppEnvironment" style="height: 30px"></div>

      <!-- 帮助按钮 -->
      <img
        v-smart-img
        :src="imageUrl('help')"
        alt=""
        style="width: 10%; position: absolute; top: 48px; right: 8px; z-index: 4"
        @click="helpInfoShow = true"
      />

      <!-- history按钮 -->
      <img
        v-smart-img
        :src="imageUrl('history')"
        alt=""
        style="width: 20%; margin-top: 20px"
        @click="historyShow = true"
      />

      <!-- 每周榜首 -->
      <div style="display: flex; flex-direction: column; align-items: center">
        <!-- 主标题 -->
        <img v-smart-img :src="imageUrl('listTitle')" alt="" style="width: 90%" />
        <!-- 榜首 -->
        <div style="width: 100%; display: flex; justify-content: space-around; margin-top: 16px">
          <div
            style="width: 40%"
            v-for="(topUser, index) in listTop"
            :key="index"
            @click="viewUserInfo(topUser.userInfo.userId)"
          >
            <div
              style="
                position: relative;
                width: 100%;
                min-height: max-content;
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <!-- 头像框 -->
              <img v-smart-img :src="topUser.Frame" alt="" style="width: 100%; z-index: 1" />
              <!-- 头像 -->
              <div
                style="
                  position: absolute;
                  left: 0;
                  right: 0;
                  top: 0;
                  bottom: 0;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  z-index: 0;
                "
              >
                <img
                  v-smart-img
                  v-if="topUser.userInfo.userAvatar"
                  :src="topUser.userInfo.userAvatar || ''"
                  alt=""
                  width="70%"
                  style="border-radius: 50%; aspect-ratio: 1/1; object-fit: cover"
                  @click="viewUserInfo(topUser.userInfo.userId)"
                />
              </div>
              <div
                style="
                  height: 10%;
                  width: 50%;
                  position: absolute;
                  z-index: 2;
                  display: flex;
                  justify-content: center;
                  align-items: center;
                "
                :style="{ bottom: topUser.type == 'topKing' ? '9.3%' : '7%' }"
              >
                <div
                  style="
                    color: #fff;
                    font-weight: 860;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  "
                  class="topName"
                >
                  {{ topUser.userInfo.userNickname }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 刷新倒计时 -->
      <div style="display: flex; justify-content: center; margin-top: 20px">
        <!-- 天数 -->
        <itemCenter :imgUrl="imageUrl('dayBg')" style="width: 10%; margin-right: 10px">
          <div class="time">{{ Days }}D</div>
        </itemCenter>

        <!-- 当天时间倒计时 -->
        <itemCenter :imgUrl="imageUrl('timeBg')" style="width: 23.75%">
          <div class="time">{{ Hours }} : {{ Minutes }} : {{ Second }}</div>
        </itemCenter>
      </div>

      <!-- rewards -->
      <div style="display: flex; justify-content: flex-end; margin-top: -8%">
        <img
          v-smart-img
          :src="imageUrl('rewards')"
          alt=""
          style="width: 20%"
          @click="rewardsShow = true"
        />
      </div>

      <!-- 每周礼物 -->
      <div style="display: flex; justify-content: center">
        <itemCenter :imgUrl="imageUrl('eventGifts')">
          <div style="width: 80%; display: flex; justify-content: space-around; margin-top: 10%">
            <div
              v-for="(gift, index) in gifts"
              :key="index"
              style="width: 30%; display: flex; flex-direction: column"
            >
              <itemCenter :imgUrl="imageUrl('gift')">
                <img v-smart-img :src="gift.giftPhoto" alt="" width="50%" />
              </itemCenter>
              <div style="display: flex; justify-content: center; align-items: center; gap: 5px">
                <img
                  v-smart-img
                  src="/src/assets/icon/coin.png"
                  alt=""
                  style="width: 18%; aspect-ratio: 1/1"
                />
                <div style="color: rgba(255, 255, 255, 1); font-weight: 590">
                  {{ gift.giftCandy }}
                </div>
              </div>
            </div>
          </div>
        </itemCenter>
      </div>

      <!-- 排行榜模块 -->
      <div style="width: 100vw">
        <!-- 排行榜切换按钮 -->
        <div style="width: 100%">
          <div
            v-show="visibleKingList"
            style="width: 100%; display: flex; justify-content: space-around"
          >
            <img v-smart-img :src="imageUrl('kingBtActive')" alt="" style="width: 40%" />
            <img
              v-smart-img
              :src="imageUrl('queenBt')"
              alt=""
              style="width: 40%"
              @click="visibleKingList = false"
            />
          </div>

          <div
            v-show="!visibleKingList"
            style="width: 100%; display: flex; justify-content: space-around"
          >
            <img
              v-smart-img
              :src="imageUrl('kingBt')"
              alt=""
              style="width: 40%"
              @click="visibleKingList = true"
            />
            <img v-smart-img :src="imageUrl('queenBtActive')" alt="" style="width: 40%" />
          </div>
        </div>

        <!-- 排行榜 -->
        <div style="width: 100%">
          <borderImg title="Ranking">
            <itemCenter
              :imgUrl="imageUrl('border-item-user')"
              style="margin: -2px 0"
              :contentStyle="`justify-content: flex-start;padding: 0 15%;gap: 4px;`"
              v-for="(listItem, index) in topList"
              :key="index"
              @click="viewUserInfo(listItem.userId)"
            >
              <!-- 基本信息 -->
              <div
                style="
                  width: 75%;
                  min-width: 0;
                  display: flex;
                  justify-content: space-around;
                  align-items: center;
                  gap: 4px;
                "
              >
                <!-- 排名 -->
                <div
                  style="width: 15%; display: flex; justify-content: center; align-items: center"
                >
                  <div style="color: #edb247; font-weight: 700">{{ listItem.rank }}</div>
                </div>

                <!-- 头像 -->
                <div
                  style="
                    width: 24%;
                    aspect-ratio: 1/1;
                    border-radius: 50%;
                    background: linear-gradient(
                      to bottom,
                      rgba(255, 224, 60, 1),
                      rgba(255, 189, 19, 1)
                    );

                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  <img
                    v-smart-img
                    :src="listItem.userAvatar || ''"
                    alt=""
                    style="
                      display: block;
                      width: 90%;
                      aspect-ratio: 1/1;
                      border-radius: 50%;
                      object-fit: cover;
                    "
                    @error="handleAvatarImageError"
                  />
                </div>

                <!-- 名称 -->
                <div
                  style="
                    min-width: 0;
                    width: calc(100% - 15% - 24% - 8px);
                    display: flex;
                    flex-direction: column;
                  "
                >
                  <div
                    style="
                      width: 100%;
                      color: #fff;
                      font-weight: 860;
                      overflow: hidden;
                      white-space: nowrap;
                      text-overflow: ellipsis;
                    "
                    class="topUserNickname"
                  >
                    {{ listItem.userNickname }}
                  </div>
                  <div style="color: #fff; font-weight: 590" class="topUserNickname">
                    ID:{{ listItem.account }}
                  </div>
                </div>
              </div>

              <!-- 贡献值 -->
              <div style="flex: 1; min-width: 0; display: flex; align-items: center">
                <img
                  v-smart-img
                  src="/src/assets/icon/coin.png"
                  alt=""
                  style="display: block; width: 30%; aspect-ratio: 1/1"
                />
                <div style="color: #edb247; font-weight: 700" class="topUserNickname">
                  {{ listItem.quantity }}
                </div>
              </div>
            </itemCenter>
            <!-- 触发加载功能 -->
            <div ref="kingListLoadmore" v-show="showKingLoading && visibleKingList"></div>
            <!-- 触发加载功能 -->
            <div ref="queenListloadmore" v-show="showQueenLoading && !visibleKingList"></div>
          </borderImg>
        </div>
      </div>
    </div>

    <!-- 弹窗遮罩层 -->
    <maskLayer :maskLayerShow="maskLayerShow" @click="closedPopup">
      <!-- help弹窗 -->
      <div v-show="helpInfoShow" style="margin: 20% 0" @click.stop>
        <img v-smart-img :src="imageUrl('helpInfo')" alt="" style="width: 100%" />
      </div>

      <!-- history弹窗 -->
      <div v-show="historyShow" style="margin: 20% 0" @click.stop>
        <div style="width: 100%">
          <borderImg title="History">
            <div
              style="
                background-size: 100% 100%;
                min-height: 20px;
                margin: -10px 0;
                padding: 10px 10%;
              "
              :style="{ backgroundImage: `url(${imageUrl('border-item')})` }"
            >
              <!-- 内容 -->
              <div
                style="width: 100%; display: flex; justify-content: space-around; margin-top: 16px"
              >
                <div
                  style="width: 40%"
                  v-for="(topOne, topIndex) in showTopOne.top"
                  :key="topIndex"
                >
                  <div
                    style="
                      position: relative;
                      width: 100%;
                      min-height: max-content;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                    "
                  >
                    <!-- 头像框 -->
                    <img v-smart-img :src="topOne.Frame" alt="" style="width: 100%; z-index: 1" />
                    <!-- 头像 -->
                    <div
                      style="
                        position: absolute;
                        left: 0;
                        right: 0;
                        top: 0;
                        bottom: 0;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        z-index: 0;
                      "
                    >
                      <img
                        v-smart-img
                        :src="topOne.userInfo.userAvatar"
                        alt=""
                        width="70%"
                        style="border-radius: 50%; aspect-ratio: 1/1; object-fit: cover"
                      />
                    </div>
                    <div
                      style="
                        height: 10%;
                        width: 50%;
                        color: #fff;
                        position: absolute;
                        z-index: 2;

                        font-weight: 860;
                        font-size: 12px;

                        display: flex;
                        justify-content: center;
                        align-items: center;
                      "
                      :style="{ bottom: topOne.type == 'topKing' ? '9.3%' : '7%' }"
                    >
                      <div
                        style="
                          color: #fff;
                          font-weight: 860;
                          overflow: hidden;
                          white-space: nowrap;
                          text-overflow: ellipsis;
                        "
                        class="topName"
                      >
                        {{ topOne.userInfo.userNickname }}
                      </div>
                    </div>
                  </div>
                  <div style="color: #fff; font-weight: 590; text-align: center">
                    ID:{{ topOne.userInfo.account }}
                  </div>
                </div>
              </div>
              <div
                style="
                  display: flex;
                  justify-content: center;
                  align-items: center;
                  margin-top: 20px;
                "
              >
                <img
                  v-smart-img
                  :src="imageUrl('timeBack')"
                  alt=""
                  width="18px"
                  height="18px"
                  @click="changeHistoryIndex(1)"
                />
                <div
                  style="
                    width: 40%;
                    text-align: center;
                    font-size: 14px;
                    font-weight: 590;
                    background-image: -webkit-linear-gradient(
                      top,
                      rgba(243, 183, 0, 1),
                      rgba(255, 238, 198, 1)
                    );
                    background-clip: text;
                    -webkit-background-clip: text;
                    -webkit-text-fill-color: transparent;
                  "
                >
                  {{ showTopOne.group }}
                </div>
                <img
                  v-smart-img
                  :src="imageUrl('timeNext')"
                  alt=""
                  width="18px"
                  height="18px"
                  @click="changeHistoryIndex(-1)"
                />
              </div>
            </div>
          </borderImg>
        </div>
      </div>

      <!-- rewards弹窗 -->
      <div v-show="rewardsShow" style="padding: 20% 0" @click.stop>
        <div style="position: relative">
          <!-- 取消按钮 -->
          <img
            v-smart-img
            :src="imageUrl('cancel')"
            alt=""
            style="width: 7%; position: absolute; top: 0; right: 6%; z-index: 99"
            @click="closedPopup"
          />
          <div style="width: 100%">
            <borderImg title="Rewards">
              <div
                style="
                  background-size: 100% 100%;
                  min-height: 20px;
                  margin: -20px 0;
                  padding: 20px 10%;
                "
                :style="{ backgroundImage: `url(${imageUrl('border-item')})` }"
              >
                <!-- 奖励榜切换按钮 -->
                <div style="width: 100%">
                  <div
                    v-show="visibleKingRewards"
                    style="width: 100%; display: flex; justify-content: space-around"
                  >
                    <img v-smart-img :src="imageUrl('kingBtActive')" alt="" style="width: 40%" />
                    <img
                      v-smart-img
                      :src="imageUrl('queenBt')"
                      alt=""
                      style="width: 40%"
                      @click="visibleKingRewards = false"
                    />
                  </div>
                  <div
                    v-show="!visibleKingRewards"
                    style="width: 100%; display: flex; justify-content: space-around"
                  >
                    <img
                      v-smart-img
                      :src="imageUrl('kingBt')"
                      alt=""
                      style="width: 40%"
                      @click="visibleKingRewards = true"
                    />
                    <img v-smart-img :src="imageUrl('queenBtActive')" alt="" style="width: 40%" />
                  </div>
                </div>

                <!-- 奖励榜 -->
                <div v-for="(rewardsTop, top) in rewardsList" :key="top">
                  <div
                    style="display: flex; flex-direction: column; align-items: center"
                    v-if="rewardsTop.rewards.length > 0"
                  >
                    <img
                      v-smart-img
                      :src="topImg[Number(rewardsTop.rankRange) - 1]"
                      alt=""
                      style="width: 40%; margin: 24px 0"
                    />
                    <div
                      style="
                        width: 100%;
                        display: grid;
                        grid-template-columns: repeat(3, 1fr);
                        gap: 3%;
                        margin-bottom: 3%;
                      "
                    >
                      <div
                        v-for="(reward, rewardIndex) in rewardsTop.rewards"
                        :key="rewardIndex"
                        style="width: 100%"
                      >
                        <itemCenter :imgUrl="imageUrl('gift')">
                          <img
                            v-smart-img
                            :src="reward.cover || ''"
                            alt=""
                            width="50%"
                            style="aspect-ratio: 1/1"
                            @error="(e) => handleRewardImageError(e, reward.type)"
                          />
                        </itemCenter>

                        <div
                          style="
                            color: rgba(255, 255, 255, 1);
                            font-weight: 590;
                            text-align: center;
                          "
                        >
                          {{ showDetail(reward.type, reward) }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </borderImg>
          </div>
        </div>
      </div>
    </maskLayer>

    <!-- 我的排名占位 -->
    <div style="height: 25vw"></div>

    <!-- 我的排名 -->
    <div
      style="
        position: fixed;
        bottom: 0;
        width: 100vw;
        background-color: rgba(77, 30, 22, 1);
        display: flex;
        justify-content: center;
        margin-top: 10px;
      "
    >
      <img
        v-smart-img
        :src="imageUrl('myRankingBg')"
        alt=""
        style="width: calc(100% - 1px); display: block"
      />

      <div
        style="
          position: absolute;
          inset: 0;
          display: flex;
          align-items: center;
          justify-content: space-around;
          padding: 2% 2% 0;
          gap: 4px;
        "
      >
        <!-- 基本信息 -->
        <div
          style="
            width: 75%;
            min-width: 0;
            display: flex;
            justify-content: space-around;
            align-items: center;
            gap: 4px;
          "
        >
          <!-- 排名 -->
          <div style="width: 15%; display: flex; justify-content: center; align-items: center">
            <div style="color: #edb247; font-weight: 700">
              {{ (myRanking.userSex == 1 ? myRanking.wealthRank : myRanking.charmRank) || 999 }}
            </div>
          </div>
          <!-- 头像 -->
          <div
            style="
              width: 25%;
              aspect-ratio: 1/1;
              border-radius: 50%;
              background: linear-gradient(to bottom, rgba(255, 224, 60, 1), rgba(255, 189, 19, 1));

              display: flex;
              justify-content: center;
              align-items: center;
            "
          >
            <img
              v-smart-img
              :src="myRanking.userAvatar || ''"
              alt=""
              style="
                display: block;
                width: 90%;
                aspect-ratio: 1/1;
                border-radius: 50%;
                object-fit: cover;
              "
              @error="handleAvatarImageError"
            />
          </div>

          <!-- 名称 -->
          <div
            style="
              min-width: 0;
              width: calc(100% - 15% - 25% - 8px);
              display: flex;
              flex-direction: column;
            "
          >
            <div
              style="
                color: #fff;
                font-weight: 860;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
              "
            >
              {{ myRanking.userNickname }}
            </div>
          </div>
        </div>

        <div style="flex: 1; min-width: 0; display: flex; align-items: center; gap: 2px">
          <img
            v-smart-img
            src="/src/assets/icon/coin.png"
            alt=""
            style="display: block; width: 35%; aspect-ratio: 1/1"
          />
          <!-- 1:男,0:女 -->
          <div v-if="myRanking.userSex == 1" style="color: #edb247; font-weight: 700">
            {{ myRanking.wealthQuantity }}
          </div>
          <div v-else style="color: #edb247; font-weight: 700">
            {{ myRanking.charmQuantity }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { isInApp, viewUserInfo } from '@/utils/appBridge.js'
import { useThrottle } from '@/utils/useDebounce'
import { connectToApp } from '@/utils/appConnector.js'
import { getPngUrl } from '@/config/imagePaths.js'
import { preloadImages } from '@/utils/imagePreloader.js'
import { handleAvatarImageError, handleRewardImageError } from '@/utils/imageHandler.js'

import {
  getWeekTopList,
  getWeekMyContribution,
  getThisWeekRewardsAndGifts,
  getHistoryTopOne,
} from '@/api/topList.js'
import { getMemberProfile } from '@/api/wallet'

import borderImg from './components/borderImg.vue'
import itemCenter from '@/components/itemCenter.vue'
import maskLayer from '@/components/MaskLayer.vue'

// 获取OSS图片URL的函数
const imageUrl = (filename) => getPngUrl('Ranking/KingQueen/', filename)

// 使用工具函数连接APP
const connectToAppHandler = async () => {
  await connectToApp(() => {
    // 连接成功回调
    getUserInfo()
    updatePageData() // 刷新页面数据
    preloadCriticalImages() // 预加载关键图片
  })
}

const userInfo = ref({})

const visibleKingList = ref(true)

const isInAppEnvironment = ref(false) // 检测是否在APP环境中

const historyList = ref([]) // 榜首历史记录
const showTopOne = computed(() => {
  let topNew = []
  if (historyList.value[historyIndex.value]?.wealth)
    topNew.push({
      type: 'topKing',
      Frame: imageUrl('kingFrame'),
      userInfo: historyList.value[historyIndex.value].wealth || {},
    })
  if (historyList.value[historyIndex.value]?.charm) {
    topNew.push({
      type: 'topQueen',
      Frame: imageUrl('queenFrame'),
      userInfo: historyList.value[historyIndex.value].charm || {},
    })
  }
  return {
    group: historyList.value[historyIndex.value]?.group,
    top: topNew,
  }
})
const historyIndex = ref(0)

const changeHistoryIndex = (num) => {
  let index = historyIndex.value + num
  let length = historyList.value.length
  console.log('index:', index)
  console.log('length:', length)

  if (index >= 0 && index < length) {
    historyIndex.value = index
  }
}

const myRanking = ref({}) // 我的排名
const kingListCurrent = ref(1) //国王榜第几页
const kingListParams = computed(() => ({
  type: 'THIS_WEEK',
  kingQueenType: 'WEALTH',
  current: kingListCurrent.value,
  size: 10,
}))
const kingList = ref([]) // 国王榜
const queenListCurrent = ref(1) //女王榜第几页
const queenListParams = computed(() => ({
  type: 'THIS_WEEK',
  kingQueenType: 'CHARM',
  current: queenListCurrent.value,
  size: 10,
}))
const queenList = ref([]) // 女王榜
const listTop = ref([
  {
    type: 'topKing',
    Frame: imageUrl('kingFrame'),
    userInfo: {},
  },
  {
    type: 'topQueen',
    Frame: imageUrl('queenFrame'),
    userInfo: {},
  },
]) //本周的top1国王和女王

// 展示用排行榜
const topList = computed(() => {
  return visibleKingList.value ? kingList.value : queenList.value
})

const showKingLoading = ref(true) //触底加载功能
const showQueenLoading = ref(true) //触底加载功能

const topImg = ref([imageUrl('top1'), imageUrl('top2'), imageUrl('top3')]) // top图片

const visibleKingRewards = ref(true) // 展示奖励榜标签
const kingRewards = ref([]) //国王奖励列表
const queenRewards = ref([]) //女王奖励列表
const rewardsList = computed(() => {
  return visibleKingRewards.value ? kingRewards.value : queenRewards.value
}) //展示奖励列表

const maskLayerShow = computed(() => {
  return helpInfoShow.value || historyShow.value || rewardsShow.value
})
const helpInfoShow = ref(false)
const historyShow = ref(false)
const rewardsShow = ref(false)

// 获取底部加载div
const kingListLoadmore = ref(null)
const queenListloadmore = ref(null)

const debouceGetKingList = useThrottle(() => {
  getTopList(kingListParams.value)
}, 1000)
const debouceGetQueenList = useThrottle(() => {
  getTopList(queenListParams.value)
}, 1000)

const gifts = ref([])

// 倒计时
const Days = ref(0)
const Hours = ref(0)
const Minutes = ref(0)
const Second = ref(0)
let timer = null

// 获取沙特下周一早上六点的时间戳
const getNextMondayInSaudi = () => {
  const now = new Date()
  const utcDay = now.getUTCDay() //获取UTC星期几，0(周日)-6(周六)

  // 计算到下周一的所需天数
  const daysToAdd = utcDay === 1 ? 7 : (1 + 7 - utcDay) % 7
  const nextMondayUTC = new Date(now) //以当前UTC时间为基准，而不是重新获取

  nextMondayUTC.setUTCDate(now.getUTCDate() + daysToAdd) //增加到下周一那天
  nextMondayUTC.setUTCHours(3, 0, 0, 0) // 设置为沙特下周一当天早上6点（北京时间3点）
  return nextMondayUTC.getTime() //得到下周一00:00:00.000的时间戳
}

// 时间格式化为2位
const formatTime = (value) => {
  return value < 10 ? `0${value}` : value
}

const targetTime = ref(getNextMondayInSaudi()) // 闭包保存目标时间 (核心修正)

// 更新倒计时
const getCountdown = () => {
  const now = Date.now()
  let diff = targetTime.value - now

  if (diff <= 0) {
    getUserInfo()
    updatePageData() // 刷新页面数据
    targetTime.value += 7 * 86400000 // +7天 (更新闭包变量)
    diff = targetTime.value - now
  }

  // 计算时间单位
  const totalSeconds = Math.floor(diff / 1000)
  Days.value = Math.floor(totalSeconds / (3600 * 24)) //totalSeconds / (3600 * 24)取余留天数并用Math.floor取整
  Hours.value = formatTime(Math.floor((totalSeconds % (3600 * 24)) / 3600)) //(totalSeconds % (3600 * 24)取余留秒数，除一小时并取整
  Minutes.value = formatTime(Math.floor((totalSeconds % 3600) / 60)) //(totalSeconds % 3600)每个小时的余留秒数，除一分钟并取整
  Second.value = formatTime(Math.floor(totalSeconds % 60)) //取一分钟内余留秒数，并取整
}

// 格式化奖励的展示信息
const showDetail = (type, reward) => {
  let showamount = ['GOLD', 'DIAMOND', 'GIFT', 'FRAGMENTS']
  if (showamount.includes(type)) {
    return reward.content
  } else {
    return `${reward.quantity}Days`
  }
}

// 获取俩榜单
const getTopList = async (params) => {
  const resWeekTopList = await getWeekTopList(params)
  if (resWeekTopList.status && resWeekTopList.body) {
    if (params.kingQueenType == 'WEALTH') {
      if (kingList.value.length == 0) listTop.value[0].userInfo = resWeekTopList.body.records[0] //首次加载获取king榜首
      kingList.value.push(...resWeekTopList.body.records)
      if (params.current * params.size >= resWeekTopList.body.total) showKingLoading.value = false
    } else {
      if (queenList.value.length == 0) listTop.value[1].userInfo = resWeekTopList.body.records[0] //首次加载获取king榜首
      queenList.value.push(...resWeekTopList.body.records)
      if (params.current * params.size >= resWeekTopList.body.total) showQueenLoading.value = false
    }
  }
}

// 获取我的贡献
const getMyContribution = async () => {
  console.log('userInfo.value.id:', userInfo.value)

  let userId = userInfo.value.id
  console.log('userId:', userId)

  const resWeekMyContribution = await getWeekMyContribution(userId)
  console.log('resWeekMyContribution:', resWeekMyContribution)

  if (resWeekMyContribution.status && resWeekMyContribution.body) {
    myRanking.value = resWeekMyContribution.body
  }
}

// 获取每周奖励列表和礼物
const getRewardsAndGifts = async () => {
  const resRewardsAndGifts = await getThisWeekRewardsAndGifts('1966020557831610370')
  if (resRewardsAndGifts.status && resRewardsAndGifts.body) {
    gifts.value = resRewardsAndGifts.body.gifts
    kingRewards.value = resRewardsAndGifts.body.butOneRewards
    queenRewards.value = resRewardsAndGifts.body.butTwoRewards

    console.log('kingRewards:', kingRewards.value)
    console.log('queenRewards:', queenRewards.value)
  }
}

const getAllTopOne = async () => {
  const resHistoryTopOne = await getHistoryTopOne()
  if (resHistoryTopOne.status && resHistoryTopOne.body) {
    historyList.value = resHistoryTopOne.body
  }
}

//获取用户信息
const getUserInfo = async () => {
  if (Object.keys(userInfo.value).length === 0) {
    const resUserInfo = await getMemberProfile()
    if (resUserInfo.status && resUserInfo.body) {
      userInfo.value = resUserInfo.body
    }
  }
  getMyContribution() // 获取我的贡献
}

// 关闭弹窗
const closedPopup = () => {
  helpInfoShow.value = false
  historyShow.value = false
  rewardsShow.value = false
}

// IntersectionObserver配置
const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > 0) {
      console.log('监控到底部')
      if (entry.target == kingListLoadmore.value && kingList.value.length != 0) {
        console.log('kingListLoadmore')
        kingListCurrent.value++
        debouceGetKingList()
      }
      if (entry.target == queenListloadmore.value && queenList.value.length != 0) {
        console.log('queenListloadmore')
        queenListCurrent.value++
        debouceGetQueenList()
      }
    }
  })
})

// 刷新页面数据
const updatePageData = () => {
  getTopList(kingListParams.value) // 获取国王榜单
  getTopList(queenListParams.value) // 获取女王榜单
  getRewardsAndGifts() //获取本周的礼物和国王和皇后top奖励列表
  getAllTopOne() //获取近几个月的榜首国王女王
}

// 预加载关键图片
const preloadCriticalImages = () => {
  const criticalImages = [
    imageUrl('bg'),
    imageUrl('help'),
    imageUrl('history'),
    imageUrl('listTitle'),
    imageUrl('dayBg'),
    imageUrl('timeBg'),
    imageUrl('rewards'),
    imageUrl('eventGifts'),
    imageUrl('gift'),
    imageUrl('kingBtActive'),
    imageUrl('queenBt'),
    imageUrl('kingBt'),
    imageUrl('queenBtActive'),
    imageUrl('border-item-user'),
    imageUrl('helpInfo'),
    imageUrl('border-item'),
    imageUrl('timeBack'),
    imageUrl('timeNext'),
    imageUrl('cancel'),
    imageUrl('myRankingBg'),
    imageUrl('kingFrame'),
    imageUrl('queenFrame'),
    imageUrl('top1'),
    imageUrl('top2'),
    imageUrl('top3'),
  ]

  preloadImages(criticalImages)
}

// 组件挂载时检测环境
onMounted(() => {
  isInAppEnvironment.value = isInApp()
  connectToAppHandler()

  getCountdown()
  timer = setInterval(getCountdown, 1000) //每秒更新

  if (kingListLoadmore.value) {
    observer.observe(kingListLoadmore.value)
  } //监控国王加载标志

  if (queenListloadmore.value) {
    observer.observe(queenListloadmore.value)
  } //监控女王加载标志
})

onUnmounted(() => {
  clearInterval(timer)
})
</script>

<style scoped>
* {
  color: black;
  font-family: 'SF Pro';
}

.fullPage {
  background-color: rgba(77, 30, 22, 1);
  min-height: 100vh;
  position: relative;
}

.bg {
  width: 100vw;
  background-image: var(--bg-url);
  background-size: 100% auto;
  background-repeat: no-repeat;
  position: relative;
}

.time {
  font-size: 0.9em;
  position: absolute;
  inset: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #fff;
  font-weight: 860;
}

.topUserNickname {
  font-size: 0.8em;
}

.topUserNickname::-webkit-scrollbar {
  display: none;
}

@media screen and (max-width: 360px) {
  * {
    font-size: 10px;
  }

  .topName {
    font-size: 8px;
  }
}

@media screen and (min-width: 360px) {
  * {
    font-size: 16px;
  }

  .topName {
    font-size: 10px;
  }
}

@media screen and (min-width: 768px) {
  * {
    font-size: 24px;
  }

  .topName {
    font-size: 20px;
  }
}

@media screen and (min-width: 1024px) {
  * {
    font-size: 32px;
  }

  .topName {
    font-size: 30px;
  }
}
</style>
