<template>
  <div>
    <div>
      <div style="display: flex; justify-content: center">
        <TopUser
          ranking="1"
          :BorderImgUrl="imageUrl('top1Bg')"
          :avatarUrl="rankingTop3[0].userAvatar"
          :name="rankingTop3[0].userName"
          :rankingType="rankingType"
          :distributionValue="rankingTop3[0].amount"
          style="width: 70%"
          @click="viewUserInfo(rankingTop3[0].userId)"
        />
      </div>

      <div
        style="
          position: relative;
          z-index: 3;
          display: flex;
          justify-content: space-around;
          pointer-events: none;
        "
      >
        <div
          style="pointer-events: auto; width: 42%"
          @click.stop="viewUserInfo(rankingTop3[1].userId)"
        >
          <TopUser
            ranking="2"
            :BorderImgUrl="imageUrl('top2Bg')"
            :avatarUrl="rankingTop3[1].userAvatar"
            :name="rankingTop3[1].userName"
            :rankingType="rankingType"
            :distributionValue="rankingTop3[1].amount"
            style="width: 100%"
          />
        </div>

        <div
          style="pointer-events: auto; width: 42%"
          @click.stop="viewUserInfo(rankingTop3[2].userId)"
        >
          <TopUser
            ranking="3"
            :BorderImgUrl="imageUrl('top3Bg')"
            :avatarUrl="rankingTop3[2].userAvatar"
            :name="rankingTop3[2].userName"
            :rankingType="rankingType"
            :distributionValue="rankingTop3[2].amount"
            style="width: 100%"
          />
        </div>
      </div>
    </div>

    <div
      v-if="showRanking.length > 0"
      style="position: relative; z-index: 2; display: flex; flex-direction: column; gap: 2vw"
    >
      <div
        v-for="(listItem, index) in showRanking"
        :key="listItem.userId || index"
        style="padding: 0 2vw; display: flex; align-items: center; gap: 2vw"
      >
        <itemCenter
          style="min-height: 9.11vw; width: 10vw"
          :imgUrl="imageUrl('rankingNumBg')"
          :contentStyle="`bottom: 0.5vw;`"
          @click="viewUserInfo(listItem.userId)"
        >
          <div style="color: #ffe601; font-weight: 700">{{ listItem?.rank }}</div>
        </itemCenter>

        <itemCenter
          style="min-height: 36vw"
          :imgUrl="imageUrl('rankingItemBg')"
          :contentStyle="`padding: 9.5vw 4vw 7vw 5vw;gap: 1vw`"
          :flip="true"
          :lazy="true"
          :immediate="index < 2"
          @click="viewUserInfo(listItem.userId)"
        >
          <div
            style="
              flex: 1;
              min-width: 0;
              display: flex;
              justify-content: space-around;
              align-items: center;
              gap: 10vw;
            "
          >
            <img
              :src="listItem?.userAvatar || ''"
              alt=""
              style="
                display: block;
                width: 19vw;
                aspect-ratio: 1/1;
                border-radius: 50%;
                object-fit: cover;
                z-index: -1;
              "
              @error="handleAvatarImageError"
            />

            <div style="flex: 1; min-width: 0; display: flex; flex-direction: column">
              <div style="display: flex; min-width: 0">
                <div
                  style="
                    color: #fff;
                    font-weight: 860;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                    direction: ltr;
                  "
                  class="sfr-x1"
                >
                  {{ listItem?.userName }}
                </div>
              </div>

              <div style="color: #fff; font-weight: 590" class="sfr-x1">
                {{ $t('user_id_prefix') }} {{ listItem?.specialAccount || listItem?.account }}
              </div>
            </div>
          </div>

          <div
            style="
              width: auto;
              min-width: 0;
              display: flex;
              align-items: center;
            "
          >
            <div
              v-if="rankingType === 'lottery'"
              style="display: flex; justify-content: center; align-items: center"
            >
              <img
                v-smart-img
                src="/src/assets/icon/Aslan/coin.png"
                alt=""
                style="display: block; width: 1.5em; aspect-ratio: 1/1; object-fit: cover"
              />
              <div style="color: #ffe601; font-weight: 700" class="Textlittle">
                {{ listItem?.amount || 0 }}
              </div>
            </div>

            <div
              v-if="rankingType === 'recharge'"
              style="color: #fff; font-weight: 700"
              class="sfr-x1"
            >
              ${{ listItem?.amount }}
            </div>
          </div>
        </itemCenter>
      </div>
    </div>

    <div ref="rankingLoadmore"></div>
  </div>
</template>

<script setup>
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { storeToRefs } from 'pinia'

import { viewUserInfo } from '@/utils/appBridge.js'
import { useThrottle } from '@/utils/useDebounce'
import { getPngUrl } from '@/config/imagePaths.js'
import { handleAvatarImageError } from '@/utils/image/imageHandler.js'
import { useSpringFestival } from '@/stores/springFestival'
import { ranklist } from '@/api/lottery'

import itemCenter from '@/components/itemCenter.vue'
import TopUser from './components/topUser.vue'

const { t } = useI18n()

const props = defineProps({
  rankingType: {
    type: String,
    default: '',
  },
})

const springFestivalStore = useSpringFestival()
const {
  lotteryPageNo,
  lotteryRanking,
  addLotteryRanking,
  myLotteryRanking,
  rechargePageNo,
  rechargeRanking,
  addRechargeRanking,
  myRechargeRanking,
} = storeToRefs(springFestivalStore)

const imageUrl = (filename) => getPngUrl('Activities/SpringFestival/', filename)

const rankingTotal = computed(() => {
  if (props.rankingType === 'lottery') {
    return [...lotteryRanking.value, ...addLotteryRanking.value]
  }
  return [...rechargeRanking.value, ...addRechargeRanking.value]
})

const rankingTop3 = computed(() => {
  const top3 = [...rankingTotal.value]
  if (top3.length < 3) {
    top3.push(
      ...Array.from({ length: 3 - top3.length }, () => ({
        userAvatar: '',
        userName: '',
        amount: '',
      })),
    )
  }
  return top3
})

const showRanking = computed(() => {
  return rankingTotal.value.filter((_, index) => index >= 3)
})

const rankingLoadmore = ref(null)

const getRanking = async () => {
  if (lotteryPageNo.value === 0) {
    lotteryPageNo.value = 1
  }
  if (rechargePageNo.value === 0) {
    rechargePageNo.value = 1
  }

  const isLottery = props.rankingType === 'lottery'
  const data = {
    activityId: isLottery ? '2007771533988204877' : '2007771533988204888',
    pageNo: isLottery ? lotteryPageNo.value : rechargePageNo.value,
    pageSize: 20,
  }

  const resRanking = await ranklist(data)
  if (!(resRanking.status && resRanking.body)) {
    if (isLottery) {
      myLotteryRanking.value = {}
      lotteryRanking.value = []
      addLotteryRanking.value = []
      lotteryPageNo.value = 1
    } else {
      myRechargeRanking.value = {}
      rechargeRanking.value = []
      addRechargeRanking.value = []
      rechargePageNo.value = 1
    }
    return
  }

  if (isLottery) {
    myLotteryRanking.value = resRanking.body?.currentUser || {}
  } else {
    myRechargeRanking.value = resRanking.body?.currentUser || {}
  }

  if (resRanking.body.topList.length <= 0) {
    return
  }

  if (resRanking.body.topList.length === 20) {
    if (isLottery) {
      addLotteryRanking.value = []
      lotteryRanking.value.push(...resRanking.body.topList)
      lotteryPageNo.value += 1
    } else {
      addRechargeRanking.value = []
      rechargeRanking.value.push(...resRanking.body.topList)
      rechargePageNo.value += 1
    }
    return
  }

  if (isLottery) {
    addLotteryRanking.value = resRanking.body.topList
  } else {
    addRechargeRanking.value = resRanking.body.topList
  }
}

const debouceGetRanking = useThrottle(() => {
  getRanking()
}, 1000)

const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (entry.intersectionRatio > 0 && rankingTotal.value.length !== 0) {
      debouceGetRanking()
    }
  })
})

onMounted(async () => {
  await nextTick()
  if (rankingLoadmore.value) {
    observer.observe(rankingLoadmore.value)
  }
})

onUnmounted(() => {
  observer.disconnect()
})
</script>

<style lang="scss" scoped>
* {
  color: #fff;
}

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

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

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

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