<template>
  <div id="active-detail">
    <img class="bg" src="../../../public/img/activeDetail_bg.jpg" alt="bg" />
    <template v-if="active_type === 'coupon'">
      <div class="coupon">
        <div class="user-icon">
          <img :src="userIcon" alt="icon" />
        </div>
        <p class="slogan">送你限量优惠券，手慢无～</p>
        <div class="coupon-content">
          <img src="../../../public/img/coupon.png" alt="coupon_bg" />
          <div class="content">
            <div class="money">{{ couponDetail.unit }}元</div>
            <div class="split">
              <img src="../../../public/img/split.png" alt="split" />
            </div>
            <div class="other">
              <p>满{{couponDetail.salesUnit}}元可用</p>
              <p>
                有效期至：
                <span style="font-size: 12px;">{{ couponDetail.end_date }}</span>
              </p>
              <p>{{ couponDetail.deptId }}号店通用</p>
            </div>
          </div>
        </div>
        <div class="btn" @click="handleGet">立即领取</div>
      </div>
    </template>
    <template v-if="active_type === 'wheel'">
      <div class="wheel-container">
        <p class="title">{{ activityName }}</p>
        <div class="wheel">
          <div class="wheel-point" @click="Start_Game">开始</div>
          <img src="../../../public/img/wheel.png" alt="wheel" />
          <!-- <div class="circle"></div> -->
          <div
            class="wheel-bg"
            :class="{freeze: freeze}"
            :style="`transform: rotate(${wheelDeg}deg)`"
          >
            <div class="prize-list">
              <div class="prize-item-wrapper" v-for="(item,index) in prizeList" :key="index">
                <div
                  class="prize-item"
                  :style="`transform: rotate(${(360/ prizeList.length) * index }deg)`"
                >
                  <div class="prize-name">{{ item.prizeName }}</div>
                  <div class="prize-icon">
                    <!-- <p>一等奖</p> -->
                    <!-- <img src="/img/counter.png" /> -->
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="awards">
          <van-field
            class="area"
            v-model="prizeDesc"
            rows="2"
            autosize
            type="textarea"
            show-word-limit
            :disabled="true"
          />
        </div>
        <div class="time-line">
          距离结束仅剩
          <span id="timer"></span>
        </div>
        <div class="description">
          <div class="t">活动介绍</div>
          <div class="content">{{ des }}</div>
        </div>
      </div>
    </template>
    <div
      class="btn-share"
      :style="active_type === 'coupon'? 'bottom: 0': ''"
      @click="handleShare"
    >立即分享</div>
    <van-overlay :show="showAward" @click="showAward = false">
      <div class="wrapper">
        <div v-if="isAward" class="block">
          <div class="award-coupon">
            <img class="bg_img" src="/img/coupon.png" alt="coupon" />
            <div class="other">
              <p>{{ awardGood.coupon.type }}</p>
              <!-- <p>代金券</p> -->
              <div class="split">
                <img src="../../../public/img/split.png" alt="split" />
              </div>
              <p>{{ awardGood.coupon.unit }}元</p>
              <!-- <p>2000元</p> -->
            </div>
          </div>
          <p style="font-size: 20px;font-weight: bold;">OLAY全场通用抵扣券</p>
          <p style="font-size: 20px;font-weight: bold;">{{ awardGood.prizeName }}！</p>
          <p style="font-size: 20px;font-weight: bold;">恭喜您中奖！</p>
          <van-button style="background: #f00;color: #fff;" @click="handleGet">领取奖品</van-button>
          <van-button style="border-color: #7f7777;" @click="handleGoOn">继续抽奖</van-button>
        </div>
        <div v-else class="block" style="background: #413d3de0;color: #fff;">
          <p style="font-size: 22px;">谢谢惠顾！</p>
          <p style="font-size: 14px;">很遗憾，此次未能中奖，再接再厉！</p>
        </div>
      </div>
    </van-overlay>
    <wx-auth :show-auth="showAuthDialog" @confirm="handleCheckAuth"></wx-auth>
  </div>
</template>

<script>
import axios from "axios";
import wxAuth from "@/components/wxAuth";
import * as APi_Active from "@/api/active";
import { CoutDown } from "@/utils/Foundation";
import { Dialog } from "vant";
export default {
  name: "active-detail",
  components: { wxAuth },
  data() {
    return {
      goOn: false,
      env: "",
      userIcon: "/img/photo.png",
      couponDetail: {},
      game_end: false,
      timer: null,
      timeLine: "",
      isAward: false,
      showAward: false,
      userBaseInfo: {},
      isMember: false,
      openid: "",
      unionid: "",
      userIds: [],
      currentUrl: "",
      showAuthDialog: false,
      nowUrl: "",
      userId: "",
      code: "",
      active_id: "",
      active_type: "coupon",
      freeze: false,
      rolling: false,
      wheelDeg: 0,
      prizeNumber: 6,
      prizeListOrigin: [
        {
          name: "奖0",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        },
        {
          name: "奖1",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        },
        {
          name: "奖2",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        },
        {
          name: "奖3",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        },
        {
          name: "奖4",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        },
        {
          name: "奖5",
          icon:
            "http://wuhanshangcheng.oss-cn-beijing.aliyuncs.com/shangchengnormal/7E4C1866C2874AA5A788B5E59630A7ED.png"
        }
      ],
      activityName: "",
      prizeDesc: "",
      des: "",
      awardGood: {
        prizeName: ""
      }
    };
  },
  async created() {
    this.currentUrl = location.href;
    this.active_id = this.$route.query.id;
    this.active_type = this.$route.query.active_type;
    this.userIcon = this.$route.query.headurl
      ? decodeURIComponent(this.$route.query.headurl)
      : "";
    this.env = window.navigator.userAgent.toLowerCase();

    // 微信端才做验证
    if (
      this.env.match(/MicroMessenger/i) !== "micromessenger" ||
      this.env.match(/wxwork/i) == "wxwork"
    ) {
      // 1.获取code
      if (this.$route.query.unionid === undefined) {
        this.getUnionid();
      } else {
        this.userBaseInfo.unionid = JSON.stringify(this.$route.query.unionid);
        this.userBaseInfo.openid = JSON.stringify(this.$route.query.openid);
        let params = {
          number: 7,
          unionId: this.$route.query.unionid
        };
        //TODO 会员验证提示
        APi_Active.isMember(params).then(res => {
          if (res.data.errMessage === "会员不存在") {
            this.isMember = false;
            Dialog.confirm({
              title: "提示",
              message:
                "当前活动为会员才可参加，尚未找到您的会员信息，是否前往注册？"
            })
              .then(() => {
                // on confirm
                let url = "http://oysales.oywanhao.com/register";
                window.location.href = url;
              })
              .catch(() => {
                // on cancel
                return false;
              });
          }
          this.isMember = true;
          this.userBaseInfo.vipId = res.data.vipId;
          this.userBaseInfo.mobile = res.data.mobile;
          this.userBaseInfo.name = res.data.name;
        });
      }
    }
  },
  mounted() {
    this.getAgentAuth();
    this.GET_DetailById(this.active_id);
  },
  watch: {
    prizeNumber() {
      this.freeze = true;
      this.wheelDeg = 0;

      setTimeout(() => {
        this.freeze = false;
      }, 0);
    }
  },
  computed: {
    prizeList() {
      return this.prizeListOrigin.slice(0, this.prizeNumber);
    }
  },
  methods: {
    // 继续抽奖
    handleGoOn() {
      this.goOn = true;
      this.showAward = false;
    },
    // 领取(
    handleGet() {
      if (
        this.env.match(/MicroMessenger/i) !== "micromessenger" ||
        this.env.match(/wxwork/i) == "wxwork"
      ) {
        this.$toast("请在微信端领取！");
        return false;
      }
      // 会员领取
      let params = {
        couponId: this.awardGood.activityPrize
          ? this.awardGood.coupon.id
          : this.couponDetail.id,
        unionId: this.userBaseInfo.unionid,
        vipId: this.userBaseInfo.vipId
      };
      APi_Active.collectMyCoupon(params).then(res => {
        this.showAward = false;
        if (res.data == "领取失败") {
          this.$toast("领取失败");
          return false;
        }
        if (!this.goOn) {
          this.$toast(
            "领取成功！奖品已经发送到您的会员账户，请进入欧亚小程序查看。"
          );
        }
      });
    },
    GET_DetailById(id) {
      APi_Active.getActiveDetailById(id).then(res => {
        this.activityName = res.data.activityInfo.activityName;
        this.des = res.data.activityInfo.des;
        this.prizeDesc = res.data.activityInfo.prizeDesc;
        let time = res.data.activityInfo.endTime;
        this.timeLine =
          `${time.substring(0, 4)}-${time.substring(4, 6)}-${time.substring(
            6,
            8
          )}` + time.substring(8);
        this.prizeListOrigin = res.data.list;
        this.prizeNumber = res.data.list.length;
        if (this.active_type === "coupon") {
          let time2 = res.data.coupon.end_date;
          res.data.coupon.end_date =
            `${time2.substring(0, 4)}-${time2.substring(
              4,
              6
            )}-${time2.substring(6, 8)}` + time2.substring(8);
          this.couponDetail = res.data.coupon;
        }
        if (this.active_type === "wheel") {
          let cur_date = new Date();
          let end_time = new Date(this.timeLine.replace(/-/g, "/"));
          if (end_time > cur_date) {
            this.timer = setInterval(() => {
              CoutDown(this.timeLine);
            }, 1000);
          } else {
            document.getElementById("timer").innerHTML = "已结束";
            this.game_end = true;
          }
        }
      });
    },
    handleCheckAuth() {
      this.showAuthDialog = false;
    },
    getUnionid() {
      let redirect_uri = encodeURIComponent(
        `oysales.oywanhao.com:8087/activeDetail?id=${this.active_id}&active_type=${this.active_type}`
      );
      window.location.href = `http://wxsyls.oysd.cn/getwxuserinfo.aspx?jump=${redirect_uri}`;
    },
    Start_Game() {
      // 在微信端打开 会有身份验证 路径中会带上 unionid
      if (
        this.env.match(/MicroMessenger/i) !== "micromessenger" ||
        this.env.match(/wxwork/i) == "wxwork"
      ) {
        this.$toast("请在微信端参与活动！");
        return false;
      }
      if (this.game_end) {
        this.$toast("活动已结束");
        return false;
      }
      if (this.rolling) {
        this.$toast("抽奖中，请勿多次点击！");
        return false;
      }
      let params = {
        activityId: this.active_id,
        openId: this.userBaseInfo.openid,
        phone: this.userBaseInfo.phone,
        unionId: this.userBaseInfo.unionid,
        userName: this.userBaseInfo.name
      };
      APi_Active.play(params)
        .then(res => {
          if (!res.data.prizeId) {
            this.showAward = false;
            this.$toast(res.data.message);
            return false;
          }
          const { wheelDeg, prizeList } = this;
          this.rolling = true;
          const random = prizeList
            .map(item => item.id)
            .indexOf(res.data.prizeId);
          this.wheelDeg =
            wheelDeg -
            (wheelDeg % 360) +
            6 * 360 -
            (360 / prizeList.length) * random;
          setTimeout(() => {
            this.awardGood = prizeList[random];
            this.awardGood.coupon = JSON.parse(this.awardGood.coupon);
            this.rolling = false;
            this.showAward = true;
            this.isAward = res.data.prizeName !== "谢谢惠顾";
            if (!this.isAward) {
              this.$toast("");
            }
          }, 4500);
        })
        .catch(err => {
          console.log("err", err);
        });
    },
    getUrlParams(name) {
      let reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
      if (reg.test(location.href))
        return unescape(RegExp.$2.replace(/\+/g, " "));
      return "";
    },
    // 分享
    handleShare() {
      let env = window.navigator.userAgent.toLowerCase();
      if (
        env.match(/MicroMessenger/i) == "micromessenger" &&
        env.match(/wxwork/i) == "wxwork"
      ) {
        console.log("企业微信客户端");
        let url = `http://oysales.oywanhao.com:8087/activeDetail?id=${this.active_id}&active_type=${this.active_type}`;
        wx.invoke(
          "shareToExternalContact",
          {
            title: `${this.activityName}`, // 分享标题
            desc: `${this.des}`, // 分享描述
            link: url, // 分享链接
            imgUrl: "" // 分享封面
          },
          function(res) {
            if (res.err_msg == "shareToExternalContact:ok") {
              console.log("分享成功");
            } else {
              console.log(res.err_msg, "错误信息");
            }
          }
        );
      } else if (env.match(/micromessenger/i) == "micromessenger") {
        console.log("微信客户端");
        let id = this.getUrlParams("id");
        let type = this.getUrlParams("active_type");
        let wx_url = `http://oysales.oywanhao.com:8087/activeDetail?id=${id}&active_type=${type}`;

        wx.ready(function() {
          wx.onMenuShareTimeline({
            title: `${type === "wheel" ? "抽奖" : "送券"}活动`, // 分享标题
            link: wx_url, // 分享链接,将当前登录用户转为puid,以便于发展下线
            imgUrl: "", // 分享图标
            success: function() {
              // 用户确认分享后执行的回调函数
            },
            cancel: function() {
              // 用户取消分享后执行的回调函数
            }
          });
          wx.error(function(res) {
            // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
            alert("errorMSG:" + res);
          });
        });
      }
    }
  },
  destroyed() {
    clearInterval(this.timer);
  }
};
</script>

<style lang="scss">
#active-detail {
  height: 100%;
  .bg {
    position: fixed;
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: -10;
  }
  .coupon {
    position: relative;
    top: 15%;
    width: 90%;
    margin: 0 auto;
    background: #fff;
    border: 1px solid #000;

    .user-icon {
      position: absolute;
      top: -54px;
      left: 0;
      right: 0;
      display: block;
      width: 100px;
      height: 100px;
      margin: 0 auto;
      text-align: center;
      line-height: 100px;
      font-size: 18px;
      border: 1px solid;
      border-radius: 50%;
      background: #fff;
      // filter: blur(2px);
      img {
        width: 100%;
        height: 100%;
        border-radius: 50%;
      }
    }

    .slogan {
      height: 80px;
      padding-top: 25px;
      line-height: 80px;
      font-size: 16px;
      text-align: center;
    }

    .coupon-content {
      position: relative;
      width: 90%;
      margin: 10px auto;
      img {
        width: 100%;
      }
      .content {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        width: 85%;
        height: 92%;
        margin: 0 auto;
        display: flex;
        justify-content: space-around;
        align-items: center;
        .money {
          text-align: center;
          font-size: 32px;
          font-weight: bold;
        }
        .split > img {
          height: 70px;
        }
        .other {
          padding-left: 15px;
          font-size: 14px;
          font-weight: 400;
          p {
            margin-bottom: 5%;
          }
        }
      }
    }

    .btn {
      width: 85%;
      height: 50px;
      margin: 10px auto 30px;
      line-height: 50px;
      text-align: center;
      font-size: 0.5625rem;
      background-color: #fc0;
      border-radius: 4px;
    }
  }

  .wheel-container {
    .title {
      padding-top: 15%;
      font-size: 40px;
      text-align: center;
      color: #fff;
    }

    .wheel {
      position: relative;
      width: 100%;
      img {
        width: 100%;
      }

      .wheel-point {
        width: 20%;
        height: 32px;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        font-size: 20px;
        text-align: center;
        line-height: 32px;
        z-index: 10;
      }

      .wheel-bg {
        width: 74%;
        height: 74%;
        border-radius: 1000px;
        overflow: hidden;
        // background: #fff;
        transition: transform 4s ease-in-out;
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        &.freeze {
          transition: none;
          background: red;
        }
      }

      .prize-list {
        width: 90%;
        height: 90%;
        margin: auto;
        position: relative;
        text-align: center;
      }

      .prize-item-wrapper {
        position: absolute;
        top: 0;
        left: 50%;
        transform: translateX(-50%);
        height: 62%;
      }

      .prize-item {
        width: 90%;
        height: 90%;
        margin: 0 auto;
        transform-origin: bottom;

        .prize-name {
          padding: 0.75rem 0 0;
          font-size: 0.4375rem;
          height: 70%;
          width: 0.5rem;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .prize-icon {
          width: 100%;
          img {
            min-width: 32px;
            min-height: 32px;
            width: 50%;
          }
        }
      }
    }

    .awards {
      width: 80%;
      margin: 0 auto 10px;
      .van-cell {
        background: #ff9;
        border-radius: 10px;
        font-weight: bold;
      }
    }

    .time-line {
      width: 80%;
      text-align: center;
      font-size: 16px;
      margin: 0 auto 20px;
      border-radius: 4px;
      background: #fff;
      span {
        color: #f00;
        font-size: 18px;
      }
    }

    .description {
      width: 100%;
      padding: 5px 1px;
      background: #fff;
      .t {
        position: relative;
        font-size: 16px;
        font-weight: bold;
        padding-left: 20px;
        &::before {
          content: "";
          display: block;
          position: absolute;
          top: 0;
          left: 0;
          width: 8px;
          height: 21px;
          background: #fc0;
        }
      }
      .content {
        padding: 10px;
        font-size: 14px;
      }
    }
  }

  .btn-share {
    position: absolute;
    display: block;
    width: 100%;
    height: 45px;
    margin: 0.3125rem auto;
    text-align: center;
    font-size: 18px;
    line-height: 45px;
    background-color: #169bd5;
  }

  .van-overlay {
    z-index: 100;
  }
  .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    display: flex;
    justify-content: center;
    align-items: center;
    flex-direction: column;
    width: 70%;
    padding: 10px 0;
    background-color: #fff;
    .award-coupon {
      position: relative;
      width: 80%;
      .bg_img {
        width: 100%;
        height: 100%;
      }
      .other {
        display: flex;
        justify-content: space-between;
        position: absolute;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        width: 90%;
        height: 60%;
        margin: auto;
        text-align: center;
        font-size: 32px;
        color: #f00;
        p {
          width: 50%;
          margin: 0;
        }
      }
    }
    p {
      margin-bottom: 8px;
    }
    .van-button {
      width: 80%;
      border-radius: 5px;
      margin: 5px 0;
    }
  }
}
</style>
