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

    <!-- 主要内容 -->
    <div v-else style="width: 100vw; min-height: 100vh; overflow: hidden; position: relative">
      <!-- 页面背景 -->
      <BackgroundLayer :backgroundImages="[imageUrl('bg')]" />

      <div style="position: absolute; top: 0; left: 0; width: 100%">
        <GeneralHeader
          :isHomePage="true"
          :showHelp="true"
          :backImg="imgUrl"
          :title="t('invitation_to_register')"
          @help="helpInfoShow = true"
        />
      </div>

      <!-- 确认邀请码 -->
      <div class="leftBt">
        <img
          v-if="leftBtType === 'enterCode'"
          v-smart-img
          :src="imageUrl(getImgName('enterCode'))"
          alt=""
          width="40%"
          @click="enterCodeShow = true"
          style="display: block"
        />
        <img
          v-else-if="leftBtType === 'privateChat'"
          v-smart-img
          :src="imageUrl(getImgName('privateChat'))"
          alt=""
          width="40%"
          @click="gotoPrivateChat(myInviter.inviterInfo?.userId)"
          style="display: block"
        />
      </div>

      <!-- 主体内容 -->
      <div
        style="
          padding: 93vw 3vw 0;

          display: flex;
          flex-direction: column;
          gap: 2vw;
        "
      >
        <!-- 我的邀请码 -->
        <itemCenter
          style=""
          :imgUrl="imageUrl(getImgName('myCode'))"
          :contentStyle="`padding: 26vw 6vw 16vw;`"
        >
          <div
            style="
              width: 100%;
              padding: 3vw 1vw;
              display: flex;
              justify-content: center;
              align-items: center;
              gap: 4px;
            "
          >
            <div style="font-weight: 590; font-size: 1.1em">
              {{ myInviteInfo.inviteCode || '' }}
            </div>
            <img
              v-if="myInviteInfo.inviteCode"
              v-smart-img
              src="../../assets/icon/Aslan/copy.png"
              alt=""
              style="display: block; width: 2em; object-fit: cover"
              @click="copyCode(myInviteInfo.inviteCode || '')"
            />
          </div>
        </itemCenter>

        <!-- 模块切换按钮 -->
        <div style="display: flex; justify-content: space-around; align-items: center">
          <!-- 奖励按钮 -->
          <div style="width: 40%; position: relative">
            <img
              v-smart-img.noFade
              :src="imageUrl(getImgName('processBt'))"
              alt=""
              style="display: block; width: 100%"
              :style="{ opacity: showModule === 'process' ? 0 : 1 }"
              @click="showModule = 'process'"
            />
            <img
              v-smart-img.noFade
              :src="imageUrl(getImgName('processBtActive'))"
              alt=""
              style="display: block; width: 100%; position: absolute; top: 0; left: 0"
              :style="{ opacity: showModule === 'process' ? 1 : 0 }"
              @click="showModule = 'process'"
            />
          </div>

          <!-- 列表按钮 -->
          <div style="width: 40%; position: relative">
            <img
              v-smart-img.noFade
              :src="imageUrl(getImgName('listBt'))"
              alt=""
              style="display: block; width: 100%"
              :style="{ opacity: showModule === 'list' ? 0 : 1 }"
              @click="showModule = 'list'"
            />
            <img
              v-smart-img.noFade
              :src="imageUrl(getImgName('listBtActive'))"
              alt=""
              style="display: block; width: 100%; position: absolute; top: 0; left: 0"
              :style="{ opacity: showModule === 'list' ? 1 : 0 }"
              @click="showModule = 'list'"
            />
          </div>
        </div>

        <!-- 邀请列表模块 -->
        <div v-show="showModule == 'list'" style="display: flex; flex-direction: column; gap: 2vw">
          <!-- 收入展示 -->
          <itemCenter
            style=""
            :imgUrl="imageUrl(getImgName('incomeBg'))"
            :contentStyle="`padding: 32vw 6vw 18vw;display:grid;grid-template-columns: repeat(2, 1fr);gap: 3.8vw;`"
          >
            <!-- 总邀请人数 -->
            <div
              style="
                align-self: stretch;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                padding: 2vw;
              "
            >
              <div style="font-weight: 700; font-size: 0.9em">{{ t('total_invitations') }}</div>
              <div style="font-weight: 600; font-size: 1.2em">
                {{ myInviteIncome.validInviteCount || 0 }}
              </div>
            </div>

            <!-- 今日邀请人数 -->
            <div
              style="
                align-self: stretch;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                padding: 2vw;
              "
            >
              <div style="font-weight: 700; font-size: 0.9em">{{ t('todays_invitation') }}</div>
              <div style="font-weight: 600; font-size: 1.2em">
                {{ myInviteIncome.todayInviteCount || 0 }}
              </div>
            </div>

            <!-- 总收入 -->
            <div
              style="
                align-self: stretch;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                padding: 2vw;
              "
            >
              <div style="font-weight: 700; font-size: 0.9em">
                {{ t('invitation_total_income') }}
              </div>
              <div style="display: flex; align-items: center">
                <img
                  v-smart-img
                  src="/src/assets/icon/Aslan/coin.png"
                  alt=""
                  style="display: block; width: 1.5em"
                />
                <div style="font-weight: 600; font-size: 1.2em">
                  {{ myInviteIncome.totalIncome || 0 }}
                </div>
              </div>
            </div>

            <!-- 今日收入 -->
            <div
              style="
                align-self: stretch;
                display: flex;
                flex-direction: column;
                justify-content: space-around;
                padding: 2vw;
              "
            >
              <div style="font-weight: 700; font-size: 0.9em">{{ t('todays_income') }}</div>
              <div style="display: flex; align-items: center">
                <img
                  v-smart-img
                  src="/src/assets/icon/Aslan/coin.png"
                  alt=""
                  style="display: block; width: 1.5em"
                />
                <div style="font-weight: 600; font-size: 1.2em">
                  {{ myInviteIncome.todayIncome || 0 }}
                </div>
              </div>
            </div>
          </itemCenter>

          <!-- 列表 -->
          <itemCenter
            style=""
            :imgUrl="imageUrl(getImgName('listBg'))"
            :contentStyle="`padding: 25vw 6vw 10vw;`"
          >
            <div
              style="
                align-self: stretch;
                width: 100%;
                border-radius: 8px;
                background: rgba(194, 174, 232, 0.2);
                backdrop-filter: blur(32px);
                padding: 8px;

                display: flex;
                flex-direction: column;
                gap: 4px;
              "
            >
              <!-- 头部 -->
              <div style="width: 100%; display: flex; align-items: center">
                <!-- user项 -->
                <div style="flex: 1; font-weight: 590; font-size: 1em; text-align: center">
                  {{ t('users') }}
                </div>

                <!-- 时间项 -->
                <div
                  style="
                    flex: 1;
                    font-weight: 590;
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                  "
                >
                  <!-- 分割线 -->
                  <div
                    style="
                      width: 1px;
                      height: 16px;
                      background: linear-gradient(
                        rgba(217, 217, 217, 0) 0%,
                        #d9d9d9 50%,
                        rgba(217, 217, 217, 0) 100%
                      );
                    "
                  ></div>

                  <div style="font-weight: 590; font-size: 1em; text-align: center">
                    {{ t('unbinding_time') }}
                  </div>

                  <!-- 分割线 -->
                  <div
                    style="
                      width: 1px;
                      height: 16px;
                      background: linear-gradient(
                        rgba(217, 217, 217, 0) 0%,
                        #d9d9d9 50%,
                        rgba(217, 217, 217, 0) 100%
                      );
                    "
                  ></div>
                </div>

                <!-- 收入项 -->
                <div
                  style="
                    flex: 1;
                    font-weight: 590;
                    text-align: end;
                    font-size: 1em;
                    text-align: center;
                  "
                >
                  {{ t('prowide_income') }}
                </div>
              </div>

              <!-- 列表项 -->
              <div class="overflow-y-auto" style="align-self: stretch; width: 100%">
                <div
                  v-for="user in myInviteUsers"
                  style="width: 100%; display: flex; align-items: center"
                >
                  <div style="flex: 1; font-weight: 590; font-size: 1em; text-align: center">
                    {{ t('user_id_prefix') }}{{ user.invitedUserAccount || '-' }}
                  </div>
                  <div
                    style="
                      flex: 1;
                      font-weight: 590;
                      display: flex;
                      justify-content: space-between;
                      align-items: center;
                    "
                  >
                    <div
                      style="
                        width: 1px;
                        height: 16px;
                        background: linear-gradient(
                          rgba(217, 217, 217, 0) 0%,
                          #d9d9d9 50%,
                          rgba(217, 217, 217, 0) 100%
                        );
                      "
                    ></div>
                    <div style="font-weight: 590; font-size: 1em">
                      {{ user.remainingDays || 0 }}{{ t('day_unit') }}
                    </div>
                    <div
                      style="
                        width: 1px;
                        height: 16px;
                        background: linear-gradient(
                          rgba(217, 217, 217, 0) 0%,
                          #d9d9d9 50%,
                          rgba(217, 217, 217, 0) 100%
                        );
                      "
                    ></div>
                  </div>
                  <div
                    style="
                      flex: 1;
                      display: flex;
                      justify-content: center;
                      align-items: center;
                      gap: 4px;
                    "
                  >
                    <img
                      v-smart-img
                      src="/src/assets/icon/Aslan/coin.png"
                      alt=""
                      style="display: block; width: 1.1em"
                    />
                    <div style="color: #ffb627; font-size: 1em; font-weight: 590">
                      {{ user.provideIncome || 0 }}
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </itemCenter>
        </div>

        <!-- 流程说明模块 -->
        <div v-show="showModule == 'process'" style="position: relative">
          <img
            v-smart-img
            :src="imageUrl(getImgName('example'))"
            alt=""
            width="100%"
            style="display: block"
          />
        </div>
      </div>

      <!-- 弹窗遮罩层 -->
      <maskLayer :maskLayerShow="maskLayerShow" @click="closedPopup">
        <!-- 帮助模块 -->
        <div v-show="helpInfoShow" style="margin: 20% 0; position: relative" @click.stop>
          <img
            v-smart-img
            :src="imageUrl(getImgName('helpInfo'))"
            alt=""
            width="100%"
            style="display: block"
          />
        </div>

        <!-- 输入邀请码模块 -->
        <div
          v-show="enterCodeShow"
          style="
            width: 100vw;
            height: 100vh;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
          "
          @click="closedPopup"
        >
          <itemCenter
            style=""
            :imgUrl="imageUrl(getImgName('enterCodeBg'))"
            :contentStyle="`padding: 31.5vw 6vw 10vw;display: flex;flex-direction: column;justify-content: space-between;`"
            @click.stop
          >
            <!-- 邀请码 -->
            <div class="bindingUserCode">
              <!-- 输入框 -->
              <input
                v-model="invitationCode"
                type="text"
                style="
                  width: 44.5vw;
                  min-width: 0;
                  align-self: stretch;

                  color: white;
                  font-weight: 510;

                  padding: 4px 8px;
                  border: none;
                  outline: none;
                  background-color: transparent;
                "
                @keyup.enter="confirmInvitationCode"
              />

              <!-- 按钮 -->
              <div style="width: 16vw" @click="confirm"></div>
            </div>

            <!-- 礼物 -->
            <div
              style="
                width: 100%;
                height: 28vw;

                display: grid;
                grid-template-columns: repeat(4, 1fr);
                gap: 1.5vw;
              "
            >
              <div
                v-for="reward in bindingUserRewards"
                style="align-self: stretch; display: flex; flex-direction: column"
              >
                <div
                  style="
                    width: 100%;
                    min-width: 0;
                    aspect-ratio: 1/1;

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

                    display: flex;
                    justify-content: center;
                    align-items: center;
                  "
                >
                  {{ showDetail(reward) }}
                </div>
              </div>
            </div>
          </itemCenter>
        </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;
          "
        >
          {{ t('copied_successfully') }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useLangStore } from '@/stores/lang'
import { gotoPrivateChat } from '@/utils/appBridge.js'
import { showError, showWarning, showSuccess } from '@/utils/toast.js'
import { useClipboard } from '@vueuse/core'
import { connectToApp } from '@/utils/appConnector.js'
import { getPngUrl } from '@/config/imagePaths.js'
import { preloadImages } from '@/utils/image/imagePreloader.js'
import { handleRewardImageError } from '@/utils/image/imageHandler.js'

import {
  getMyInviteCode, // 获取我的邀请码
  bindInviteCode, // 绑定邀请码
  getMyInviteIncome, // 获取收益统计
  getMyInviteUsers, // 有效邀请用户列表
  apiGetBindingUserRewards, // 获取绑定用户奖励
  getMyInviter, // 获取我的邀请人信息
} from '@/api/invitation.js'

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

const imgUrl = new URL('/src/assets/icon/Aslan/arrowBack.png', import.meta.url).href

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

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

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

const { copy, isSupported } = useClipboard()

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

const helpInfoShow = ref(false) //帮助模块
const enterCodeShow = ref(false) //交易弹窗
const tipShow = ref(false) //提示弹窗

const invitationCode = ref('') //邀请码
const myInviteInfo = ref({}) //我的邀请信息
const myInviter = ref({}) //我的邀请人信息
const myInviteIncome = ref({}) //邀请用户收益统计
const myInviteUsers = ref([]) //邀请用户列表
const bindingUserRewards = ref([]) //绑定用户奖励

const showModule = ref('process') //显示模块

const leftBtType = computed(() => {
  // 数据还未加载完成
  if (!myInviter.value || Object.keys(myInviter.value).length === 0) {
    return null
  }

  // 优先级1: 如果有邀请人信息且有userId，则显示私聊按钮
  if (myInviter.value.inviterInfo?.userId) {
    return 'privateChat'
  }

  // 优先级2: 如果没有过期且没有邀请人，则显示输入邀请码按钮
  if (!myInviter.value.myInfo?.expired && !myInviter.value.inviterInfo) {
    return 'enterCode'
  }

  // 其他情况不显示按钮
  return null
})

// 展示遮罩层
const maskLayerShow = computed(() => {
  return helpInfoShow.value || enterCodeShow.value
})

// 关闭弹窗
const closedPopup = () => {
  helpInfoShow.value = false
  enterCodeShow.value = false
}

// 格式化奖励的展示信息
const showDetail = (reward) => {
  let showamount = ['GOLD', 'DIAMOND', 'GIFT', 'FRAGMENTS']
  if (showamount.includes(reward.type)) {
    return reward.content
  } else if (reward.type === 'DOLLARS') {
    return `$${reward.content}`
  } else {
    return `${reward.quantity}${t('day_unit')}`
  }
}

// 复制到剪贴板（原生方法）
const copyCode = (text) => {
  if (isSupported.value) {
    copy(text)
  } else {
    // 降级方案
    const textArea = document.createElement('textarea')
    textArea.value = text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand('copy')
    document.body.removeChild(textArea)
  }

  tipShow.value = true
  setTimeout(() => {
    tipShow.value = false
  }, 2000)
}

// 更改邀请码
const confirmInvitationCode = () => {
  if (!invitationCode.value.trim()) {
    showWarning(t('please_enter_valid_invitation_code'))
    return
  }
}

// 获取我的邀请码
const apiGetMyInviteCode = async () => {
  const resCode = await getMyInviteCode()
  if (resCode.status && resCode.body) {
    myInviteInfo.value = resCode.body
  }
}

// 获取我的邀请人信息
const apiGetMyInviter = async () => {
  const resInviter = await getMyInviter()
  if (resInviter.status && resInviter.body) {
    myInviter.value = resInviter.body || {}
  }
}

// 绑定邀请码
const confirm = async () => {
  if (!invitationCode.value.trim()) {
    showWarning(t('please_enter_valid_invitation_code'))
    return
  }
  let data = { inviteCode: invitationCode.value.trim(), inviteType: 'REGISTER' }
  try {
    const resBind = await bindInviteCode(data)
    if (resBind.status) {
      showSuccess(t('invitation_code_bound_successfully'))
      apiGetMyInviter() //刷新我的邀请人信息
    } else {
      showError(t('invitation_code_binding_failed'))
    }
    invitationCode.value = ''
    enterCodeShow.value = false
  } catch (error) {
    showError(error.errorMsg)
  }
}

// 获取收益统计
const apiGetMyInviteIncome = async () => {
  const resIncome = await getMyInviteIncome()
  if (resIncome.status && resIncome.body) {
    myInviteIncome.value = resIncome.body
  }
}

// 有效邀请用户列表
const apiGetMyInviteUsers = async () => {
  const resUserList = await getMyInviteUsers()
  if (resUserList.status && resUserList.body) {
    myInviteUsers.value = resUserList.body
    // myInviteUsers.value = Array(2).fill(resUserList.body).flat()
    // myInviteUsers.value = []
  }
}

// 绑定用户奖励
const getBindingUserRewards = async () => {
  let data = ['1983474358707736577']
  const resAwardPool = await apiGetBindingUserRewards(data)
  if (resAwardPool.status && resAwardPool.body) {
    bindingUserRewards.value = resAwardPool.body['1983474358707736577']
  }
}

// 预加载关键图片
const preloadCriticalImages = async () => {
  const criticalImages = [
    imageUrl('bg'),
    imageUrl('enterCode'),
    imageUrl('enterCodeBg'),
    imageUrl('example'),
    imageUrl('helpInfo'),
    imageUrl('incomeBg'),
    imageUrl('listBg'),
    imageUrl('listBt'),
    imageUrl('listBtActive'),
    imageUrl('myCode'),
    imageUrl('privateChat'),
    imageUrl('processBt'),
    imageUrl('processBtActive'),
  ]

  const criticalImages_ar = [
    imageUrl('bg'),
    imageUrl('enterCode_ar'),
    imageUrl('enterCodeBg_ar'),
    imageUrl('example_ar'),
    imageUrl('helpInfo_ar'),
    imageUrl('incomeBg_ar'),
    imageUrl('listBg_ar'),
    imageUrl('listBt_ar'),
    imageUrl('listBtActive_ar'),
    imageUrl('myCode_ar'),
    imageUrl('privateChat_ar'),
    imageUrl('processBt_ar'),
    imageUrl('processBtActive_ar'),
  ]

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

// 页面初始化数据
const initData = async () => {
  await Promise.all([
    apiGetMyInviteCode(), // 获取我的邀请码
    apiGetMyInviter(), // 获取我的邀请人信息
    apiGetMyInviteIncome(), // 获取收益统计
    apiGetMyInviteUsers(), // 有效邀请用户列表
    getBindingUserRewards(), // 绑定用户奖励
  ])
}

// 完成预加载
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;
  background-color: #220c34;
  position: relative;
}

.overflow-y-auto {
  overflow-y: auto;
}

.overflow-y-auto::-webkit-scrollbar {
  display: none;
}

.leftBt {
  position: absolute;
  top: 75vw;
  left: 0;
  width: 100vw;

  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.bindingUserCode {
  width: 100%;
  padding-left: 3.5vw;
  padding-right: 5vw;
  height: 8vw;

  display: flex;
  justify-content: space-between;
}

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

  overflow: hidden;
  position: relative;
}

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

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

[dir='rtl'] .leftBt {
  align-items: flex-end;
}

[dir='rtl'] .bindingUserCode {
  padding-left: 5vw;
  padding-right: 3.5vw;
}
</style>
