<template>
  <div class="friend-help-container">
    <img class="banner-img"
         v-lazy="baseInfoObj.imgurl"
         alt="" />
    <div class="content-wrap">
      <!-- 邀请好友部分 -->
      <div class="box-shadow">
        <template v-if="inviteObj.helpcount>0 && inviteObj.helpcount < maxInviteNum">
          <p>你已成功邀请了{{inviteObj.helpcount}}名好友</p>
          <p v-if="inviteObj.getstatus">获得 {{inviteObj.getprize}} 奖励，请继续关注我们哦!</p>
          <p v-else>你有奖品待领取，快去领取吧</p>
        </template>
        <template v-else-if="inviteObj.helpcount <= 0">
          <p>您还未有好友助力哦~</p>
          <p>暂未有健康奖励，快动起手来邀请好友来助力吧!</p>
        </template>
        <template v-else>
          <p>真棒，您已经完成了所有任务！</p>
          <p v-if="inviteObj.getstatus">获得 {{inviteObj.getprize}} 奖励，请继续关注我们哦!</p>
          <p v-else>你有奖品待领取，快去领取吧</p>
        </template>
        <div class="invite-wrap">
          <div class="prize-wrap">
            <div class="prize-item"
                 v-for="(item,index) in baseInfoObj.prizeList"
                 :key="item.designation">
              <span class="title">邀请{{item.invitenumber}}名</span>
              <div class="prize-img-wrap">
                <img class="prize-img"
                     :src="item.prizeimg"
                     alt="">
                <span class="prize-name">{{item.designation}}</span>
              </div>
              <div class="progress-item">
                <template v-if="item.isActive">
                  <img src="../../../static/imgs/activityCenter/friendsHelp/button-active.png"
                       alt="">
                  <span class="progress-block"
                        style="width: 1.8rem"
                        v-if="index!==baseInfoObj.prizeList.length-1"></span>
                </template>

                <template v-else>
                  <img src="../../../static/imgs/activityCenter/friendsHelp/button.png"
                       alt="">
                  <span class="progress-block"
                        style="width: 1.8rem; backgroundColor: #d6d6d6;"
                        v-if="index!==baseInfoObj.prizeList.length-1"></span>
                </template>
              </div>
              <div :class="item.isActive?'getPrize': 'getPrizeDisable'"
                   @click="handleGetPrize(item.isActive, index)">去领取</div>
            </div>
          </div>
          <p class="prize-text"
             v-if="inviteObj.getstatus===false && inviteObj.helpcount < maxInviteNum">再邀请 {{nextInviteNum}} 名好友，就能获得 {{nextPrizeName}}</p>
        </div>
        <van-button type="info"
                    class="vant-button"
                    @click="handleInviteClick">立即邀请</van-button>
      </div>

      <!-- 邀请记录 -->
      <div class="invite-record-wrap">
        <img class="invite-title"
             src="../../../static/imgs/activityCenter/friendsHelp/title.png" />
        <!-- 邀请记录列表部分 -->
        <div class="invite-content box-shadow">
          <div class="item"
               v-for="item in inviteObj.helperList">
            <div class="item-left">
              <img :src="item.headimg"
                   alt="">
              <span>{{item.nickname}}</span>
            </div>
            <div class="item-right">
              {{item.helptime}}
            </div>
          </div>
        </div>
      </div>

      <!-- 领取奖励二维码弹出框 -->
      <van-popup v-model="getPrizeModal"
                 :close-on-click-overlay="false">
        <img src="../../../static/imgs/activityCenter/friendsHelp/getPrize.png" />
        <span class="close-btn"
              @click="getPrizeModal = false"></span>
      </van-popup>

      <!-- 邀请好友弹窗 -->
      <van-popup v-model="active"
                 :close-on-click-overlay="false">
        <img :src="inviteImage" />
        <span class="close-btn"
              @click="active = false"></span>
      </van-popup>
    </div>
  </div>
</template>

<script>
  import ljCard from '../../../components/common/Card.vue'
  import { Dialog } from 'vant';
  import { reqGetFriendsHelpBaseInfo, reqInviteFriendsInfo, reqJudgeMobileIsNull, reqCreateImage } from '../../../api/activityCenter/activityCenter'
  export default {
    components: {
      ljCard
    },
    data() {
      return {
        id: null,
        unionid: null,
        baseInfoObj: {       // 活动的基本信息对象

        },
        inviteObj: {  // 邀请好友领取奖励数据和被邀请好友信息列表
          helpcount: 0,
          getstatus: false
        },    
        nextInviteNum: null,   //  再邀请多少好友
        nextPrizeName: null,   // 下一个商品名称
        active: false,    // 邀请好友弹窗
        getPrizeModal: false,   // 领取奖励弹窗
        inviteImage: '',    // 邀请好友图片
      }
    },
    methods: {
      // 邀请好友弹窗图片生成接口
      async createImage() {
        const { data: response } = await reqCreateImage({ id: this.id, unionid: this.unionid })
        console.log("邀请好友弹窗生成二维码接口返回数据: ", response)
        if (response.success !== 1) return this.$toast(response.message)
        this.inviteImage = response.result
        this.active = true
        console.log("active: ", this.active)
      },

      // 获取邀请好友的领取奖品标记信息
      async getInviteFriendsInfo() {
        const { data: response } = await reqInviteFriendsInfo({ id: this.id, unionid: this.unionid })
        if (response.success !== 1) return this.$toast(response.message)
        // this.inviteObj = response.result
        if(response.result) this.inviteObj = response.result
        let tempNum = 0
        let tempIndex = 0
        try {
          this.baseInfoObj.prizeList.forEach((item, index) => {
            // 找到下一个奖品需要邀请的人数和该值所在数组中的索引位置
            if (this.inviteObj.helpcount < item.invitenumber) {
              tempNum = item.invitenumber
              tempIndex = index
              throw new Error('endIterative')
            }
          })
        } catch (error) {
          if (error.message !== 'endIterative') throw error
        }
        // maxInviteNum：最后一个奖品所需要邀请的人数
        if (this.inviteObj.helpcount >= this.maxInviteNum) {
          tempNum = this.maxInviteNum
          tempIndex = this.baseInfoObj.prizeList.length - 1
        }
        this.nextInviteNum = tempNum - this.inviteObj.helpcount
        this.nextPrizeName = this.baseInfoObj.prizeList[tempIndex].designation
        this.baseInfoObj.prizeList.map((item, index) => {
          if(this.inviteObj.getstatus === true) return item.isActive = false
          if(this.inviteObj.helpcount >= item.invitenumber) {
            item.isActive = true
          }else {
            item.isActive = false
          }
          console.log(`奖品需要邀请人数: ${item.invitenumber}, 奖品索引位置: ${index}`)
        })
      },

      // 获取活动基本信息
      async getFriendsHelpBaseInfo() {
        const { data: response } = await reqGetFriendsHelpBaseInfo(this.id)
        console.log("获取活动基本信息返回数据: ", response)
        if (response.success !== 1) return this.$toast(response.message)
        // 对奖品列表排序
        response.result.prizeList = response.result.prizeList.sort((a, b) => { return a.invitenumber - b.invitenumber })
        this.baseInfoObj = response.result
        this.getInviteFriendsInfo()

      },
      // 调用领取奖品接口
      async handleGetPrize(active, index) {
        // 调用接口判断用户是否注册手机号,如果注册就直接跳转注册页面,否则停留当前页面并且弹窗显示联系客服图片
        if (!active) return this.$toast('不能领取奖品')
        // 显示领取奖励弹窗
        const { data: response } = await reqJudgeMobileIsNull({ unionid: this.unionid })
        console.log("领取奖品,判断手机号接口: ", response)
        if(process.env.VUE_APP_Name == "测试环境" || process.env.VUE_APP_Name == "开发环境") {
          if (!response.result) return window.location.href = `https://mem.360lj.com/ym2/ymallWechat/code?redirectCode=activityIndex&id=${this.id}`
        }else {
          if (!response.result) return window.location.href = `https://mem.360lj.com/ym/ymallWechat/code?redirectCode=activityIndex&id=${this.id}`
        }
        this.getPrizeModal = true
      },
      // 监听立即邀请按钮点击事件
      handleInviteClick() {
        let { begintime, endtime } = this.baseInfoObj
        const nowtime = new Date().getTime()
        begintime = begintime.replace(/-/g, "/");
        endtime = endtime.replace(/-/g, "/");
        console.log('开始时间: ', begintime)
        console.log('结束时间: ', endtime)
        console.log("当前时间: ", nowtime)
        if (new Date(begintime).getTime() < nowtime && nowtime < new Date(endtime).getTime()) {
          // 活动进行中.
          this.createImage()
        } else if (new Date(endtime).getTime() < nowtime) {
          Dialog.alert({
            message: '抱歉, 活动已结束了, 持续关注我们,还会有源源不断的优惠活动哦~',
          })
        } else {
          this.$toast('活动未开始')
        }
      }
    },
    mounted() {
      // 配置JS SDK
      wx.ready(function () {
        wx.checkJsApi({
          jsApiList: ['hideOptionMenu'],
          success: function (res) {
            console.log("weixin sdk config status: ", res)
          }
        })
        // 隐藏选项菜单
        wx.hideOptionMenu()
      })
      this.id = this.getUrlParams('id')
      window.sessionStorage.setItem('id', this.id)
      this.unionid = this.getUrlParams('unionid')
      if (this.id && this.unionid) {
        this.getFriendsHelpBaseInfo()
      }
    },
    computed: {
      // 获取最大邀请人数
      maxInviteNum() {
        if (JSON.stringify(this.baseInfoObj) !== '{}') {
          return this.baseInfoObj.prizeList[this.baseInfoObj.prizeList.length - 1].invitenumber
        } else {
          return null
        }
      }
    }
  }
</script>

<style lang="less" scoped>
  html,
  body {
    height: unset !important;
  }
  .friend-help-container {
    background-color: #f7f7f7;
    .banner-img {
      width: 100%;
      max-height: 3rem;
    }
  }
  .content-wrap {
    padding: 0 0.2rem;
    .box-shadow {
      position: relative;
      margin: 0 auto;
      margin-top: -0.4rem;
      width: 100%;
      padding-top: 0.4rem;
      background-color: #fff;
      border-radius: 0.1rem;
      -moz-box-shadow: 0 0.08rem 0.12rem #ebedf0;
      -webkit-box-shadow: 0 0.08rem 0.12rem #ebedf0;
      box-shadow: 0 0.08rem 0.12rem #ebedf0;
      min-height: 4rem;
      p {
        font-size: 0.32rem;
        &:nth-child(1) {
          color: #000;
        }
        &:nth-child(2) {
          margin-top: 0.2rem;
          color: #999999;
        }
      }
    }
  }
  .invite-wrap {
    // height: 6.4rem;
    > p {
      margin-top: 0.8rem !important;
      color: #478bfb !important;
    }

    .prize-wrap {
      display: flex;
      overflow-x: scroll;
      &::-webkit-scrollbar {
        display: none;
      }
      .prize-item {
        display: flex;
        min-width: 28%;
        margin-top: 0.4rem;
        flex-direction: column;
        align-items: center;
        .title {
          font-size: 0.3rem;
        }
        .prize-img-wrap {
          position: relative;
          margin-top: 0.1rem;
          width: 1.2rem;
          height: 1.2rem;
        }
        .prize-img {
          width: 100%;
        }
        .prize-name {
          position: absolute;
          width: 100%;
          min-height: 0.28rem;
          bottom: 0%;
          left: 0;
          background-color: rgba(0, 0, 0, 0.4);
          color: #fff;
        }
        .progress-item {
          display: flex;
          align-items: center;
          margin: 0.2rem;
          position: relative;
          img {
            position: relative;
            z-index: 1;
            // width: 100%;
          }
          .progress-block {
            position: absolute;
            width: 1.5rem;
            height: 0.1rem;
            // top: 1%;
            left: 90%;
            background-color: #478bfb;
          }
        }
        .getPrize {
          width: 1rem;
          height: 0.44rem;
          background-color: #478bfb;
          color: #fff;
          border-radius: 8%;
          line-height: 0.44rem;
        }
        .getPrizeDisable {
          background-color: #989898;
          width: 1rem;
          height: 0.44rem;
          color: #fff;
          border-radius: 8%;
          line-height: 0.44rem;
        }
      }
    }
  }

  .vant-button {
    width: 90%;
    margin: 0.4rem 0;
  }

  .invite-record-wrap {
    .invite-title {
      margin: 0.4rem 0;
    }
    // margin-top: 9.4rem;
    width: 100%;
    .invite-content {
      position: static;
      margin-top: 0.2rem;
      .item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        font-size: 0.32rem;
        margin: 0 0.4rem;
        height: 1.42rem;
        border-bottom: 1px solid #efefef;
        .item-left {
          display: flex;
          align-items: center;
          font-size: 0.34rem;
          color: #000;
          max-width: 3rem;
          overflow: hidden;
          img {
            width: 0.62rem;
            margin-right: 0.2rem;
          }
        }
        .item-right {
        }
      }
    }
  }

  /deep/.van-dialog__content img {
    width: 50%;
    max-height: 3rem;
  }

  /deep/.van-popup {
    background-color: transparent;
  }

  // 关闭按钮
  .close-btn {
    position: absolute;
    bottom: 1%;
    left: 44%;
    display: block;
    width: 0.7rem;
    height: 0.6rem;
    background-color: transparent;
  }
</style>