<template>
  <div style="padding: 0 4vw; display: grid; grid-template-columns: repeat(3, 1fr); gap: 2vw">
    <itemCenter
      style="min-height: 35.3vw"
      v-for="item in goodsList"
      :key="item.id"
      :imgUrl="webpUrl('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
          :src="item.propsGroup?.activityRewardProps?.[0].cover"
          alt=""
          style="width: 70%; display: block; object-fit: cover"
        />
      </div>

      <!-- 兑换条件 -->
      <div class="conditions">
        <div
          style="
            font-size: 1em;
            font-weight: 800;

            background: linear-gradient(
              180deg,
              #ffdf6b 31.61%,
              #ffe562 36.73%,
              #fff 52.37%,
              #ffe562 58.67%,
              #ffa615 72.2%
            );
            background-clip: text;
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
          "
          @click="exchangeGoods(item)"
        >
          *{{
            formatRewardDisplay(
              item.propsGroup?.activityRewardProps?.[0]?.type,
              item.propsGroup?.activityRewardProps?.[0],
            )
          }}/ {{ JSON.parse(item.rule.jsonData).need_fragments }}
        </div>
        <img
          v-smart-img
          :src="webpUrl('debris')"
          alt=""
          style="display: block; width: 1em; object-fit: cover"
        />
      </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 { getWebpUrl } 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/image/imagePreloader.js'
import { formatUTCCustom } from '@/utils/utcFormat.js'
import { showError, showSuccess } from '@/utils/toast.js'
import { handleAvatarImageError, handleRewardImageError } from '@/utils/image/imageHandler.js'
import { useCoupleStore } from '@/stores/couple'
import { formatRewardDisplay } from '@/utils/rewardFormatter.js'

import {
  apiGetActivityResource, //获取兑换资源
} from '@/api/activity.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 webpUrl = (filename) => getWebpUrl('Ranking/Couple/webp/', 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.response.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>
.conditions {
  height: 17%;
  display: flex;
  justify-content: center;
  align-items: center;
}

[dir='rtl'] .conditions {
  flex-direction: row-reverse;
}
</style>
