<template>
  <view class="lotterypage">
    <!-- 返回按钮 -->
    <view class="nav-left">
      <image class="back-btn" src="@/assets/images/back-btn.png" mode="aspectFit"
             @click="handleBack"/>
    </view>

    <view class="lotterypageCon">
			<span class="lotterypagebg"
            :style="{ backgroundImage: `url(${config.images.background})` }"></span>

      <div class="lotterypageturntable">
				<span class="lotterypageturntablebg"
              :style="{ backgroundImage: `url(${config.images.turnTableBg})` }"></span>
        <span class="lotterypageturntablelogo"
              :style="{ backgroundImage: `url(${config.images.turnTableLogo})` }"></span>

        <div class="lotterypageturntableawards" :style="turntableRotationStyle">
          <div class="lotterypageturntableawards6" v-if="turntablePrizes.length > 5">
						<span class="lotterypageturntableawards6selbg"
                  v-if="isPrizeSelected(5) || isPrizeHighlighted(5)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards6img"
                   :src="`${$baseUrl}${turntablePrizes[5].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品6图片加载失败')"></image>
            <span class="lotterypageturntableawards6name">{{ turntablePrizes[5].prizeName }}</span>
          </div>
          <div class="lotterypageturntableawards5" v-if="turntablePrizes.length > 4">
						<span class="lotterypageturntableawards5selbg"
                  v-if="isPrizeSelected(4) || isPrizeHighlighted(4)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards5img"
                   :src="`${$baseUrl}${turntablePrizes[4].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品5图片加载失败')"></image>
            <span class="lotterypageturntableawards5name">{{ turntablePrizes[4].prizeName }}</span>
          </div>
          <div class="lotterypageturntableawards4" v-if="turntablePrizes.length > 3">
						<span class="lotterypageturntableawards4selbg"
                  v-if="isPrizeSelected(3) || isPrizeHighlighted(3)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards4img"
                   :src="`${$baseUrl}${turntablePrizes[3].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品4图片加载失败')"></image>
            <span class="lotterypageturntableawards4name">{{ turntablePrizes[3].prizeName }}</span>
          </div>
          <div class="lotterypageturntableawards3" v-if="turntablePrizes.length > 2">
						<span class="lotterypageturntableawards3selbg"
                  v-if="isPrizeSelected(2) || isPrizeHighlighted(2)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards3img"
                   :src="`${$baseUrl}${turntablePrizes[2].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品3图片加载失败')"></image>
            <span class="lotterypageturntableawards3name">{{ turntablePrizes[2].prizeName }}</span>
          </div>
          <div class="lotterypageturntableawards2" v-if="turntablePrizes.length > 1">
						<span class="lotterypageturntableawards2selbg"
                  v-if="isPrizeSelected(1) || isPrizeHighlighted(1)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards2img"
                   :src="`${$baseUrl}${turntablePrizes[1].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品2图片加载失败')"></image>
            <span class="lotterypageturntableawards2name">{{ turntablePrizes[1].prizeName }}</span>
          </div>
          <div class="lotterypageturntableawards1" v-if="turntablePrizes.length > 0">
						<span class="lotterypageturntableawards1selbg"
                  v-if="isPrizeSelected(0) || isPrizeHighlighted(0)"
                  :style="{ backgroundImage: `url(${config.images.lotterypageturntableawardsSelBg})` }"></span>
            <image class="lotterypageturntableawards1img"
                   :src="`${$baseUrl}${turntablePrizes[0].prizeImageUrl}`" mode="aspectFit"
                   @error="console.log('奖品1图片加载失败')"></image>
            <span class="lotterypageturntableawards1name">{{ turntablePrizes[0].prizeName }}</span>
          </div>
        </div>
      </div>

      <span class="lotterypagetitle"
            :style="{ backgroundImage: `url(${config.images.title})` }"></span>
      <span class="lotterypagerulebtn"
            :style="{ backgroundImage: `url(${config.images.ruleBtn})` }"
            @click="handleRuleClick"></span>
      <span class="lotterypageawardbtn"
            :style="{ backgroundImage: `url(${config.images.awardBtn})` }"
            @click="handleAwardClick"></span>

      <div class="lotterypagenoticecon">
				<span class="lotterypagenoticeconbg"
              :style="{ backgroundImage: `url(${config.images.noticeConBg})` }"></span>
        <div class="lotterypagenoticecontext-wrapper">
          <div class="lotterypagenoticecontext-container" :class="{ 'no-transition': isResetting }"
               :style="{ transform: `translateY(-${currentNoticeIndex * 40}rpx)` }">
            <p class="lotterypagenoticecontext" v-for="(notice, index) in displayNotices"
               :key="`${notice.userNickname}-${index}`" :style="{ top: `${index * 40}rpx` }">
              <span class="lotterypagenoticetext">{{ formatNotice(notice.userNickname, notice.prizeName) }}</span>
              <span class="lotterypagenoticetime">
                {{getDetailedHumanizedTimeDiff(notice.winningTime)}}
              </span>
            </p>
          </div>
        </div>
      </div>

      <span class="lotterypagedrawbtn"
            :style="{ backgroundImage: `url(${config.images.drawBtn})` }"
            @click="handleDrawClick" :class="{ 'disabled-draw-btn': !canDraw }"></span>
      <span class="lotterypagelefttimes">剩余次数：{{ remainingTimes }}</span>

      <!-- 规则弹窗 -->
      <RuleModal :visible="showRuleModal" :rules="activityRules" :config="ruleModalConfig"
                 @close="handleRuleModalClose"/>

      <GotPrizeModal ref="gotPrizeModalRef"/>
    </view>
  </view>
</template>

<script setup>
import {ref, onMounted, computed, getCurrentInstance, onUnmounted} from 'vue'
import {lotteryConfig} from './config.js'
import RuleModal from './components/ruleModal/ruleModal.vue'
import {lotteryDraw, fetchLotteryInfo, fetchLotteryConfig} from '../api.ts'
import md from '@/md.js'
import {jump, JumpType} from '@/utils/index.js'
import GotPrizeModal from "../components/GotPrizeModal.vue";
import {getDetailedHumanizedTimeDiff} from "../utils";

// 组件名称
defineOptions({
  name: 'LotteryPage'
})

// 响应式数据
const currentState = ref('normal') // 页面状态
const remainingTimes = ref(0) // 剩余抽奖次数
const currentNotice = ref('') // 当前公告
const turntablePrizes = ref([]) // 转盘奖品列表
const winningCarousel = ref([]) // 中奖轮播列表
const userWinningPrizes = ref([]) // 用户中奖记录
const currentNoticeIndex = ref(0) // 当前公告索引
const ruleModalConfig = ref({}) // 规则弹窗配置
const carouselTimer = ref(null) // 轮播定时器
const activityRules = ref('') // 活动规则内容
const isDrawing = ref(false) // 是否正在抽奖
const selectedPrizeIndex = ref(-1) // 当前选中的奖品索引
const currentHighlightIndex = ref(-1) // 当前高亮的奖品索引（用于轮流亮起效果）
const isResetting = ref(false) // 是否正在重置轮播位置

// 弹窗状态
const showRuleModal = ref(false) // 规则弹窗
const gotPrizeModalRef = ref()

// 配置对象
const config = lotteryConfig

// 获取$baseUrl
const instance = getCurrentInstance()
const $baseUrl = instance.proxy.$baseUrl

// 计算属性 - 是否可以抽奖
const canDraw = computed(() => {
  return remainingTimes.value > 0 && currentState.value === 'normal' && !isDrawing.value
})

// 转盘不需要旋转，保持静态
const turntableRotationStyle = computed(() => {
  return {
    transform: 'rotate(0deg)',
    transition: 'none'
  }
})

// 检查奖品是否被选中（用于最终结果）
const isPrizeSelected = (index) => {
  return selectedPrizeIndex.value === index
}

// 检查奖品是否正在高亮（用于轮流亮起效果）
const isPrizeHighlighted = (index) => {
  return currentHighlightIndex.value === index
}

// 获取最近的20条公告
const recentNotices = computed(() => {
  let notices = [];

  if (winningCarousel.value.length > 0) {
    notices = winningCarousel.value.slice(0, 20);
  } else {
    // 提供默认数据确保轮播能正常工作
    notices = [
      {userNickname: '用户1', prizeName: '奖品A'},
      {userNickname: '用户2', prizeName: '奖品B'},
      {userNickname: '用户3', prizeName: '奖品C'}
    ];
  }

  // 如果只有1条数据，复制成3条以确保轮播效果
  if (notices.length === 1) {
    const singleNotice = notices[0];
    notices = [singleNotice, singleNotice, singleNotice];
    console.log('轮播数据只有1条，已复制成3条:', notices);
  }

  return notices;
});

// 用于轮播显示的公告列表（重复数据以实现无缝循环）
const displayNotices = computed(() => {
  const notices = recentNotices.value;
  if (notices.length === 0) return [];

  // 重复数据以实现无缝循环
  return [...notices, ...notices];
});

// 格式化公告内容，限制为20个字符
const formatNotice = (nickname, prize) => {
  return `${nickname} 获得了 ${prize}`
};

// 返回按钮处理
const handleBack = () => {
  console.log('点击返回按钮')
  // md.sensorComponentLogTake({
  // 	xcxComponentClick: "true",
  // 	pageName: "1015专题活动页面",
  // 	componentName: "返回按钮",
  // 	componentContent: "返回"
  // });

  try {
    uni.navigateBack({
      delta: 1,
      success: () => {
        console.log('返回成功')
      },
      fail: () => {
        // 如果返回失败，跳转到首页
        uni.redirectTo({
          url: '/activities/1015/home'
        })
      }
    })
  } catch (error) {
    console.log('返回失败:', error)
    uni.redirectTo({
      url: '/activities/1015/home'
    })
  }
}

// 规则按钮点击处理
const handleRuleClick = () => {
  console.log('点击规则按钮')
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "1015专题活动页面",
    componentName: "抽奖板块",
    componentContent: "规则"
  });
  showRuleModal.value = true
}

// 规则弹窗关闭处理
const handleRuleModalClose = () => {
  showRuleModal.value = false
}

// 奖品按钮点击处理
const handleAwardClick = () => {
  console.log('点击奖品按钮')
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "1015专题活动页面",
    componentName: "抽奖板块",
    componentContent: "奖品"
  });
  // // 根据环境获取对应的appId
  // const getAppId = () => {
  // 	// 可以根据实际环境判断
  // 	// uat2: wxabebc35e71e66795
  // 	// test2: wx18428fc8a569a3c7
  // 	// 生产: wx4205ec55b793245e

  // 	// 这里可以根据实际需求调整环境判断逻辑
  // 	// 例如：根据域名、配置等判断当前环境
  // 	const currentEnv = 'prod' // 可以动态获取

  // 	const appIdMap = {
  // 		'uat2': 'wxabebc35e71e66795',
  // 		'test2': 'wx18428fc8a569a3c7',
  // 		'prod': 'wx4205ec55b793245e'
  // 	}

  // 	return appIdMap[currentEnv] || appIdMap['uat2'] // 默认uat2环境
  // }


  jump({
    type: JumpType.MINI,
    url: '/subPackages/xmhMainProcess/mine/index',
    extra: {
      appId: 'wx4205ec55b793245e',
      envVersion: 'release'
    }
  })

  // const appId = getAppId()
  // const path = '/subPackages/xmhMainProcess/mine/index'

  // uni.navigateToMiniProgram({
  // 	appId: appId,
  // 	path: path,
  // 	extraData: {},
  // 	envVersion: 'release', // 可以根据环境调整：develop, trial, release
  // 	success: (res) => {
  // 		console.log('跳转小程序成功:', res)
  // 	},
  // 	fail: (err) => {
  // 		console.error('跳转小程序失败:', err)
  // 		// uni.showToast({
  // 		// 	title: '跳转失败',
  // 		// 	icon: 'none'
  // 		// })
  // 	}
  // })
}


// 加载规则弹窗配置
const loadRuleModalConfig = async () => {
  try {
    console.log('开始请求 fetchAct1015LotteryJSON 接口...')
    const response = await fetchLotteryConfig()
    console.log('fetchAct1015LotteryJSON 接口返回结果:', response)

    if (response && response.ok && response.data) {
      ruleModalConfig.value = response.data
      console.log('规则弹窗配置加载成功:', ruleModalConfig.value)
    } else {
      console.warn('规则弹窗配置接口返回异常:', response)
    }
  } catch (error) {
    console.error('fetchAct1015LotteryJSON 接口请求失败:', error)
  }
}

// 加载抽奖信息
const loadLotteryInfo = async () => {
  try {
    console.log('开始请求 getAct1015LotteryInfo 接口...')
    const response = await fetchLotteryInfo()
    console.log('getAct1015LotteryInfo 接口返回结果:', response)

    if (response && response.ok) {
      remainingTimes.value = response.data.remainingChances
      turntablePrizes.value = response.data.turntablePrizes
      winningCarousel.value = response.data.winningCarousel
      userWinningPrizes.value = response.data.userWinningPrizes
      activityRules.value = response.data.activityRules || ''

      // 启动公告轮播（无论是否有API数据）
      startNoticeCarousel()
    } else {
      // uni.showToast({
      // 	title: response.msg || '获取抽奖信息失败',
      // 	icon: 'none'
      // })
      // 即使API失败也启动轮播
      startNoticeCarousel()
    }
  } catch (error) {
    console.error('getAct1015LotteryInfo 接口请求失败:', error)
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    })
    // 即使网络错误也启动轮播
    startNoticeCarousel()
  }
}

// 公告轮播
const startNoticeCarousel = () => {
  //return
  // 确保有数据可以轮播
  if (recentNotices.value.length > 0) {
    carouselTimer.value = setInterval(() => {
      currentNoticeIndex.value = currentNoticeIndex.value + 1
      //console.log('当前公告索引:', currentNoticeIndex.value)

      // 当滚动到重复数据的开始位置时，立即重置到原始位置（无动效）
      if (currentNoticeIndex.value >= recentNotices.value.length) {
        // 禁用过渡动效
        isResetting.value = true

        // 立即重置到原始位置
        currentNoticeIndex.value = 0

        // 下一帧恢复过渡动效
        setTimeout(() => {
          isResetting.value = false
        }, 100) // 确保重置完成
      }
    }, 3000) // 每3秒切换一次
  }
}

// 停止轮播
const stopNoticeCarousel = () => {
  if (carouselTimer.value) {
    clearInterval(carouselTimer.value)
    carouselTimer.value = null
  }
}


// 抽奖按钮点击处理
const handleDrawClick = async () => {
  md.sensorComponentLogTake({
    xcxComponentClick: "true",
    pageName: "1015专题活动页面",
    componentName: "抽奖板块",
    componentContent: "立即抽奖"
  });
  if (!canDraw.value) {
    uni.showToast({
      title: '抽奖次数已用完',
      icon: 'none'
    })
    return
  }

  console.log('开始抽奖')
  isDrawing.value = true
  selectedPrizeIndex.value = -1 // 重置选中状态
  currentHighlightIndex.value = -1 // 重置高亮状态

  // uni.showLoading({
  // 	title: '抽奖中...',
  // 	mask: true
  // })

  try {
    const response = await lotteryDraw()
    console.log('getAct1015LotteryDraw 接口返回结果:', response)

    if (response && response.ok) {
      remainingTimes.value = response.data.remainingChances

      // 根据接口返回的prizeId找到对应的奖品索引
      const prizeIndex = turntablePrizes.value.findIndex(prize => prize.prizeId === response.data.prizeId)

      console.warn("prizeIndex", prizeIndex)
      if (prizeIndex !== -1) {
        // 开始轮流亮起效果
        startHighlightAnimation(prizeIndex, response.data.isWin)
      } else {
        // 如果找不到对应奖品，显示失败
        // uni.hideLoading()
        isDrawing.value = false
        gotPrizeModalRef.show()
      }
    } else {
      // uni.hideLoading()
      isDrawing.value = false
      uni.showToast({
        title: response.msg || '抽奖失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('getAct1015LotteryDraw 接口请求失败:', error)
    uni.hideLoading()
    isDrawing.value = false
    uni.showToast({
      title: '网络错误，请稍后重试',
      icon: 'none'
    })
  }
}

// 轮流亮起动画
const startHighlightAnimation = (targetIndex, isWin) => {
  console.log(`开始轮流亮起动画，目标奖品索引: ${targetIndex}, 是否中奖: ${isWin}`)

  // 按照指定顺序：1 -> 5 -> 3 -> 2 -> 4 -> 6
  // 对应索引：0 -> 4 -> 2 -> 1 -> 3 -> 5
  const turntableOrder = [0, 4, 2, 1, 3, 5] // 按照指定顺序
  const totalPrizes = turntableOrder.length
  let currentOrderIndex = 0
  let roundCount = 0
  const maxRounds = 2 // 最多转2圈
  const highlightSpeed = 200 // 每个奖品高亮200ms

  const highlightTimer = setInterval(() => {
    // 获取当前转盘顺序中的奖品索引
    const currentPrizeIndex = turntableOrder[currentOrderIndex]
    currentHighlightIndex.value = currentPrizeIndex

    // 检查是否到达目标位置
    if (roundCount >= maxRounds && currentPrizeIndex === targetIndex) {
      clearInterval(highlightTimer)

      // 停止高亮，显示最终选中状态
      setTimeout(() => {
        currentHighlightIndex.value = -1
        selectedPrizeIndex.value = targetIndex
        uni.hideLoading()

        // 显示结果弹窗
        setTimeout(() => {
          isDrawing.value = false

          if (isWin) {
            const {prizeName, prizeImageUrl} = turntablePrizes.value[targetIndex]
            gotPrizeModalRef.value.show({
              prizeName,
              prizeImageUrl: $baseUrl + prizeImageUrl,
            })
          } else {
            gotPrizeModalRef.value.show({})
          }

          // 延迟重置选中状态
          setTimeout(() => {
            selectedPrizeIndex.value = -1
          }, 2000)
        }, 1000)
      }, highlightSpeed)
    } else {
      // 移动到下一个奖品（按转盘顺序）
      currentOrderIndex = (currentOrderIndex + 1) % totalPrizes

      // 如果回到起点，增加圈数
      if (currentOrderIndex === 0) {
        roundCount++
      }
    }
  }, highlightSpeed)
}

// 生命周期
onMounted(() => {
  console.log('抽奖页面已加载')
  loadRuleModalConfig() // 先加载规则弹窗配置
  loadLotteryInfo()

  md.sensorComponentLogTake({
    xcxComponentExposure: "true",
    pageName: "1015专题活动页面",
    componentName: "抽奖板块",
    componentContent: "规则、奖品、立即抽奖"
  });
})

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

<style lang="less" scoped>
@import 'index.less';
</style>
