<template>
  <div style="padding: 4vw 0 8vw">
    <!-- 栏目按钮 -->
    <div
      style="
        width: 100vw;
        padding: 0 4vw;

        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 2vw;
      "
    >
      <!-- 抽奖栏目按钮 -->
      <div style="flex: 1; min-width: 0" @click="changeTag('lottery')">
        <img
          v-show="lotteryShow"
          v-smart-img
          :src="imageUrl(getImgName('gameLotteryBtActive'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
        <img
          v-show="!lotteryShow"
          v-smart-img
          :src="imageUrl(getImgName('gameLotteryBt'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
      </div>

      <!-- 签到按钮 -->
      <div style="flex: 1; min-width: 0" @click="changeTag('signIn')">
        <img
          v-show="signInShow"
          v-smart-img
          :src="imageUrl(getImgName('gameSignInBtActive'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
        <img
          v-show="!signInShow"
          v-smart-img
          :src="imageUrl(getImgName('gameSignInBt'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
      </div>

      <!-- 兑换按钮 -->
      <div style="flex: 1; min-width: 0" @click="changeTag('exchange')">
        <img
          v-show="exchangeShow"
          v-smart-img
          :src="imageUrl(getImgName('gameExchangeBtActive'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
        <img
          v-show="!exchangeShow"
          v-smart-img
          :src="imageUrl(getImgName('gameExchangeBt'))"
          alt=""
          style="width: 100%; display: block; object-fit: cover"
        />
      </div>
    </div>

    <div style="position: relative">
      <!-- 中奖历史按钮 -->
      <img
        v-smart-img
        :src="imageUrl('historyBt')"
        alt=""
        style="width: 8vw; position: absolute; z-index: 2; top: 0vw; right: 4vw"
        @click="showDrawRecord"
      />

      <itemCenter
        style="position: relative; z-index: 1"
        :imgUrl="imageUrl(getImgName('myPropsBg'))"
        :contentStyle="`inset: 28vw 17vw 25vw;justify-content:space-between;`"
      >
        <!-- 水晶数量 -->
        <div style="display: flex; align-items: center; gap: 1vw">
          <img
            v-smart-img
            :src="imageUrl('crystal')"
            alt=""
            style="display: block; width: 15vw; object-fit: cover"
          />
          <div style="font-size: 2em; font-weight: 600; color: #ff79a1">:{{ crystal }}</div>
        </div>

        <!-- 碎片数量 -->
        <div style="display: flex; align-items: center; gap: 1vw">
          <img
            v-smart-img
            :src="imageUrl('debris')"
            alt=""
            style="display: block; width: 15vw; object-fit: cover"
          />
          <div style="font-size: 2em; font-weight: 600; color: #ff79a1">:{{ debris }}</div>
        </div>
      </itemCenter>
    </div>

    <!-- 游戏模块 -->
    <lottery v-show="lotteryShow" style="margin-top: -35vw" />
    <signIn v-show="signInShow" />
    <exchange v-show="exchangeShow" />
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useLangStore } from '@/stores/lang'
import { useI18n } from 'vue-i18n'
import { getPngUrl } from '@/config/imagePaths.js'
import { getUserId, setUserInfo } from '@/utils/userStore.js'
import { viewUserInfo } from '@/utils/appBridge.js'
import { connectToApp } from '@/utils/appConnector.js'
import { preloadImages } from '@/utils/imagePreloader.js'
import { formatUTCCustom } from '@/utils/utcFormat.js'
import { showError, showSuccess } from '@/utils/toast.js'
import { handleAvatarImageError, handleRewardImageError } from '@/utils/imageHandler.js'
import { useCoupleStore } from '@/stores/couple'
import { storeToRefs } from 'pinia'

import {
  apiGetMyLotteryTicketCount, // 获取我的剩余抽奖券数量
  apiGetUserFragmentBackpack, // 获取用户碎片背包
  apiGetDrawBackpackLogs, // 查询抽奖背包流水(水晶&碎片)
} from '@/api/couple.js'

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

import lottery from './components/lottery.vue'
import signIn from './components/signIn.vue'
import exchange from './components/exchange.vue'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const coupleStore = useCoupleStore()

const langStore = useLangStore()
// 当前语言类型
const currentLangType = computed(() => {
  return langStore.selectedLang?.type || 'en'
})

const isLoading = ref(true) // 预加载状态

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

// 根据语言获取图片名
const getImgName = (filename) => {
  return currentLangType.value === 'ar' ? `${filename}_ar` : filename
}

const {
  crystal, //水晶数量
  debris, //碎片数量

  receiveRecordShow, // 领取记录弹窗
  receiveRecord, // 领取记录
} = storeToRefs(coupleStore)

const lotteryShow = ref(true) //抽奖模块
const signInShow = ref(false) //签到模块
const exchangeShow = ref(false) //兑换模块

// 切换栏目
const changeTag = (module) => {
  switch (module) {
    case 'lottery':
      lotteryShow.value = true
      signInShow.value = false
      exchangeShow.value = false
      break
    case 'signIn':
      lotteryShow.value = false
      signInShow.value = true
      exchangeShow.value = false
      break
    case 'exchange':
      lotteryShow.value = false
      signInShow.value = false
      exchangeShow.value = true
      break
  }
}

// 获取抽奖券
const getMyLotteryTicketCount = async () => {
  try {
    const response = await apiGetMyLotteryTicketCount('2004471533988167125')
    if (response.status) {
      crystal.value = response.body || 0
    }
  } catch (error) {
    showError(error.response.errorMsg)
  }
}

// 获取用户碎片背包
const getUserFragmentBackpack = async () => {
  try {
    const response = await apiGetUserFragmentBackpack({
      userId: getUserId(),
      // userId: '1957345312961527809',
      fragmentsIds: ['2011710323414081538'],
    })
    if (response.status) {
      debris.value = response.body?.[0]?.quantity || 0
    }
  } catch (error) {
    showError(error.response.errorMsg)
  }
}

// 获取领取记录
const getReceiveRecords = async () => {
  const resReceiveRecords = await apiGetDrawBackpackLogs({
    pageSize: 100,
    pageNum: 1,
  })
  if (resReceiveRecords.status && resReceiveRecords.body) {
    receiveRecord.value = resReceiveRecords.body?.records || []
    receiveRecordShow.value = true
  }
}

// 展示中奖记录
const showDrawRecord = () => {
  getReceiveRecords() // 获取中奖记录，并让爷爷组件打开弹窗
}

// 页面初始化数据
const initData = async () => {
  await Promise.all([
    getMyLotteryTicketCount(), // 获取我的剩余抽奖券数量
    getUserFragmentBackpack(), // 获取用户碎片背包
  ])
}

// 预加载关键图片
const preloadCriticalImages = async () => {
  const criticalImages = []

  const criticalImages_ar = []

  if (currentLangType.value == 'en') {
    await preloadImages(criticalImages)
  } else if (currentLangType.value == 'ar') {
    await preloadImages(criticalImages_ar)
  }
}

// 完成预加载
const completePreloading = async () => {
  try {
    // 执行所有初始化操作
    await Promise.all([initData(), preloadCriticalImages()])
    console.log('预加载完成，初始化数据成功')
  } catch (error) {
    console.error('预加载过程中发生错误:', error)
  } finally {
    // 无论成功或失败都结束加载状态
    isLoading.value = false
  }
}

// 使用工具函数连接APP
const connectToAppHandler = async () => {
  await connectToApp(() => {
    // 连接成功回调
    completePreloading() // 完成预加载
  })
}

onMounted(() => {
  connectToAppHandler()
})
</script>

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