<template>
  <div>
    <!-- 规则&倒计时 -->
    <itemCenter
      style="min-height: 126.7vw"
      :imgUrl="webpUrl(getImgName('checkInRule'))"
      :contentStyle="`inset: 8vw 28vw 105vw;`"
    >
      <div class="timeBox">
        <div class="timeText" style="">{{ Days }}D</div>
        <div class="timeText timeGap"></div>
        <div class="timeText" style="">{{ Hours }}</div>
        <div class="timeText timeGap">:</div>
        <div class="timeText" style="">{{ Minutes }}</div>
        <div class="timeText timeGap">:</div>
        <div class="timeText" style="">{{ Seconds }}</div>
      </div>
    </itemCenter>

    <!-- 签到奖池列表 -->
    <div
      style="
        position: relative;
        padding: 0 2vw 4vw;
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 4vw;
      "
    >
      <signInItem
        v-for="(rewards, index) in signInInfo.dailyConfigs"
        :key="index"
        :rewards="rewards"
        :currentDayIndex="signInInfo.currentDayIndex"
        :style="getGridPosition(index)"
      />

      <!-- 箭头覆盖层 -->
      <div
        style="
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          pointer-events: none;
          z-index: 1;
        "
      >
        <!-- 根据签到项之间的关系绘制箭头 -->
        <img
          v-smart-img
          v-for="(arrow, arrowIndex) in arrows"
          :key="'arrow-' + arrowIndex"
          :src="webpUrl('arrowRight')"
          :style="arrow.style"
          alt="arrow"
          style="position: absolute; width: 8vw; object-fit: contain"
        />
      </div>
    </div>
  </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 { 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 { storeToRefs } from 'pinia'

import {
  apiGetMySignInStatus, // 获取我的签到状态
  apiPostMySignIn, // 执行签到
  apiPostMySignInSupplement, // 补签
} from '@/api/couple.js'

import itemCenter from '@/components/itemCenter.vue'
import signInItem from './signInItem.vue'

const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const coupleStore = useCoupleStore()
const {
  signInInfo, // 签到奖池
} = storeToRefs(coupleStore)

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 Days = ref(0)
const Hours = ref(0)
const Minutes = ref(0)
const Seconds = ref(0)
let countdownTimer = null

// 获取对应的时间戳
const getNextMondayInBeijing = () => {
  const now = new Date()
  const targetDate = new Date(now.getTime()) // 创建一个基于当前时间的新日期对象

  // 转换为北京时间来判断星期几
  const utcTime = now.getTime() + now.getTimezoneOffset() * 60000
  const beijingTime = new Date(utcTime + 8 * 3600000) // UTC+8

  const beijingDay = beijingTime.getDay() // 0=周日, 1=周一, ..., 6=周六
  const beijingHour = beijingTime.getHours()

  // 转换为 0=周一, 1=周二, ..., 6=周日
  const normalizedDay = beijingDay === 0 ? 6 : beijingDay - 1

  let daysToAdd
  if (normalizedDay === 0) {
    // 今天是周一
    if (beijingHour >= 5) {
      daysToAdd = 7 // 超过5点，计算到下周一的所需时间
    } else {
      daysToAdd = 0 // 今天
    }
  } else {
    daysToAdd = 7 - normalizedDay // 到下周一的天数
  }

  // 正确地添加天数
  targetDate.setDate(targetDate.getDate() + daysToAdd) // 添加天数到下周一的当前时间
  targetDate.setHours(5, 0, 0, 0) // 将时间重新设置为早上5点，作为目标时间戳

  return targetDate.getTime()
}

const targetTime = ref(getNextMondayInBeijing()) // 闭包保存目标时间 (核心修正)

// 格式化时间
const formatTime = (value) => {
  return value < 10 ? `0${value}` : value
}

// 倒计时
const getCountdown = () => {
  const now = Date.now()
  let diff = targetTime.value - now

  if (diff <= 0) {
    // 初始化数据
    initData()

    targetTime.value += 7 * 86400000 // +7天 (更新闭包变量)
    diff = targetTime.value - now
  }

  const totalSeconds = Math.floor(diff / 1000)
  Days.value = Math.floor(totalSeconds / (24 * 3600))
  Hours.value = formatTime(Math.floor((totalSeconds % (24 * 3600)) / 3600))
  Minutes.value = formatTime(Math.floor((totalSeconds % 3600) / 60))
  Seconds.value = formatTime(Math.floor(totalSeconds % 60))
}

// 启动倒计时
const startCountdown = () => {
  getCountdown() // 立即执行一次
  countdownTimer = setInterval(getCountdown, 1000)
}

// 签到奖池布局
const getGridPosition = (index) => {
  // 一周
  const positions = [
    { gridArea: '1/1' }, //1左
    { gridArea: '1/2' }, //1右
    { gridArea: '2/2' }, //2右
    { gridArea: '2/1' }, //2左
    { gridArea: '3/1' }, //3左
    { gridArea: '3/2' }, //3右
    { gridArea: '4/2' }, //4右
  ]
  return positions[index]
}

// 箭头配置数据
const arrows = computed(() => {
  const items = signInInfo.value?.dailyConfigs || []
  const arrowList = []

  // 为相邻的签到项之间添加箭头
  for (let i = 0; i < items.length - 1; i++) {
    // 检测是否为阿拉伯语环境
    const isRTL = currentLangType.value === 'ar'

    // 这是一个示例箭头位置配置，需要根据实际布局调整
    switch (i) {
      case 0: // 第1天 -> 第2天
        arrowList.push({
          style: isRTL
            ? 'top: 10.6%; right: calc(50%);transform: scaleX(-1) translateX(-50%)' // RTL 版本 - 位置改为right
            : 'top: 10.6%; left: calc(50%); transform: translateX(-50%);', // LTR 版本
        })
        break
      case 1: // 第2天 -> 第3天
        arrowList.push({
          style: isRTL
            ? 'top: calc(10.6% * 2 + 4.5vw); right: 70%; transform: scaleX(-1) rotate(90deg);' // RTL 版本 - 使用right
            : 'top: calc(10.6% * 2 + 4.5vw); left: 75%; transform: translateX(-50%) rotate(90deg);', // LTR 版本
        })
        break
      case 2: // 第3天 -> 第4天
        arrowList.push({
          style: isRTL
            ? 'top: calc(10.6% * 3 + 4.5vw + 5.5vw); right: 50%; transform: scaleX(-1) translateX(-50%) rotate(180deg);' // RTL 版本 - 使用right
            : 'top: calc(10.6% * 3 + 4.5vw + 5.5vw); left: 50%; transform: translateX(-50%) rotate(180deg);', // LTR 版本
        })
        break
      case 3: // 第4天 -> 第5天
        arrowList.push({
          style: isRTL
            ? 'top: calc(10.6% * 4 + 4.5vw * 2 + 4vw); right: 20%; transform: scaleX(-1)  rotate(90deg);' // RTL 版本 - 使用right
            : 'top: calc(10.6% * 4 + 4.5vw * 2 + 4vw); left: 25%; transform: translateX(-50%) rotate(90deg);', // LTR 版本
        })
        break
      case 4: // 第5天 -> 第6天
        arrowList.push({
          style: isRTL
            ? 'top: calc(10.6% * 5 + 4.5vw * 2 + 4vw * 2); right: 50%; transform: scaleX(-1) translateX(-50%);' // RTL 版本 - 使用right
            : 'top: calc(10.6% * 5 + 4.5vw * 2 + 4vw * 2); left: 50%; transform: translateX(-50%);', // LTR 版本
        })
        break
      case 5: // 第6天 -> 第7天
        arrowList.push({
          style: isRTL
            ? 'top: calc(10.6% * 6 + 4.5vw * 3 + 4vw * 2); right: 70%; transform: scaleX(-1)  rotate(90deg);' // RTL 版本 - 使用right
            : 'top: calc(10.6% * 6 + 4.5vw * 3 + 4vw * 2); left: 75%; transform: translateX(-50%) rotate(90deg);', // LTR 版本
        })
        break
    }
  }

  return arrowList
})

// 获取签到状态
const getSignInStatus = async () => {
  try {
    const response = await apiGetMySignInStatus()
    if (response.status) {
      signInInfo.value = response.body || {}
    }
  } catch (error) {
    console.error('Failed to get sign in status:', error)
    throw error
  }
}

// 页面初始化数据
const initData = async () => {
  await Promise.all([
    getSignInStatus(), // 获取签到状态
  ])
}

// 预加载关键图片
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()
  startCountdown() //开启倒计时
})

onUnmounted(() => {
  // 销毁计时器
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
})
</script>

<style lang="scss" scoped>
.timeBox {
  width: 50vw;
  display: flex;
  justify-content: center;
}

.timeText {
  color: #fff;
  font-weight: 590;
  font-size: 2em;
  margin-top: 1vw;

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

.timeGap {
  width: 6px;
  align-self: stretch;

  display: flex;
  justify-content: center;
  align-items: center;
}

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