<template>
  <div class="draw">
    <img class="draw-bg" :src="getAssets('zhuanpan/dzp_di.png')" />
    <div class="container">
      <img
        v-show="showBg"
        class="light"
        :src="getAssets('zhuanpan/light1.png')"
      />
      <img
        v-show="!showBg"
        class="light"
        :src="getAssets('zhuanpan/light2.png')"
      />
      <h-img
        type="local"
        width="2rem"
        class="xuanzhong"
        src="zhuanpan/zc.png"
      />
      <div class="dot flex-ct" @click="onDraw">
        <!-- <h-img width=".7rem" class="jiantou" src="turntable/jiantou.png" /> -->
        <img class="anniu" :src="getAssets('zhuanpan/anniu.png')" />
        <div class="num" v-if="showNumberVisible">
          <span>{{ number }}</span>
          <!-- <span class="txt">vezes</span> -->
        </div>
        <div class="animated-number" v-else>
          <div>+</div>
          <number-animation
            :from="0.0"
            :to="newNumber"
            :duration="1000"
            :precision="2"
            @finished="finished"
          />
        </div>
        <!-- <h-img width="1.9rem" src="turntable/sorteio.png" /> -->
      </div>
      <div class="xuanzhong2" ref="xuanzhongRef">
        <h-img type="local" src="zhuanpan/xz.png" />
      </div>
      <!-- 转盘主体 -->
      <div class="prize" ref="prizeRef" :style="bgColor">
        <div
          class="prize-item"
          v-for="(item, index) in prizeList"
          :key="index"
          :style="prizeStyle(index)"
        >
          <img
            class="icon"
            :src="getImage(item.displayUrl)"
            v-if="item.awardType !== TURNTABLE_AWARD_TYPE.COINS"
            :style="iconStyle(item)"
          />
          <span class="text" :style="textStyle(item)">
            {{ prizeValue(item) }}
          </span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive, onMounted, onUnmounted } from "vue";
import storage, { actions } from "@/utils/storage";
import { useRouter } from "vue-router";
import { useBaseStore } from "@/stores/modules/base";
import { getImage, getAssets } from "@/utils";
import { prizeValue } from "../utils";
import { TURNTABLE_AWARD_TYPE } from "@/enums/TURNTABLE_TYPE_ENUM";
import { toast } from "@/utils/toast";
import { showConfirmDialog } from "vant";
const baseStore = useBaseStore();
const router = useRouter();
const emit = defineEmits(["draw", "finished", "no-number"]);

const props = defineProps({
  number: { type: Number, default: 0, required: true },
  speed: { type: Number, default: 0, required: false },
});

const showNumberVisible = ref(true);

// 新金额
const newNumber = ref(0);
// 转盘ref
const prizeRef = ref();
// 选中动效
const xuanzhongRef = ref();

const showBg = ref(false);
const showBgTimer = ref();

const data = reactive<any>({
  baseRotate: 360 * 5,
  // 旋转度数
  rotate: 0,
  resetRotate: -90,
  numbers: 0,
  drawStatus: false,
  idx: -1,
});

const token = computed(() => storage.getStorage(actions.USER_TOEKN));

const prizeList = computed(() => {
  if (Object.keys(baseStore.turntableConfig).length) {
    return baseStore.turntableConfig.helpTurntable2List;
  }
  return [];
});

const rotateAngle = computed(() => {
  const _degree = 360 / prizeList.value.length;
  return _degree;
});

const bgColor = computed(() => {
  const _len = prizeList.value.length;
  const colorList = ["#cd762b", "#265b25"];
  let colorVal = "";
  for (let i = 0; i < _len; i++) {
    colorVal += `${colorList[i % 2]} ${rotateAngle.value * i}deg ${
      rotateAngle.value * (i + 1)
    }deg,`;
  }
  return `background: conic-gradient(${colorVal.slice(0, -1)});`;
});

const totalRunAngle = computed(() => {
  return (
    data.baseRotate +
    360 -
    data.idx * rotateAngle.value -
    rotateAngle.value / 2 +
    90
  );
});

const prizeStyle = computed(() => {
  const _degree = rotateAngle.value;
  return (i: any) => {
    return `transform: rotate(${_degree * i + _degree / 2}deg)`;
  };
});

const textStyle = computed(() => {
  return (item: any) => {
    switch (item.awardType) {
      case TURNTABLE_AWARD_TYPE.WITHDRAW:
        return "color:#6ae5bd";
      case TURNTABLE_AWARD_TYPE.COINS:
        return "color:#f9d96c";
    }
  };
});

const iconStyle = (item: any) => {
  switch (item.awardType) {
    case TURNTABLE_AWARD_TYPE.WITHDRAW:
      return `width:0.7rem;height:0.7rem;top: -0.35rem;`;
    case TURNTABLE_AWARD_TYPE.DIAMOND:
      return `width:1.1rem;height:.8rem;transform: rotate(-95deg);`;
    case TURNTABLE_AWARD_TYPE.TASK_COINS:
      return "right: .4rem; top: -0.35rem;";
    case TURNTABLE_AWARD_TYPE.NO_AWARD:
      return "right: .4rem; top: -0.45rem;";
    case TURNTABLE_AWARD_TYPE.FIRST_TASK_COINS:
      return "right: .4rem; top: -0.35rem;";
  }
};

// 开始旋转
const onDraw = async () => {
  if (!token.value) {
    router.push("/register");
    return;
  }
  if (props.speed == 100) {
    showConfirmDialog({
      title: "Prompt",
      message:
        "Parabéns por completar sua tarefa. Bem-vindos a voltar na próxima vez!",
      showCancelButton: false,
      confirmButtonText: "OK",
      confirmButtonColor: "#313160",
      width: "80%",
    });
    return;
  }
  if (!baseStore.turntableConfig.helpTurntable2Count) {
    emit("no-number");
    return;
  }
  if (data.drawStatus) {
    toast("In the lottery...");
    return;
  }
  data.drawStatus = true;
  // 获取选中数据
  await baseStore.getHelpTurntableResult();
  console.log(baseStore.turntableResult, "---------需要抽中数据");
  let id = baseStore.turntableResult.awardId;
  let index = prizeList.value.findIndex((i: any) => i._id == id);
  data.idx = index;
  xuanzhongRef.value.style.opacity = 0;
  startRun();
};
// 开始旋转方法
const startRun = () => {
  prizeRef.value.style.transition = "all 2s ease 0s";
  prizeRef.value.style.transform = `rotate(${totalRunAngle.value}deg)`;
  prizeRef.value.addEventListener("transitionend", stopRun, false);
};

// 抽奖完成
const stopRun = async () => {
  xuanzhongRef.value.classList.add("xz-active");
  // 获取旋转位置详情
  const currentPrize = prizeList.value.find(
    (i: any) => i._id == baseStore.turntableResult.awardId
  );
  // 未更新前老数据
  const myOldTask = {
    ...baseStore.turntableConfig.helpTurntable2TaskList?.rows[0],
  };
  console.log(currentPrize, "------选中位置详情");
  // 任务
  const taskNum = currentPrize.propsList[0].num / 10000;
  console.log(taskNum, "--------任务总金额");
  if (currentPrize.awardType == TURNTABLE_AWARD_TYPE.TASK_COINS) {
    console.log("-----------------更新转盘任务");
    // 未更新前进度
    const oldProgress = myOldTask.taskProgress;
    await baseStore.getHelpTurntable();
    // 更新后进度
    const newProgress =
      baseStore.turntableConfig.helpTurntable2TaskList?.rows[0].taskProgress;
    // 进度差
    const differ = newProgress - oldProgress;
    newNumber.value = (taskNum * differ) / 100;
    setShow(false);
  } else {
    // 如果非任务奖励
    await baseStore.getHelpTurntable();
    data.drawStatus = false;
  }
  // 如果初次旋转领取任务
  if (currentPrize.awardType == TURNTABLE_AWARD_TYPE.FIRST_TASK_COINS) {
    console.log("-----------------首次获取转盘任务");
    let preogress =
      baseStore.turntableConfig.helpTurntable2TaskList?.rows[0].taskProgress;
    newNumber.value = (taskNum * preogress) / 10000;
    setShow(false);
  }
  const rotate = totalRunAngle.value - data.baseRotate;
  prizeRef.value.style.transform = `rotate(${rotate}deg)`;
  prizeRef.value.style.transition = "";
  xuanzhongRef.value.classList.remove("xz-active");
  xuanzhongRef.value.style.opacity = 1;
  emit("draw");
};

const finished = () => {
  setTimeout(() => {
    setShow(true);
    data.drawStatus = false;
  }, 400);
  emit("finished");
};

const setShow = (status: boolean) => {
  showNumberVisible.value = status;
};

onMounted(() => {
  showBgTimer.value = setInterval(() => {
    showBg.value = !showBg.value;
  }, 500);
});

onUnmounted(() => {
  prizeRef.value &&
    prizeRef.value.removeEventListener("transitionend", stopRun);
  clearInterval(showBgTimer.value);
});

defineExpose({
  setShow,
});
</script>

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