<template>
  <div style="display: flex; flex-direction: column; gap: 2vw">
    <!-- 个人充值信息 -->
    <div style="padding: 0 4vw">
      <itemCenter
        style="min-height: 41.66vw; z-index: 0"
        :imgUrl="imageUrl('earningInfoBg')"
        :flip="true"
        :contentStyle="`inset:11vw 10vw 9vw 9vw;justify-content: space-between;gap: 10vw;`"
      >
        <!-- 头像 -->
        <img
          :src="myRechargeRecode?.userAvatar || ''"
          alt=""
          style="
            position: relative;
            z-index: -1;
            width: 23vw;
            min-width: 0;

            border-radius: 50%;
            aspect-ratio: 1/1;
            object-fit: cover;
          "
          @error="handleAvatarImageError"
        />

        <!-- 基本信息 -->
        <div
          style="
            position: relative;
            flex: 1;
            min-width: 0;
            height: 80%;

            display: flex;
            flex-direction: column;
            justify-content: center;
            gap: 1vw;
          "
        >
          <!-- 充值帮助按钮 -->
          <img
            v-smart-img
            src="/src/assets/icon/Aslan/helpWhite.png"
            alt=""
            class="ruleBt"
            @click="openPopup('rechargeHelp')"
          />

          <!-- 名称 -->
          <div
            style="
              max-width: 70%;
              min-width: 0;
              font-weight: 500;
              overflow: hidden;
              white-space: nowrap;
              text-overflow: ellipsis;
            "
          >
            {{ myRechargeRecode?.userName || '' }}
          </div>

          <!-- 账号 -->
          <div>{{ $t('user_id_prefix') }} {{ myRechargeRecode?.account }}</div>

          <!-- 总充值 -->
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
              white-space: nowrap;
            "
          >
            <div>
              {{ t('Accumulated recharge') }}:${{
                formatRechargeAmount(myRechargeRecode?.totalAmount)
              }}
            </div>

            <img
              v-show="rechargehidden"
              v-smart-img
              :src="imageUrl('rechargeNumHidden')"
              alt=""
              style="width: 5vw; display: block; object-fit: cover"
              @click="rechargehidden = !rechargehidden"
            />
            <img
              v-show="!rechargehidden"
              v-smart-img
              :src="imageUrl('rechargeNumShow')"
              alt=""
              style="width: 5vw; display: block; object-fit: cover"
              @click="rechargehidden = !rechargehidden"
            />
          </div>
        </div>
      </itemCenter>
    </div>

    <itemCenter
      :style="{ minHeight: index <= 0 ? '106vw' : index <= 2 ? '109.6vw' : '135.73vw' }"
      v-for="(rewardsTop, index) in RechargeRewards"
      style=""
      :imgUrl="topImg[index]"
      :contentStyle="rewardContentLayer(index)"
    >
      <!-- 奖励列表 -->
      <div
        v-for="(reward, rewardIndex) in rewardsTop.rewardProps"
        :key="rewardIndex"
        style="
          width: 100%;
          align-self: stretch;
          display: flex;
          flex-direction: column;
          align-items: center;
        "
      >
        <!-- 奖品图 -->
        <div
          style="
            width: 80%;
            height: 75%;
            padding: 6vw 0 2vw;
            min-width: 0;
            aspect-ratio: 1/1;

            display: flex;
            justify-content: center;
            align-items: center;
          "
        >
          <!-- 奖励图片 -->
          <img
            :src="reward.cover || ''"
            alt=""
            style="display: block; min-width: 0; width: 80%; height: 100%; object-fit: contain"
            @error="(e) => handleRewardImageError(e, reward.type)"
          />
        </div>

        <!-- 数值 -->
        <div
          style="
            width: 80%;
            height: 5.5vw;
            display: flex;
            justify-content: center;
            align-items: center;
          "
        >
          <div style="min-width: 0; font-size: 1em; font-weight: 590; color: #fff">
            {{ formatRewardDisplay(reward.type, reward) }}
          </div>
        </div>
      </div>

      <!-- 领取按钮 -->
      <div
        style="
          position: absolute;
          bottom: 7vw;
          left: 0;
          right: 0;
          width: 100%;

          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        <img
          v-smart-img
          v-if="rewardsTop.claimStatus == -1"
          class="grayscale-container"
          :src="imageUrl(getImgName('receiveBt'))"
          alt=""
          style="width: 40vw; display: block; object-fit: cover"
        />
        <img
          v-smart-img
          v-if="rewardsTop.claimStatus == 0"
          :src="imageUrl(getImgName('receiveBt'))"
          alt=""
          style="width: 40vw; display: block; object-fit: cover"
          @click="receiveReward(rewardsTop)"
        />
        <img
          v-smart-img
          v-if="rewardsTop.claimStatus == 1"
          :src="imageUrl(getImgName('receivedBt'))"
          alt=""
          style="width: 40vw; display: block; object-fit: cover"
        />
      </div>
    </itemCenter>
  </div>
</template>

<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { connectToApp } from '@/utils/appConnector.js'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { setDocumentDirection } from '@/locales/i18n'
import { viewUserInfo } from '@/utils/appBridge.js'
import { useLangStore } from '@/stores/lang'
import { getPngUrl } from '@/config/imagePaths.js'
import { preloadImages } from '@/utils/image/imagePreloader.js'
import { showError, showSuccess } from '@/utils/toast.js'
import { handleAvatarImageError, handleRewardImageError } from '@/utils/image/imageHandler.js'
import { formatRewardDisplay } from '@/utils/rewardFormatter.js'
import { useSpringFestival } from '@/stores/springFestival'
import { storeToRefs } from 'pinia'

import {
  receiveRechargeReward, // 领取充值奖励
  activityRewardConfigs, // 获取活动奖励配置列表
} from '@/api/lottery'

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

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

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()
const springFestivalStore = useSpringFestival()

const {
  // 抽奖模块
  lotteryRewards, // 抽奖奖池
  tickets, // 抽奖券数量
  luckyUsers, // 中奖用户列表
  userInfo, // 用户信息
  userIdentity, // 用户身份
  currentEarnings, // 当前收益
  selectedPayee, // 选择的收款人
  taskList, // 任务列表

  // 抽奖排名模块
  lotteryPageNo, // 抽奖排名页码
  lotteryRanking, // 抽奖排名
  addLotteryRanking, // 补充的抽奖排名
  myLotteryRanking, // 我的抽奖排名

  // 排行榜奖励模块
  rankingRewards, // 排名奖池

  // 充值排名模块
  rechargePageNo, // 充值排名页码
  rechargeRanking, // 充值排名
  addRechargeRanking, // 补充的充值排名
  myRechargeRanking, // 我的充值排名

  // 充值奖池模块
  myRechargeRecode, // 我的充值记录
  RechargeRewards, // 充值奖池

  resultShow,
  result, // 抽奖结果

  drawRecordShow,
  myRecords, // 我的抽奖记录

  receiveRecordShow,
  receiveRecord, // 领取抽奖券记录

  taskListShow, // 任务列表展示
  checkDate, // 对应周几
  checkStatus, // 是否已看过

  earningsHelpShow, // 收益help展示
  rechargeHelpShow, // 充值help展示
} = storeToRefs(springFestivalStore)

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

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

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

const rechargehidden = ref(true) //金额是否隐藏
// 根据隐藏状态处理金额显示的方法
const formatRechargeAmount = (amount) => {
  if (rechargehidden.value) {
    // 如果隐藏，则将数字替换为*
    return String(amount || '0').replace(/\d/g, '*')
  } else {
    // 如果不隐藏，则正常显示
    return amount || '0'
  }
}

const topImg = ref([
  imageUrl(getImgName('rechargeReward100')),
  imageUrl(getImgName('rechargeReward500')),
  imageUrl(getImgName('rechargeReward1000')),
  imageUrl(getImgName('rechargeReward3000')),
  imageUrl(getImgName('rechargeReward5000')),
  imageUrl(getImgName('rechargeReward10000')),
]) // top图片

//充值奖励的内容样式
const rewardContentLayer = (index) => {
  let gridStyle = ''
  if (currentLangType.value == 'ar') {
    gridStyle = 'direction: ltr;'
  }
  if (index == 0) {
    return `display: grid;grid-template-columns: repeat(3, 1fr);gap:3vw 3.5vw;padding: 27.5vw 7vw 22vw;${gridStyle}`
  } else if (index == 1 || index == 2) {
    return `display: grid;grid-template-columns: repeat(3, 1fr);gap:3vw 3.5vw;padding: 27.5vw 7vw 25.5vw;${gridStyle}`
  } else if (index == 3 || index == 4 || index == 5) {
    return `display: grid;grid-template-columns: repeat(3, 1fr);gap:3vw 3.5vw;padding: 27.5vw 7vw 21.5vw;${gridStyle}`
  }
}

// 打开遮罩层
const openPopup = (type) => {
  switch (type) {
    case 'result':
      closedPopup() // 关闭弹窗
      resultShow.value = true
      break
    case 'drawRecord':
      closedPopup() // 关闭弹窗
      drawRecordShow.value = true
      break
    case 'receiveRecord':
      closedPopup() // 关闭弹窗
      receiveRecordShow.value = true
      break
    case 'earningsHelp':
      closedPopup() // 关闭弹窗
      earningsHelpShow.value = true
      break
    case 'rechargeHelp':
      closedPopup() // 关闭弹窗
      rechargeHelpShow.value = true
      break
    case 'taskList':
      closedPopup() // 关闭弹窗
      taskListShow.value = true
      break

    default:
      closedPopup() // 关闭弹窗
      break
  }
}

// 关闭弹窗
const closedPopup = () => {
  if (taskListShow.value) {
    checkStatus.value = true
  }

  resultShow.value = false
  drawRecordShow.value = false
  receiveRecordShow.value = false
  earningsHelpShow.value = false
  rechargeHelpShow.value = false
  taskListShow.value = false
}

// 领取充值奖励
const receiveReward = async (rewards) => {
  let data = {
    activityType: rewards.activityType,
    activityId: '2007771533988204888',
    ruleId: rewards.ruleId,
  }
  try {
    const resReceive = await receiveRechargeReward(data)
    if (resReceive.status && resReceive.body) {
      getRechargeReward() // 刷新充值奖励
    }
  } catch (error) {
    showError(error.errorMsg)
  }
}

//获取充值奖励列表
const getRechargeReward = async () => {
  let data = {
    activityType: 'CONSUMPTION_ACTIVITY',
    activityId: '2007771533988204888',
  }
  const resActivityReward = await activityRewardConfigs(data)
  if (resActivityReward.status && resActivityReward.body) {
    RechargeRewards.value = resActivityReward.body.map((rewards) => {
      let jsonData = JSON.parse(rewards.jsonData)
      let addReward = []

      if (rewards.sort == 1) {
        addReward = []
      } else if (rewards.sort == 2) {
        addReward = []
      } else if (rewards.sort == 3) {
        addReward = []
      } else if (rewards.sort == 4) {
        addReward = [
          {
            type: 'GIFT',
            cover: imageUrl('reward_gift'),
            content: 1,
          },
        ]
      } else if (rewards.sort == 5) {
        addReward = [
          {
            type: 'GIFT',
            cover: imageUrl('reward_gift'),
            content: 1,
          },
        ]
      } else if (rewards.sort == 6) {
        addReward = [
          {
            type: 'GIFT',
            cover: imageUrl('reward_gift'),
            content: 1,
          },
          {
            type: 'PROPS',
            detailType: 'AVATAR_FRAME',
            cover: imageUrl('reward_frame'),
            quantity: 365,
          },
          {
            type: 'PROPS',
            detailType: 'RIDE',
            cover: imageUrl('reward_ride'),
            quantity: 60,
          },
        ]
      }

      rewards.rewardProps.push(...addReward) //补充奖励项

      rewards = {
        ...rewards,
        ...jsonData,
      }
      return rewards
    })
    console.log('RechargeRewards.value:', RechargeRewards.value)
  } else {
    RechargeRewards.value = []
  }
}

onMounted(() => {})

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

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

.fullPage {
  position: relative;
  background: #142c24;
}

.bg {
  width: 100vw;
  min-height: 100vh;
  position: relative;
  z-index: 1;
}

.background-overlay {
  position: absolute;
  inset: 236vw 0 0;
  background-image: var(--bg2-url);
  background-repeat: repeat-y;
  background-position: top center;
  background-size: 100% auto;
  z-index: 0; /* 确保在.bg之下 */
}

/* 添加加载动画样式 */
.loading-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #666;
}

.ruleBt {
  width: 4vw;
  min-width: 0;
  display: block;
  aspect-ratio: 1/1;
  object-fit: cover;

  position: absolute;
  top: 0;
  right: 0;
}

[dir='rtl'] .ruleBt {
  left: 0;
  right: auto;
}

.grayscale-container {
  filter: grayscale(100%) brightness(90%);
}

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

[dir='rtl'] .flipImg {
  transform: scaleX(-1);
}

@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>
