<!-- src/views/Activities/Reward/RechargeReward.vue -->
<template>
  <div class="fullPage">
    <!-- 预加载状态 -->
    <div v-if="isLoading" class="loading-container">
      <LoadingContent>{{ $t('loading') }}...</LoadingContent>
    </div>

    <!-- 主要内容 -->
    <div v-else>
      <!-- Rewards0.png 使用相对定位容器 -->
      <itemCenter :imgUrl="webpUrl('goodID0New')" :contentStyle="`display: block;`">
        <!-- 帮助按钮 -->
        <img
          v-smart-img
          :src="webpUrl('help')"
          alt=""
          style="
            position: absolute;
            top: 57%;
            right: 4%;
            display: block;
            width: 10vw;
            aspect-ratio: 1/1;
            object-fit: cover;
          "
          @click="maskLayerShow = true"
        />

        <!-- 用户财富等级、靓号申请窗口 -->
        <itemCenter
          style="position: absolute; top: 65%"
          :imgUrl="webpUrl('applyBg')"
          :contentStyle="`display: block;`"
        >
          <!-- 财富等级 -->
          <div style="height: 46%; display: flex; justify-content: center; align-items: center">
            <div
              style="
                width: 50%;
                height: 30%;
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <div
                style="
                  font-weight: 700;
                  font-size: 0.9em;

                  background: linear-gradient(0deg, #fff 0%, #ffe656 100%);
                  background-clip: text;
                  -webkit-background-clip: text;
                  -webkit-text-fill-color: transparent;
                "
              >
                {{ t('my_wealth_level') }} {{ wealthLevel }}
              </div>
            </div>
          </div>

          <!-- 申请 -->
          <div
            style="
              position: absolute;
              bottom: 22%;

              width: 79%;
              height: 30%;

              left: 50%;
              transform: translateX(-50%);

              display: flex;
              justify-content: space-between;
              align-items: center;
              gap: 8px;
            "
          >
            <!-- 输入框 -->
            <input
              v-model="goodId"
              type="text"
              :placeholder="t('good_id_placeholder')"
              style="
                flex: 1;
                min-width: 0;
                align-self: stretch;

                color: white;
                font-weight: 700;
                font-size: 1.1em;

                border: none;
                outline: none;
                background-color: transparent;
              "
              @keyup.enter="confirm"
            />

            <!-- 按钮 -->
            <img
              v-smart-img
              :src="webpUrl(getImgName('applyBt'))"
              alt=""
              style="height: 70%; display: block"
              @click="confirm"
            />
          </div>
        </itemCenter>
      </itemCenter>

      <!-- 其他图片直接引入 -->
      <img v-smart-img :src="webpUrl('goodID1')" alt="" style="width: 100%; display: block" />
      <img v-smart-img :src="webpUrl('goodID2')" alt="" style="width: 100%; display: block" />

      <!-- 弹窗遮罩层 -->
      <maskLayer :maskLayerShow="maskLayerShow" @click="maskLayerShow = false">
        <!-- help弹窗 -->
        <div style="margin: 20% 0" @click.stop>
          <img
            v-smart-img
            :src="webpUrl(getImgName('rule'))"
            alt=""
            style="display: block; width: 100%"
          />
        </div>
      </maskLayer>

      <!-- 提示弹窗 -->
      <div
        v-show="tipShow"
        style="position: fixed; top: 50vh; display: flex; justify-content: center; width: 100vw"
      >
        <div
          style="
            padding: 12px;
            border-radius: 8px;
            background: rgba(0, 0, 0, 0.4);
            font-weight: 600;
          "
        >
          {{ tipText }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useLangStore } from '@/stores/lang'
import { useI18n } from 'vue-i18n'
import { getWebpUrl } from '@/config/imagePaths.js'
import { connectToApp } from '@/utils/appConnector.js'
import { preloadImages } from '@/utils/image/imagePreloader.js'
import { getUserId } from '@/utils/userStore.js'
import { showError, showWarning, showSuccess } from '@/utils/toast.js'

import {
  apiGetUserWealthLevel, // 获取用户消费等级
  applyGoodID, // 申请靓号
} from '@/api/goodId.js'

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

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

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

// 获取OSS图片URL的函数
const webpUrl = (filename) => getWebpUrl('GoodIDWebp/', filename)
// 根据语言获取图片名
const getImgName = (filename) => {
  return currentLangType.value === 'ar' ? `${filename}_ar` : filename
}

const wealthLevel = ref('-') //财富等级
const goodId = ref('') //靓号

const maskLayerShow = ref(false) //帮助模块
const tipShow = ref(false) //提示弹窗
const tipText = ref('') //提示文本

// 定义错误消息映射
const errorMessages = {
  4200: 'error_wealth_level_insufficient', // 财富等级尚未>=10级
  4201: 'error_invalid_id_format', // 输入的内容大于8位数或少于2位数
  4202: 'application_submitted_success', // 用户未在当前财富等级申请过ID（申请成功，待审核）
  4203: 'error_already_applied', // 用户在当前财富等级已经申请过ID（申请失败）
  4204: 'error_id_already_used', // 用户申请的ID已经被他人使用
}

// 限时提示弹窗
const showMessage = (messageKey) => {
  tipText.value = t(messageKey)
  tipShow.value = true
  setTimeout(() => {
    tipShow.value = false
  }, 2000)
}

// 申请靓号
const confirm = async () => {
  if (!goodId.value.trim()) return

  let data = { account: goodId.value.trim(), wealthLevel: wealthLevel.value }
  try {
    const resApplyGoodID = await applyGoodID(data)
    if (resApplyGoodID.status) {
      goodId.value = ''
      showMessage('application_submitted_success')
      initData() //重新获取数据
    }
  } catch (error) {
    const errorCode = error.response?.errorCode
    if (errorCode in errorMessages) {
      showMessage(errorMessages[errorCode])
    } else {
      showError(error.errorMsg)
    }
  }
}

// 获取我的财富等级
const getUserWealthLevel = async () => {
  try {
    const resWealthLevel = await apiGetUserWealthLevel(getUserId())
    if (resWealthLevel.status && resWealthLevel.body) {
      wealthLevel.value = resWealthLevel.body?.wealthLevel || '-'
    }
  } catch (error) {
    showError(error.errorMsg)
  }
}

// 初始化数据
const initData = () => {
  getUserWealthLevel() // 获取我的财富等级
}

// 预加载关键图片
const preloadCriticalImages = () => {
  const criticalImages = [
    webpUrl('goodID0New'),
    webpUrl('goodID1'),
    webpUrl('goodID2'),
    webpUrl('help'),
    webpUrl('rule'),
    webpUrl('applyBg'),
    webpUrl(getImgName('applyBt')),
  ]

  return preloadImages(criticalImages)
}

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

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

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

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

.fullPage {
  width: 100vw;
  min-height: 100vh;
  position: relative;
  background-color: #9d5225;
}

.textGold {
  background: linear-gradient(
    255deg,
    #b77c44 28.08%,
    #fee5bb 46.5%,
    #bf854a 67.95%,
    #fcdfb3 85.67%,
    #c0864b 102.89%,
    #fbe8d4 122.57%
  );
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

input::placeholder {
  color: #fff;
}

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

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

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

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

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