<template>
  <div v-if="game && game.gameExt">
    <div class="bg-image-box">
      <img class="bg-image" :src="game.gameExt.backImageUrl" mode="widthFix" />
    </div>

    <div class="right-btn rule" @click="toGameRule">游戏规则</div>

    <div class="right-btn award" @click="toMyReward">我的奖品</div>

    <div class="content">
      <div
        class="music-icon iconfont"
        :class="isPlay ? 'icon-yinfu' : 'icon-xingzhuangjiehe2x'"
        @click="playMusic"
        v-if="game.backMusicFlag && game.gameExt.backMusicUrl"
      ></div>
      <div class="integral" v-if="(rule.giveawayType == 21 || rule.giveawayType == 22) && rule.giveawayNum">
        <div v-if="rule.giveawayType == 21">每天可有{{ rule.giveawayNum }}次免费参与次数</div>
        <div v-else-if="rule.giveawayType == 22">共有{{ rule.giveawayNum }}次免费参与次数</div>
      </div>
      <div class="integral" v-else-if="rule.integral && rule.inviteNum">
        {{ rule.integral || 0 }}积分/次或好友助力参与
      </div>
      <div class="integral" v-else-if="rule.integral">
        {{ rule.integral || 0 }}积分/次
      </div>
      <div class="integral" v-else-if="rule.inviteNum">邀请好友助力参与</div>

      <swiper
        class="swiper-class"
        ref="mySwiper"
        :options="swiperOptions"
        v-if="game.bulletFlag && barrageList && barrageList.length > 2"
      >
        <swiper-slide v-for="item in barrageList.length * 2" :key="item">
          <div
            class="swiper-item"
            v-if="item % 2 == 0 && barrageList[item / 2 - 1]"
          >
            <img src="./images/tips_bg.png" />
            <span
              >恭喜 {{ barrageList[item / 2 - 1].memberName }} 获得
              {{ barrageList[item / 2 - 1].prizeName }}</span
            >
          </div>
        </swiper-slide>
      </swiper>

      <div class="box-box">
        <img
          :class="{
            active: clickIndex == index,
            'animation-end': animationEnd,
          }"
          v-for="(item, index) in boxList"
          :key="item"
          :src="
            game.gameExt.prizeStyleList.length == 1
              ? game.gameExt.prizeStyleList[0].imageNoSelectUrl
              : game.gameExt.prizeStyleList[index].imageNoSelectUrl
          "
          :style="{ left: item.left, top: item.top }"
          @click="clickBox(index)"
        />
      </div>

      <div class="points-count-box">
        <div>
          <!-- 左边显示-右边次数显示且积分玩法开启才显示在左边 -->
          <div
            class="text-box"
            v-if="
              rule.integral && playNumberObj && playNumberObj.playNumberFlag
            "
          >
            <div class="text">{{ currentIntegral }}</div>
            <img class="text-shadow" src="./images/circle_bg.png" />
            <img class="title-image" src="./images/我的积分.png" />
          </div>
        </div>

        <img
          class="guide-img"
          :src="game.gameExt.noticeImageUrl"
          mode="widthFix"
        />
        <div>
          <div
            class="text-box number"
            v-if="playNumberObj && playNumberObj.playNumberFlag"
          >
            <div class="text">{{ playNumberObj.playNumber }}</div>
            <img class="text-shadow" src="./images/circle_bg.png" />
            <img class="title-image" src="./images/剩余次数.png" />
          </div>
          <div class="text-box" v-else-if="rule.integral">
            <div class="text">{{ currentIntegral }}</div>
            <img class="text-shadow" src="./images/circle_bg.png" />
            <img class="title-image" src="./images/我的积分.png" />
          </div>
        </div>

        <div class="share-box" @click.stop="clickShareBtn" v-if="rule.inviteNum">
          <div class="icon">
            <div class="iconfont icon-yaoqing"></div>
          </div>
          <img src="./images/邀请助力.png" />
        </div>
      </div>

      <img
        class="ad-image"
        :src="game.gameExt.adsImageUrl"
        mode="widthFix"
        @click="clickAdImg"
        v-if="game.adsFlag"
      />

    </div>

    <open-box-dialog
      :show.sync="showOpenBoxDialog"
      :title="openBoxTitle"
      :data="openBoxData"
      :isOpening="isOpening"
      @open="open()"
    ></open-box-dialog>
    <reward-dialog
      :show.sync="showRewardDialog"
      :reward="rewardDetail"
      @toMyReward="toMyReward"
    ></reward-dialog>
    <reward-fail-dialog :show.sync="showRewardFailDialog"></reward-fail-dialog>
    <share-select-dialog
      :show.sync="showShareSelectDialog"
      v-show="showShareSelectDialog"
      :memberId="memberId"
      :enterpriseId="enterpriseId"
      :gameId="gameId"
      :shareConditionObj="shareConditionObj"
      @shareWx="shareWx"
      @sharePyq="sharePyq"
    ></share-select-dialog>

    <share-img-dialog
      :show.sync="showShareImgDialog"
      v-bind="pyqOptions"
    ></share-img-dialog>

    <alert-dialog v-bind.sync="alertOptions"></alert-dialog>
  </div>
</template>

<script>
import { gameRequestApi } from "@/api/common.js";
const {
  getGameInfo,
  getGamePlayNumber,
  getGamePlayBarrage,
  getIntegral,
  getGameRule,
  saveGameShare,
  getGameShareQrCodeUrl,
  shareEvent,
} = gameRequestApi;

import { Swiper, SwiperSlide } from "vue-awesome-swiper";

import { Manager } from "../../manager";

import "swiper/css/swiper.css";

import OpenBoxDialog from "./components/open-box.vue";

import RewardDialog from "./components/reward-dialog.vue";
import RewardFailDialog from "./components/reward-fail.vue";
import ShareSelectDialog from "./components/share-select-dialog.vue";
import ShareImgDialog from "./components/share-img-dialog.vue";
import AlertDialog from "./components/alert.vue";
export default {
  components: {
    OpenBoxDialog,
    Swiper,
    SwiperSlide,
    RewardDialog,
    RewardFailDialog,
    ShareSelectDialog,
    ShareImgDialog,
    AlertDialog,
  },
  data() {
    return {
      clickIndex: -1,
      animationEnd: false,
      isOpening: false,
      showOpenBoxDialog: false,
      showRewardDialog: false,
      showRewardFailDialog: false,
      showShareSelectDialog: true,
      showShareImgDialog: false,
      shareConditionObj: {},
      alertOptions: {},
      barrageList: [],
      boxList: [
        {
          left: "calc(24.4% - 50px)",
          top: "212px",
        },
        {
          left: "calc(50% - 50px)",
          top: "212px",
        },
        {
          left: "calc(76.6% - 50px)",
          top: "212px",
        },
        {
          left: "calc(24.4% - 50px)",
          top: "320px",
        },
        {
          left: "calc(50% - 50px)",
          top: "320px",
        },
        {
          left: "calc(76.6% - 50px)",
          top: "320px",
        },
        {
          left: "calc(24.4% - 50px)",
          top: "428px",
        },
        {
          left: "calc(50% - 50px)",
          top: "428px",
        },
        {
          left: "calc(76.6% - 50px)",
          top: "428px",
        },
      ],
      swiperOptions: {
        direction: "vertical",
        loop: true,
        speed: 500,
        autoplay: {
          delay: 1000,
          stopOnLastSlide: false,
          disableOnInteraction: true,
        },
      },
      isPlay: false,
      name: "猜盲盒",
      game: {},
      gameId: "",
      enterpriseId: "",
      memberId: "",
      isAttest: 0,
      currentIntegral: "--",
      rule: {},
      playNumberObj: {},
    };
  },
  created() {
    this.manager = new Manager(this);
    let query = this.$route.query;
    this.gameId = query.gameId;
    this.enterpriseId = query.enterpriseId;
    this.memberId = query.memberId;
    this.isAttest = +query.isAttest;

    if (!this.audio) {
      this.audio = new Audio();
      this.audio.autoplay = true;
      this.audio.addEventListener(
        "ended",
        () => {
          if (this.isPlay) {
            this.audio.play();
          }
        },
        false
      );
      document.addEventListener("visibilitychange", () => {
        if (document.hidden) {
          this.isPlay = false;
          this.audio.pause();
        }
      });
    }
    this.getGame();
    this.getGameRule();
    this.getGamePlayNumber();
    this.getIntegral();
    this.getGamePlayBarrage();
    this.lookBuryPoint();
  },
  mounted() {
    this.manager.startPolling();
  },
  destroyed() {
    this.manager.stopPolling();
    this.audio.pause();
    document.removeEventListener("visibilitychange",()=>{});
  },
  methods: {
    lookBuryPoint() {
      let query = this.$route.query;
      if (query.memberId) {
        shareEvent({
          enterpriseId: query.enterpriseId || "",
          memberId: query.memberId || "",
          relationType: "game",
          relationId: query.gameId || "",
          event: 2,
        });
      }
    },
    async getGame() {
      let res = await getGameInfo({
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
      });

      document.title = res.gameName;
      res.gameExt.prizeStyleList = JSON.parse(
        res.gameExt.prizeStyleJson || "[]"
      );
      this.game = res;
      setTimeout(() => {
        this.animationEnd = true;
      }, 1000);
      this.audio.src = res.gameExt.backMusicUrl;

      if (this.isPlay) {
        this.audio.play();
      } else {
        this.audio.pause();
      }
    },
    async getGameRule() {
      let rule = await getGameRule({
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
      });
      let gameRuleConditionList = rule.gameRuleConditionList || [];
      gameRuleConditionList.map((item) => {
        let obj = JSON.parse(item.conditionJson);
        if (+obj.type == 11 || +obj.type == 12) {
          this.shareConditionObj = obj;
        }
      });
      this.rule = rule;
      window.wx.miniProgram.postMessage({
        data: {
          shareTitle: rule.shareRuleDesc,
          shareImage: rule.shareImageUrl,
        },
      });
    },
    async getGamePlayNumber() {
      let playNumberObj = await getGamePlayNumber({
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
        memberId: this.memberId || "",
      });
      this.playNumberObj = playNumberObj;
    },
    async getGamePlayBarrage() {
      let barrageList = await getGamePlayBarrage({
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
      });
      this.barrageList = barrageList || [];
    },
    async getIntegral() {
      let currentIntegral = await getIntegral({
        enterpriseId: this.enterpriseId,
        memberId: this.memberId,
      });
      this.currentIntegral = currentIntegral;
    },
    clickBox(index) {
      if (this.clickIndex != -1) {
        return;
      }
      this.clickIndex = index;
      setTimeout(() => {
        let prizeStyleList = this.game.gameExt.prizeStyleList;
        let itemIndex = prizeStyleList.length > index ? index : 0;
        let boxItem = prizeStyleList[itemIndex];
        this.showOpenBoxDialog = true;
        this.openBoxData = boxItem;
        if (this.playNumberObj.playNumber == 0 && this.rule.integral) {
          this.openBoxTitle = `每次参与游戏消耗${this.rule.integral}积分${
            this.playNumberObj.playNumberFlag ? "或参与次数" : ""
          }`;
        } else {
          this.openBoxTitle = "";
        }
      }, 900);
    },
    toGameRule() {
      this.$router.push({
        path: "/cmh/4/rule",
        query: this.$route.query,
      });
    },
    async toMyReward() {
      await this.manager.checkMyReward();
      this.$router.push({
        path: "/cmh/4/my-reward",
        query: this.$route.query,
      });
    },
    playMusic() {
      this.isPlay = !this.isPlay;
      if (this.isPlay) {
        this.audio.play();
      } else {
        this.audio.pause();
      }
    },
    async clickShareBtn() {
      await this.manager.checkPlay();
      this.showShareSelectDialog = true;
    },
    shareWx() {
      let options = this.shareConditionObj;
      let data = {
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
        memberId: this.memberId,
        shareType: 1,
      };
      saveGameShare(data).then(()=>{
        return getGameShareQrCodeUrl(data);
      }).then((result)=>{
        let linkId = result.linkId;

        this.manager.shareWx({
          title: options.shareTitle,
          imageUrl: options.shareCard,
          path: `/pages/page-transit/page-transit-qy?scene=${linkId}`,
        });
      }).catch((err)=>{
        this.manager.showTips(err.message);
      })
      
    },
    sharePyq() {
      let options = this.shareConditionObj;
      let data = {
        gameId: this.gameId,
        enterpriseId: this.enterpriseId,
        memberId: this.memberId,
        shareType: options.type == 12 ? 2 : 1,
      };
      saveGameShare(data).then(()=>{
        return getGameShareQrCodeUrl(data)
      }).then((result)=>{
        this.pyqOptions = {
          bgImage: options.shareReport,
          qrcodeUrl: result.qrCodeUrl,
        };
        this.showShareSelectDialog = false;
        this.showShareImgDialog = true;
      }).catch((err)=>{
        this.manager.showTips(err.message);
      })
    },
    clickAdImg() {
      window.wx.miniProgram.navigateTo({
        url: "/" + this.game.gameExt.adsLinkUrl,
      });
    },
    async open() {
      let gameRes = await this.manager.play();

      this.showOpenBoxDialog = false;
      // this.rewardDetail = {};
      if (gameRes.prizeType) {
        this.rewardDetail = gameRes;
        this.showRewardDialog = true;
      } else {
        this.showRewardFailDialog = true;
      }
      this.getGamePlayNumber();
      this.getIntegral();
    },
  },
  watch: {
    showOpenBoxDialog(n) {
      if (!n) {
        this.clickIndex = -1;
      }
    },
  },
};
</script>
<style>
body{
  margin: 0;
}
</style>
<style scoped>

.bg-image-box{
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  max-height: 100%;
  overflow: hidden;
}
.bg-image {
  width: 100%;
}
.content {
  position: relative;
  z-index: 1;
}

.music-icon {
  text-align: center;
  width: 30px;
  height: 30px;
  line-height: 30px;
  border-radius: 50%;
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 10;

  background: #0CC6DA;
  box-shadow: inset 0px 2px 1px 0px rgba(255, 255, 255, 0.5);
  color: white;
  font-size: 20px;
  /* transform: rotate(90deg); */
}

@keyframes transform {
  0% {
    transform: rotate(0%);
  }
  25% {
    transform: rotate(90deg);
  }
  50% {
    transform: rotate(180deg);
  }
  75% {
    transform: rotate(270deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.music-icon.icon-yinfu {
  animation-name: transform;
  animation-duration: 3s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.right-btn {
  text-align: center;
  position: fixed;
  right: 0px;
  top: 20px;
  padding: 7px 5px;
  line-height: 13px;
  width: 25px;
  box-sizing: border-box;
  border-radius: 8px 0 0 8px;
  background: #0CC6DA;
  z-index: 10;
  color: white;
  font-size: 11px;
  font-family: PingFangSC-Medium, PingFang SC;
  font-weight: 500;
  box-shadow: inset 2px 1px 1px 0px rgba(255, 255, 255, 0.5);
}

.right-btn.award {
  top: 89px;
}

.integral {
  position: absolute;
  z-index: 2;
  top: 126px;
  left: 50%;
  transform: translateX(-50%);
  min-width: 120px;
  height: 24px;
  line-height: 24px;
  text-align: center;
  padding: 0 10px;
  box-sizing: border-box;
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.8);
  color: black;
  font-size: 12px;
  font-weight: 500;
}

.swiper-class {
  position: absolute;
  left: 20px;
  top: 160px;
  z-index: 10;
  width: 300px;
  height: 36px;
}
.swiper-item {
  width: 300px;
  height: 36px;
  box-sizing: border-box;
  border-radius: 17px 0 0 17px;
  position: relative;
  display: flex;
  align-items: center;
}
.swiper-item img {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
}
.swiper-item span {
  padding-left: 30px;
  color: black;
  font-size: 12px;
  z-index: 2;
}

.box-box {
  height: 555px;
  width: 100%;
  position: relative;
}

@keyframes box-animation {
  from {
    transform: translate(0, -100px);
  }
  to {
    transform: translate(0, 0);
  }
}

@keyframes box-up-animation{
  0% {
    transform: translate(0, 0) scale(1);
  }
  100% {
    transform: translate(0, -50%) scale(1);
  }
}

@keyframes box-active-animation {
  0% {
    transform: translate(0, -50%) scale(1);
  }
  99% {
    transform: translate(-50%, -50%) scale(1.8);
    left: 50%;
    top: 346px;
    z-index: 10;
    opacity: 1
  }
  100% {
    transform: translate(-50%, -50%) scale(1.8);
    left: 50%;
    top: 346px;
    z-index: 10;
    opacity: 0;
  }
}
.box-box img {
  position: absolute;
  transform: translate(0, -100px);
  width: 95px;
  height: 95px;
  animation-timing-function: linear;
  animation-name: box-animation;
  animation-duration: 0.3s;
  animation-fill-mode: forwards;
  animation-iteration-count: 1;
}
.box-box img:nth-child(1) {
  animation-delay: 0.65s;
}
.box-box img:nth-child(2) {
  animation-delay: 0.6s;
}
.box-box img:nth-child(3) {
  animation-delay: 0.7s;
}
.box-box img:nth-child(4) {
  animation-delay: 0.5s;
}
.box-box img:nth-child(5) {
  animation-delay: 0.45s;
}
.box-box img:nth-child(6) {
  animation-delay: 0.55s;
}

.box-box img.animation-end {
  transform: translate(0, 0);
  animation: none;
}

.box-box img.active {
  animation-timing-function: linear, linear;
  animation-name: box-up-animation, box-active-animation;
  animation-duration: 0.3s, 0.3s;
  animation-fill-mode: forwards, forwards;
  animation-iteration-count: 1, 1;
  animation-delay: 0s, 0.4s;
}

.points-count-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 18px;
  position: relative;
  height: 57px;
}

.text-box {
  position: relative;
  text-align: center;
}
.text-box .text {
  font-family: DINAlternate-Bold, DINAlternate;
  font-size: 26px;
  font-weight: 600;
  color: black;
  line-height: 23px;
  position: relative;
  z-index: 2;
}

.text-box.number .text {
  font-size: 40px;
  line-height: 30px;
}

.text-box .text-shadow {
  position: absolute;
  left: 50%;
  top: 17px;
  transform: translateX(-50%);
  width: 41px;
  height: 8px;
  z-index: 1;
}

.text-box.number .text-shadow {
  top: 25px;
}

.text-box .title-image {
  padding-top: 5px;
  width: 48px;
  height: 16px;
}

.guide-img {
  width: 174px;
  height: 17px;
}

.ad-image {
  margin: 39px 15px 15px;
  border-radius: 8px;
  width: calc(100% - 30px);
}

.share-box {
  position: absolute;
  z-index: 10;
  right: 10px;
  bottom: -64px;
  padding: 10px;
}
.share-box .icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: #42B8E7;
box-shadow: inset 0px 2px 1px 0px #DEE9F5;
}
.share-box .icon .iconfont {
  color: #FAE3A7;
  font-size: 18px;
}
.share-box img {
  position: absolute;
  left: 50%;
  bottom: 0;
  width: 48px;
  height: 16px;
  transform: translateX(-50%);
  z-index: 2;
}
</style>
