<template>
  <ModalTransition class="lottery" :show="show" name="opacity" position="center">
    <div class="lottery-wrapper">
      <div class="guang" ref="guangRef"></div>
      <div class="guangyun" ref="guangyunRef"></div>
      <div class="lottery-scene" ref="sceneRef">
        <div class="lottery-card" ref="cardRef">
          <div class="lottery-prize" :style="prizeBackgroundImg">
            <div class="lottery-layer" ref="layerRef">

              
              <div class="lottery-mask-image" ref="maskBgRef" >
                <!-- 中奖 -->
                <div class="lottery-reveal lottery-image" v-if="activePrizeData.prize_code !== 'NO'">
                  <div class="lottery-image USER_LZ_ZQ_DZJ">
                    <div class="lottery-image prize-img" :class="'USER_' + activePrizeData.prize_code"></div>
                    <div class="lottery-name">{{ activePrizeData.prize_name }}</div>
                  </div>
                </div>
                <!-- 未中奖 -->
                <div class="lottery-reveal lottery-image" v-if="activePrizeData.prize_code === 'NO'">
                  <div class="lottery-image" :class="'USER_' + 'NO'"></div>
                </div>
              </div>

            </div>

            <div
              class="lottery-title-no"
              :class="props.type === 'notice' && 'notice'"
              ref="titleRef"
              v-if="btngroupShow && activePrizeData.prize_code === 'NO'"
            ></div>

            <div
              class="lottery-title"
              :class="props.type === 'notice' && 'notice'"
              ref="titleRef"
              v-if="btngroupShow && activePrizeData.prize_code !== 'NO'"
            ></div>

            <div class="lottery-btngroup" v-show="btngroupShow">
              <div class="btn-more" @click="navigateSharePage" v-if="activePrizeData.prize_code !== 'NO'"></div>
              <div class="btn-kaixin" @click="handleLotteryAction" v-if="activePrizeData.prize_code !== 'NO'"></div>
              <div class="back-home" @click="handleGoHomeAction" v-if="activePrizeData.prize_code === 'NO'"></div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </ModalTransition>
</template>

<script setup>
import { gsap } from "gsap";
import { ref, watch, onMounted, onUnmounted, computed } from "vue"
import globalToastEvent, { ToastType } from "../globalToastEvent";
import ModalTransition from "./ModalTransition.vue"
import confetti from "canvas-confetti";
import { Request, Sleep } from "../libs/utils"
import { globalStore } from "@/globalstore";

const navigateSharePage = () => {
  globalToastEvent.emit(ToastType.SHOW_SHAREPAGE, true)
}


// const lotteryFaceUrl = ref('')
const cardRef = ref(null)
const sceneRef = ref(null)
const guangRef = ref(null)
const guangyunRef = ref(null)
// 旧的 lotteryImageRef 仍保留（避免影响其他逻辑），但遮罩/揭晓现在用下面两个 ref
const lotteryImageRef = ref(null)
const maskBgRef = ref(null)
const layerRef = ref(null)
const revealRef = ref(null)
const titleRef = ref(null)
const activePrizeData = ref({})
const btngroupShow = ref(false)

const revealDone = ref(false)

gsap.registerPlugin()
const props = defineProps({
  show: false,
  type: "draw",
  data: null
})
const emit = defineEmits(['close'])

let interval = null
let gsapCtx = null
let PRIZEDATA = null

const closeThis = () => {
  initAnimateStyle()
  emit("close")
}

import noPrizeBg from '../assets/images/new/NO-prize-bg.webp';
import prizeBg from '../assets/images/new/lottery-bg.webp';

const prizeBackgroundImg = computed(() => {
  if (activePrizeData.value.prize_code === 'NO') {
    return `background-image: url("${noPrizeBg}")`
  } else {
    return `background-image: url("${prizeBg}")`
  }
})

// const handleBtnMore = () => {
//   closeThis()
//   globalToastEvent.emit(ToastType.SHOW_AD)
// }
const readNotice = async () => {
  await Request(`notice/read`, { id: activePrizeData.value.noticeId })
}
const handleLotteryAction = async () => {
  //实物
  // closeThis()
  globalToastEvent.emit(ToastType.CLOSE_ALL);
  if (props.type !== 'draw') {
    await readNotice()
  }
  if (activePrizeData.value.coupon_type === 'scene') {
    globalToastEvent.emit(ToastType.SHOW_ADDRESS, activePrizeData.value.id)
  }
}

const handleGoHomeAction = async () => {
  //实物
  closeThis()
  globalToastEvent.emit(ToastType.CLOSE_ALL);
  globalToastEvent.emit(ToastType.SHOW_POPUPMORE);
}

onMounted(() => {
  gsap.registerPlugin()
  // initAnimateStyle()
})

const initAnimateStyle = () => {
  interval && clearInterval(interval)
  interval = null

  let keyframes = [];
  const frames = 20; // 关键帧数量
  const strength = 5; // 抖动强度

  // 生成关键帧
  for (let i = 0; i < frames; i++) {
    keyframes.push({
      x: gsap.utils.random(-strength, strength),
      y: gsap.utils.random(-strength, strength),
      duration: 0.01 // 每帧的持续时间
    });
  }

  revealDone.value = false
  btngroupShow.value = false

  // 重置遮罩层/揭晓层的初始状态
  if (maskBgRef.value) {
    gsap.set(maskBgRef.value, { opacity: 1 })
  }
  // 以 50x50px 为起点（按你的假设），把变量放在容器上，便于同时驱动 reveal + 可视化 mask
  if (layerRef.value) {
    gsap.set(layerRef.value, { '--maskSize': '50px' })
  }
}

watch(() => props.show, async (newVal) => {
  if (!newVal) {
    return
  }

  const loading = weui.loading()
  let lottteryResult = null
  if (props.type === 'draw') {
    lottteryResult = await Request("lottery/draw", { pool: 'game', consume_type: 'points' })
    // 监听请求失败，关闭组件
    if (!lottteryResult || !lottteryResult.res || (lottteryResult.res.status !== 200 && lottteryResult.res.status !== 201)) {
      emit('close')
      loading.hide()
      return
    }
  } else {
    if (!props.data) {
      weui.alert("获取排名奖励出错，请刷新页面重试")
      emit('close')
      loading.hide()
      return
    }

    lottteryResult = {
      res: { status: 200 },
      json: {
        noticeId: props.data.id,
        id: props.data.data.prize.id,
        prize_code: props.data.data.prize.prize_code,
        prize_name: props.data.data.prize.name,
        coupon_type: props.data.data.prize.scene,
        rank: props.data.data.rank
      }
    }
  }

  // const userPicture = await getUserPicture()

  // const preimg = async() => {
  //   new Promise((resolve) => {
  //     const img = new Image()
  //     img.onload = () => resolve(img)
  //     img.src = userPicture
  //   })
  // }
  // await preimg()
  // lotteryFaceUrl.value = userPicture

  // TODO: 延时测试，上限删掉
  // await Sleep(20000)


  // TODO: 测试数据
  // lottteryResult = {
  //   res: { status: 200 },
  //   json: {
  //     id: 0,
  //     code: "xxx",
  //     // NOTE: 测试用，确保能命中现有的样式映射，便于看到揭晓效果
  //     prize_code: '52A6_100ML_6',
  //     prize_name: '泸州老窖国窖1573 55度双十耀星版500ml',
  //     coupon_type: "scene",
  //     name: "泸州老窖的一瓶酒"
  //   }
  // }

  loading.hide()

  if (lottteryResult.res.status !== 200) {
    emit('close')
    return
  } else {
    globalStore.lotteryCut()
    activePrizeData.value = lottteryResult.json

    // 未中奖的情况
    if (lottteryResult.json.code === 204) {
      activePrizeData.value = { prize_code: 'NO', coupon_type: 'NO' }
    }

    // kapianCover.value = PRIZEDATA.prize_code === '66_POINTS' ? 'POINTS' : PRIZEDATA.prize_code
  }

  gsapCtx = gsap.context(() => {
    initAnimateStyle()

    const prizeshowTime = gsap.timeline({
      onComplete: () => {
        btngroupShow.value = true
      }
    });

    prizeshowTime.to([sceneRef.value], {
      duration: 1.5,
      scale: 1,
      opacity: 1,
      ease: "power4.inOut"
    })

    // 中奖揭晓：先显示 2 秒，再用更慢、线性的放大过程（更清晰地看到“逐渐放大”）
    if (layerRef.value) {
      // 保证起始大小（50x50px）
      gsap.set(layerRef.value, { '--maskSize': '50px' })

      // 先停留 2 秒，让用户看清初始“窗口”
      // prizeshowTime.to({}, { duration: 0.5 })

      // 再逐渐放大到 50 倍（2500px）
      prizeshowTime.to(layerRef.value, {
        duration: 5.0,
        ease: "none",
        '--maskSize': '2500px',
        onComplete: () => {
          revealDone.value = true
          // 动画结束后把遮罩背景淡出，让中奖图完全可见
          maskBgRef.value && gsap.to(maskBgRef.value, { duration: 0.3 })
        }
      })
    }

    // 兼容旧动画（如果外部还在依赖 lotteryImageRef）
    if (lotteryImageRef.value) {
      prizeshowTime.to(lotteryImageRef.value, {
        duration: 1,
        scale: 1,
        ease: "power4.inOut"
      }, "-=1.5")
    }

    prizeshowTime.to(guangyunRef.value, {
      duration: 1.5,
      scale: 2,
    }, "-=1")

    prizeshowTime.to(titleRef.value, {
      scaleY: 1,
      ease: "elastic.out(1,0.3)"
    })

    var duration = 4 * 1000;
    var animationEnd = Date.now() + duration;
    var defaults = { startVelocity: 30, spread: 360, ticks: 60, zIndex: 0 };

    function randomInRange (min, max) {
      return Math.random() * (max - min) + min;
    }

    interval = setInterval(function () {
      var timeLeft = animationEnd - Date.now();

      if (timeLeft <= 0) {
        return clearInterval(interval);
      }

      var particleCount = 50 * (timeLeft / duration);
      confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.1, 0.3), y: Math.random() - 0.2 } });
      confetti({ ...defaults, particleCount, origin: { x: randomInRange(0.7, 0.9), y: Math.random() - 0.2 } });
    }, 250);

  })
})

onUnmounted(() => {
  gsapCtx && gsapCtx.revert()
})
</script>

<style scoped>
.lottery-layer {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);

  /* 叠加区域尺寸：按需求宽度 80vw，并水平/垂直居中 */
  width: 80vw;
  height: 80vw;
  max-height: 80vh;
}

/* 中层遮罩背景（默认完全盖住中奖图） */
.lottery-mask-image {
  height: 110vw;
  width: 82vw;
  margin-top: -30vw;
  position: absolute;
  inset: 0;
  background-image: url("../assets/images/new/lottery-mask-bg.webp");
  background-repeat: no-repeat;
  /* 保持图片比例：区域 80vw 内居中显示 */
  background-size: contain;
  background-position: center;
  z-index: 2;
}

/* 底层/顶层复用：中奖图 */
.lottery-image {
  height: 110vw;
  width: 82vw;
  position: absolute;
  inset: 0;
  background-position: center;
  background-repeat: no-repeat;
  /* 保持图片比例：区域 80vw 内居中显示 */
  background-size: contain;
  z-index: 1;
}

/* 顶层：通过 mask-img.webp 露出中奖图，并放大 mask 直到全露出 */
.lottery-reveal {
  z-index: 3;

  /* CSS Mask（WebKit + 标准） */
  -webkit-mask-image: url("../assets/images/new/mask-img.webp");
  -webkit-mask-repeat: no-repeat;
  -webkit-mask-position: center;
  -webkit-mask-size: var(--maskSize) var(--maskSize);

  mask-image: url("../assets/images/new/mask-img.webp");
  mask-repeat: no-repeat;
  mask-position: center;
  mask-size: var(--maskSize) var(--maskSize);
  /* -webkit-clip-path: circle(calc(var(--maskSize) * 0.5) at 50% 50%);
  clip-path: circle(calc(var(--maskSize) * 0.5) at 50% 50%); */
}

/* 可视化的 mask-img.webp：让用户能看到“遮罩在放大”的过程 */
.lottery-mask-visual {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: var(--maskSize);
  height: var(--maskSize);
  /* background-image: url("../assets/images/new/mask-img.webp"); */
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  z-index: 4;
  pointer-events: none;
}

.lottery-reveal.reveal-done {
  -webkit-clip-path: none;
  clip-path: none;
}

.lottery-mask-visual.reveal-done {
  opacity: 0;
}

/* 动画结束后：移除 mask，避免某些机型在超大 mask-size 时渲染抖动 */
.lottery-reveal.reveal-done {
  -webkit-mask-image: none;
  mask-image: none;
}

.lottery-image.USER_LZ_ZQ_DZJ {
  background-image: url("../assets/images/new/zhongjiang-bg.webp");
}

.lottery-image.USER_GJ1573_55_SSYX {
  background-image: url("../assets/images/new/USER_GJ1573_55_SSYX.webp");
}

.lottery-image.USER_QLL_WQSBLH {
  background-image: url("../assets/images/new/USER_QLL_WQSBLH.webp");
}

.lottery-image.USER_HYJJ {
  background-image: url("../assets/images/new/USER_HYJJ.webp");
}

.lottery-image.USER_43I1_100ML {
  background-image: url("../assets/images/new/USER_43I1_100ML.webp");
}

.lottery-image.USER_43A2_100ML_6 {
  background-image: url("../assets/images/new/USER_43A2_100ML_6.webp");
}

.lottery-image.USER_43A6_100ML_6 {
  background-image: url("../assets/images/new/USER_43A6_100ML_6.webp");
}

.lottery-image.USER_52A6_100ML_6 {
  background-image: url("../assets/images/new/USER_52A6_100ML_6.webp");
}

.lottery-image.USER_NO {
  background-position: center center;
  background-image: url("../assets/images/new/USER_NO.webp");
}

.guang,
.guangyun {
  position: absolute;
  left: 50%;
  margin-left: -66.2vw;
  top: 50%;
  margin-top: -64.5vw;
  width: 129.62963vw;
  height: 129.62963vw;
  background-repeat: no-repeat;
  background-size: 100%;
}

.guang {
  background-image: url("../assets/images/guang.webp");
  animation: rotateGuang 20s linear infinite;
}


.guangyun {
  background-image: url("../assets/images/guangyun.webp");
  /* animation: rotateGuangyun 3s linear infinite; */
}

.lottery-title {
  position: absolute;
  top: 24vw;
  left: 50%;
  transform: translateX(-50%) !important;
  width: 65.462963vw;
  height: 19.907407vw;
  background-image: url("../assets/images/new/lottery-title.webp");
  background-repeat: no-repeat;
  background-size: 100%;
  z-index: 10;
}

.lottery-title-no {
  position: absolute;
  top: 24vw;
  left: 50%;
  transform: translateX(-50%) !important;
  width: 40vw;
  height: 20vw;
  background-image: url("../assets/images/new/no-lottery-title.webp");
  background-repeat: no-repeat;
  background-size: 100%;
  z-index: 10;
}

.lottery-title.notice {
  width: 39.259259vw;
  height: 7.12963vw;
  background-image: url("../assets/images/notice-title.webp");
}

.lottery-desc {
  position: absolute;
  top: 32vw;
  left: 50%;
  transform: translateX(-50%) !important;
  width: 81vw;
  font-size: 5vw;
  font-weight: 700;
  text-align: center;
  color: rgb(255, 255, 255);
  text-shadow:
    0 0 0.37037vw #ff0000,
    0 0 0.740741vw #ff0000,
    0 0 1.111111vw #ff0000,
    0.092593vw 0.092593vw 0 #ff0000,
    -0.092593vw -0.092593vw 0 #ff0000;
}

.lottery-name {
  position: absolute;
  bottom: 8vw;
  text-align: center;
  width: 80%;
  left: 10%;
  font-size: 4.3vw;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 700;
  color: rgb(255, 255, 255);
  text-shadow:
    0 0 0.37037vw #ff0000,
    0 0 0.740741vw #ff0000,
    0 0 1.111111vw #ff0000,
    0.092593vw 0.092593vw 0 #ff0000,
    -0.092593vw -0.092593vw 0 #ff0000;
}

.lottery-btngroup {
  position: absolute;
  bottom: 56vw;
  width: 100%;
  display: flex;
  justify-content: space-evenly;
  z-index: 10;
}

.btn-more {
  width: 48.703704vw;
  height: 18.240741vw;
  background-image: url("../assets/images/new/share-btn.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}

.btn-kaixin {
  width: 48.703704vw;
  height: 18.240741vw;
  background-image: url("../assets/images/new/btn-kaixin.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}

.back-home {
  width: 48.703704vw;
  height: 18.240741vw;
  background-image: url("../assets/images/new/back-home.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}


@keyframes rotateGuangyun {
  0% {
    transform: scale(.3);
    opacity: 0;
  }

  50% {
    transform: scale(1);
    opacity: 1;
  }

  100% {
    transform: scale(1.4);
    opacity: 0;
  }
}

@keyframes rotateGuang {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(-360deg);
  }
}

.lottery-scene {
  position: relative;
  width: 88.055556vw;
  height: 148.796296vw;
}

.lottery-card {
  position: absolute;
  width: 100%;
  height: 100%;

  top: -14vw;
}


.lottery-face {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  backface-visibility: hidden;
}

.lottery-card img {
  width: 100%;
  display: block;
}

.lottery-prize {
  position: absolute;
  /* top: 0;
  left: 0;
  width: 100%;
  height: 100%; */
  top: -20vw;
  left: -6vw;
  width: 100vw;
  height: 244vw;
  /* background-image: url("../assets/images/new/lottery-bg.webp"); */
  /* background-image: url("../assets/images/new/NO-prize-bg.webp"); */
  background-repeat: no-repeat;
  background-size: 100%;
}

.close {
  position: absolute;
  width: 8.148148vw;
  height: 8.055556vw;
  right: 5vw;
  top: 0;
  background-image: url("../assets/images/icon-close.webp");
  background-repeat: no-repeat;
  background-size: 100%;
}
.prize-img {
  width: 45vw;
  height: 50vw;
  top: 25vw;
  left: 18vw;
}
</style>