<template>
  <div>
    <van-swipe
      ref="swipe"
      :touchable="false"
      :show-indicators="false"
      vertical
      indicator-color="white"
    >
      <van-swipe-item>
        <div style="width: 100%; overflow: hidden; position: relative">
          <transition name="fade">
            <div class="next" v-if="step === 5">
              <img
                @click="nextPage"
                src="../../../assets/img/next.png"
                style="width: 2em; display: block; margin: 0 auto"
              />
              <p style="font-size: 12px; text-align: center">
                获取你的新年好物
              </p>
            </div>
          </transition>
          <div class="six" :style="'background-image: url(' + bgimg + ')'">
            <img
              :src="kuangimg"
              :style="
                step === 2
                  ? 'opacity: 1'
                  : step >= 3
                  ? 'width: 25%;transform: translate(0, 0);opacity: 1; top: 1em; left: 1em'
                  : 'opacity: 0'
              "
              class="firstImg"
            />
            <transition name="fade">
              <div
                class="sImg img"
                v-if="step === 1"
                :style="'width:' + width + 'px;'"
              >
                <template v-for="(item, i) in text.texts" :key="i">
                  <p
                    v-text="item"
                    :style="
                      stepBody >= i
                        ? 'opacity: 1;color: ' + text.color
                        : 'color: ' + text.color
                    "
                  ></p>
                  <br />
                </template>
              </div>
            </transition>
            <transition name="fade">
              <div class="body" @click="changeNextStep" v-if="nextStep === 1">
                <div class="loading">
                  <div class="loading1">
                    <div class="loading2"></div>
                  </div>
                </div>
              </div>
            </transition>
            <img
              :src="text2img"
              :style="step >= 4 ? 'opacity: 1' : ''"
              class="tImg"
            />
            <transition name="fade">
              <div class="btns" v-if="step === 5">
                <div
                  class="btn"
                  @click="() => showDown(1)"
                  style="margin-left: 0"
                  :stype="'border-color:' + text.color + ';color:' + text.color"
                >
                  下载壁纸
                </div>
                <div
                  class="btn"
                  @click="() => showDown(2)"
                  :stype="'border-color:' + text.color + ';color:' + text.color"
                >
                  生成海报
                </div>
              </div>
            </transition>
          </div>
        </div>
      </van-swipe-item>
      <!-- <van-swipe-item style="overflow: auto">
        <div
          v-if="showSheet == 1"
          style="
            width: 100%;
            height: 100%;
            overflow: hidden;
            position: relative;
          "
        >
            <img
                @click="nextPage"
                src="../../../assets/img/next.png"
                class="next"
            />
          <seven />
        </div>
      </van-swipe-item> -->
      <van-swipe-item style="overflow: auto; height: 100vh">
        <eight
          ref="eightRef"
          @showTitleFunc="showTitleFunc"
          @showVideo="showVideo"
        />
      </van-swipe-item>
    </van-swipe>

    <transition name="fade">
      <div class="model" v-if="showImg !== undefined">
        <div class="gs">
          <img :src="bgimg" style="width: 100%; height: 100%" alt="" />
        </div>
        <van-icon
          color="#fff"
          size="26"
          name="close"
          class="close"
          @click="close"
        />
        <div class="modelImg">
          <p>请长按保存图片</p>
          <img :src="showImg" style="width: 100%; height: 100%" />
        </div>
      </div>
    </transition>

    <transition name="fade">
      <div v-if="showOverlay" class="model">
        <van-icon
          color="#fff"
          size="26"
          name="close"
          class="close"
          @click="closeSeven"
        />
        <video class="sevenvideo" src=""></video>
      </div>
    </transition>

    <van-dialog
      v-model:show="showTitle"
      title="登录后即可参与抽奖~"
      show-cancel-button
      :before-close="closeTitle"
    >
      <van-field
        required
        v-model="from.phone"
        label="联系方式"
        type="tel"
        placeholder="请输入手机号"
      >
        <template #button>
          <van-button
            v-if="isCode === 0"
            @click="getCode"
            size="small"
            type="primary"
            >获取验证码</van-button
          >
          <van-count-down
            v-if="isCode !== 0"
            @finish="isCode = 0"
            :time="isCode"
            format="ss 秒"
          />
        </template>
      </van-field>
      <van-field
        required
        v-model="from.code"
        label="验证码"
        type="tel"
        placeholder="请输入验证码"
      />
    </van-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, nextTick, defineEmits } from "vue";
import {
  getStore,
  getSendVerifyCode,
  getInfo,
  getDrawPlus,
} from "@/api/SilkRoadSpringGala.js";
import data from "../data/data.json";
import { showToast } from "vant";
// import seven from "./seven.vue";
import eight from "./eight.vue";

const from = reactive({
  name: "",
  phone: localStorage.getItem("silkRoadPhone"),
  code: "",
});

// import { onMounted, reactive } from "vue";
// import { isIpad, isIpod, isIphone } from "../../utils/isTerminal";
/**
 * window.$originData.orginParames.title 页面标题
 * window.$originData.orginParames.parameters 固定参数值
 * window.$originData.urlParames url参数
 */

const showImg = ref(undefined);
const swipe = ref(null);
let width = window.$originData.orginParames.availWidth * 0.7;
const type = Math.floor(Math.random() * 12 + 1);
let ori = data[type - 1] || {
  texts: [],
};
let max = 0;
const showTitle = ref(false);
for (let i = 0; i < ori.texts.length; i++) {
  max < ori.texts[i].length && (max = ori.texts[i].length);
}
width = 14 * max;
const url = {
  bg: require("@/assets/img/12/" + type + "-1.png"),
  bg2: require("@/assets/img/12/" + type + "-2.png"),
  kuang: require("@/assets/img/12/" + type + ".kuang.png"),
  text2: require("@/assets/img/12/" + type + ".text2.png"),
};
const text = reactive({
  ...data[type - 1],
  width,
});
const emits = defineEmits(["autoAudio"]);
const isCode = ref(0); // 验证码
const bgimg = ref(url.bg);
const kuangimg = ref(url.kuang);
const text2img = ref(url.text2);
const step = ref(0); // 动画步骤 默认0
const stepBody = ref(0); // 首页文字显示动画 默认0
const nextStep = ref(0);
const eightRef = ref(null);

// 如果有手机号获取用户信息
if (from.phone) {
  getInfo({
    phone: from.phone,
  }).then(r => {
    r.addr && localStorage.setItem("silkRoadAddress", r.addr);
    r.userName && localStorage.setItem("silkRoadName", r.userName);
  });
}
let t = setTimeout(() => {
  clearTimeout(t);
  step.value += 1;
  t = setInterval(() => {
    stepBody.value += 1;
    if (stepBody.value === text.texts.length) {
      nextStep.value = 1;
      clearInterval(t);
      t = setInterval(() => {
        nextStep.value === 2 && (step.value += 1);
        if (step.value === 5) clearInterval(t);
      }, 1000);
    }
  }, 1000);
}, 200);

function nextPage() {
  if (step.value !== 5) return;
  swipe.value.next();
}

function changeNextStep() {
  nextStep.value += 1;
}

function showTitleFunc() {
  showTitle.value = true;
  from.name = "";
  from.phone = "";
  from.code = "";
}

function getCode() {
  // 获取验证码
  if (!/1[0-9]{10}/.test(from.phone)) {
    showToast("请输入正确的手机号");
    return;
  }
  getSendVerifyCode({
    phone: from.phone,
  }).then(() => {
    isCode.value = 60000;
  });
}

function closeTitle(type) {
  if (type !== "confirm") return true;
  const v = !from.code || !from.phone;
  if (v) {
    showToast("请输入完整信息。");
    return false;
  }
  getStore({
    phone: from.phone,
    verifyCode: from.code,
  }).then(r => {
    localStorage.setItem("silkRoadPhone", from.phone);
    localStorage.setItem("silkRoadCode", from.code);
    localStorage.setItem("silkRoadName", from.name);
    localStorage.setItem("silkRoadToken", r.token);
    isCode.value = 0;
    showTitle.value = false;
    console.log(showTitle.value);
    // 调用子组件抽奖
    eightRef.value.draw();
  });
  return true;
}

function showDown(type) {
  switch (type) {
    case 1:
      showImg.value = url.bg;
      break;
    case 2:
      showImg.value = url.bg2;
      break;
  }
}

function close() {
  showImg.value = undefined;
}

// 视频播放
const showOverlay = ref(false);
let time = -1;
let autoTime = 0;
let current = 0;

function showVideo(url) {
  showOverlay.value = true;
  emits("autoAudio");
  nextTick(() => {
    let ele = document.querySelector(".sevenvideo");
    ele.src = url;
    ele.currentTime = 0;
    current = 0;
    time = -1;
    // 已经开始
    ele.addEventListener("playing", function () {
      time = Date.now();
      current = ele.duration * 1000;
    });
    // 当媒介能够开始播放但可能因缓冲而需要停止时运行脚本
    ele.addEventListener("canplay", endVideo, false);
    //播放结束
    ele.addEventListener(
      "ended",
      function () {
        console.log("ended");
        endVideo();
        closeSeven();
      },
      false
    );
    //暂停
    ele.addEventListener("pause", endVideo, false);
    ele.play();
  });
}

function closeSeven() {
  autoTime = Date.now() - time;
  if (autoTime / current <= 0.95)
    showToast({
      message: "温馨提醒：中途退出无法获取抽奖机会哦～",
      duration: 3000,
    });
  let ele = document.querySelector(".sevenvideo");
  ele.pause();
  emits("autoAudio");
  showOverlay.value = false;
}

function endVideo() {
  if (time == -1) return;
  const phone = localStorage.getItem("silkRoadPhone");
  autoTime = Date.now() - time;
  if (autoTime / current <= 0.95 || !phone) return;
  getDrawPlus({
    phone,
  }).then(() => {
    showToast("已增加一次抽奖机会！");
  });
}
</script>
<style lang="scss" scoped>
.six {
  width: 100%;
  height: 100vh;
  background-size: 100% 100%;
  position: relative;

  .body {
    position: absolute;
    bottom: 10vh;
    width: 100vw;
  }

  img,
  .img {
    width: 50%;
    transition-property: all;
    transition-duration: 2s;
    opacity: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .firstImg {
    transition-delay: 1s;
    -moz-transition-delay: 1s;
    /* Firefox 4 */
    -webkit-transition-delay: 1s;
    /* Safari 和 Chrome */
    -o-transition-delay: 1s;
    /* Opera */
  }

  .sImg {
    width: 70%;
    color: #ffffff;
    font-family: OPPOSans;
    font-size: 14px;
    line-height: 3em;
    opacity: 1;

    p {
      display: inline-block;
      white-space: nowrap;
      transition-property: all;
      transition-duration: 0.5s;
      opacity: 0;
    }
  }

  .tImg {
    width: 80%;
    transition-delay: 1s;
    -moz-transition-delay: 1s;
    /* Firefox 4 */
    -webkit-transition-delay: 1s;
    /* Safari 和 Chrome */
    -o-transition-delay: 1s;
    /* Opera */
  }

  .btns {
    position: absolute;
    text-align: center;
    bottom: 10vh;
    width: 100%;

    > div {
      display: inline-block;
      border: 1px solid #fff;
      border-radius: 2em;
      font-weight: 600;
      color: #fff;
      padding: 5px 15px;
      margin-left: 2em;
    }
  }

  .fade-enter-from,
  .fade-leave-to {
    opacity: 0;
  }

  .fade-enter-active,
  .fade-leave-active {
    transition: opacity 1s ease;
  }

  .fade-enter-to,
  .fade-leave-from {
    opacity: 1;
  }
}

.next {
  bottom: 40px;
  left: 50%;
  transform: translateX(-50%);
  top: inherit;
  width: 8em;
  color: #fff;
  z-index: 1;
  position: absolute;
  animation-name: an;
  animation-duration: 1s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

@keyframes an {
  from {
    bottom: 10px;
  }

  to {
    bottom: 15px;
  }
}

.model {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 10;
  background-color: #000000;

  .gs {
    width: 100vw;
    height: 100vh;
    filter: blur(10px);
    -webkit-filter: blur(10px);
  }

  .modelImg {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80%;
    text-align: center;
    color: #ffffff;
  }

  .close {
    position: absolute;
    top: 1em;
    right: 1em;
  }

  .sevenvideo {
    top: 50%;
    transform: translateY(-50%);
    width: 100%;
    position: absolute;
  }
}
</style>
