<template>
  <div style="padding: 0 4vw; display: grid; grid-template-columns: repeat(3, 1fr); gap: 2vw">
    <itemCenter
      v-for="item in goodsList"
      :key="item.id"
      :imgUrl="imageUrl('goodsItem')"
      :contentStyle="`flex-direction: column;justify-content: space-between;align-items: center;`"
    >
      <div
        style="
          width: 100%;
          min-width: 0;
          aspect-ratio: 1/0.95;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <img
          v-smart-img
          :src="item.propsGroup?.activityRewardProps?.[0].cover"
          alt=""
          style="width: 70%; display: block; object-fit: cover"
        />
      </div>

      <div style="height: 17%; display: flex; justify-content: center; align-items: center">
        <!-- <img
          v-smart-img
          :src="imageUrl(getImgName('debris'))"
          alt=""
          style="display: block; width: 2em; object-fit: cover"
        /> -->
        <div style="font-size: 0.8em; font-weight: 600; color: #fff" @click="exchangeGoods(item)">
          *{{
            formatRewardDisplay(
              item.propsGroup?.activityRewardProps?.[0]?.type,
              item.propsGroup?.activityRewardProps?.[0],
            )
          }}/ {{ JSON.parse(item.rule.jsonData).need_fragments }}Star
        </div>
      </div>
    </itemCenter>
  </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 { formatRewardDisplay } from '@/utils/rewardFormatter.js'

import {
  apiGetActivityResource, //获取兑换资源
  apiGetMyLotteryTicketCount, // 获取我的剩余抽奖券数量
  apiGetUserFragmentBackpack, // 获取用户碎片背包
  exchangeGood, //用碎片兑换资源
} from '@/api/couple.js'

import itemCenter from '@/components/itemCenter.vue'
import maskLayer from '@/components/MaskLayer.vue'
import { storeToRefs } from 'pinia'

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 {
  debris, // 碎片
  fragmentNotEnoughShow, // 碎片不足弹窗
  exchangeConfirmShow, // 兑换确认弹窗
  exchangeItem, // 当前兑换的物品
} = storeToRefs(coupleStore)

const goodsList = ref([]) // 兑换物品列表

// 获取兑换物品列表
const getActivityResource = async () => {
  try {
    const response = await apiGetActivityResource('APRIL_ACTIVITY_FRAGMENT')
    if (response.status) {
      goodsList.value = response.body || []
    }
  } catch (error) {
    showError(error.errorMsg)
  }
}

// 用碎片兑换资源
const exchangeGoods = async (goods) => {
  // 碎片不足提示
  if (debris.value < JSON.parse(goods.rule.jsonData).need_fragments) {
    fragmentNotEnoughShow.value = true
    return
  }

  exchangeItem.value = {
    userId: getUserId(),
    propsGroupId: goods.rule.id,
    fragmentsId: '2011710323414081538',
  }
  // 触发兑换确认弹窗
  exchangeConfirmShow.value = true
}

// 页面初始化数据
const initData = async () => {
  await Promise.all([
    getActivityResource(), // 获取兑换物品列表
  ])
}

// 预加载关键图片
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>
