<template>
  <div class="group-index" ref="index" v-if="groupDetail" style="background-color: #fda813;">
    <div>
      <img class="tips" :src="tipsUrl"/>
      <div class="img-cvs" id="capture" ref="imageWrapper" v-if="groupDetail.share_desc.refImg && groupDetail.share_desc.refImg.length > 0">
        <template v-if="avatar && QRCodeB">
          <img :src="groupDetail.share_desc.refImg[0].url">
          <div class="avatar-container"><img :src="avatar" class="avatar"/> 我已加入，邀请你一起加入</div>
        </template>
        <div id="qrcode" class="qrcode">
        </div>
      </div>
      <img :src="dataURL" class="cvs-img" id="cvs-img"/>
      <div class="inviteBtn" id="inviteBtn">
        <div class="i-btn flex-start" @click="show=true">
          <img class="i-env" :src="whiteEnvelopeUrl"/>
          <span class="i-env-title">邀请语：</span>
          <div class="elips"><span class="marquee">{{comments[commentIndex]}}</span></div>
        </div>
      </div>
      <mt-popup v-model="show" :closeOnClickModal="false">
        <div class="pop-fill">
          <div class="flex-bt">
            <div class="flex-start no-margin">
              <img class="p-envelope" :src="envelopeUrl"/>
              <span class="p-tips">贴心的邀请语提高成功率</span>
            </div>
            <img class="p-switch no-margin" :src="switchUrl" @click="onSwitch"/>
          </div>
          <div class="p-comments">
            <p>{{comments[commentIndex]}}</p>
          </div>
          <div class="copyBtn" v-clipboard:copy="comments[commentIndex]" v-clipboard:success="onCopy">复制邀请语</div>
          <div class="close">
            <img :src="closePopUrl" class="close-pop" @click="show=false"/>
          </div>
        </div>
      </mt-popup>
    </div>
  </div>
</template>

<script>
  import 'swiper/dist/css/swiper.css'
  import { swiper, swiperSlide } from 'vue-awesome-swiper'
  import  QRCode from 'qrcodejs2'
  import { Indicator } from 'mint-ui';
  import {getwechatParam,getGoodsDetailApi,getGroupDetailApi,getStatusWechatApi,getUserDetailApi} from "../../service/api";
  import refBg from '../../assets/refBg.png'
  import moreUrl from '../../assets/moreIcon.png'
  import refIcon from '../../assets/refIcon.png'
  import weChatIcon from '../../assets/wechatIcon.png'
  import weChatQrUrl from '../../assets/weChatCode.png'
  import closeUrl from '../../assets/closemy.png'
  import redBtnUrl from '../../assets/activity/red-bg.png'
  import envelopeUrl from '../../assets/activity/envelope.png'
  import whiteEnvelopeUrl from '../../assets/activity/white-envelope.png'
  import closePopUrl from '../../assets/activity/close.png'
  import switchUrl from '../../assets/activity/switch.png'
  import tipsUrl from '../../assets/activity/tips.png'
  import html2canvas from 'html2canvas'
  import { Toast } from 'mint-ui';
  export default {
    name: "index",
    components: {
      swiper,
      swiperSlide,
    },
    data(){
      return {
        refBg:refBg,
        join:false,
        popType:false,
        popFill:false,
        popupVisible:false,
        refVisible:false,
        tabType:true,
        popcontentW:`您已经购买过课程，无需重复<br>购买，您可以添加微信公众号了解更多`,
        popcontentT:`为了更好地为您进行课程服务，<br>请扫码添加老师二维码`,
        qrCode:weChatQrUrl,
        weChatIcon:weChatIcon,
        closeUrl:closeUrl,
        moreUrl:moreUrl,
        tipsUrl:tipsUrl,
        refIcon:refIcon,
        swiperOption: {
          pagination: {
            el: '.swiper-pagination'
          }
        },
        QRCodeB:false,
        dataURL:null,
        user_id:null,
        avatar:'',
        invite_code_f:true,
        invite_code:'',
        shopId:'',
        groupId:null,
        groupDetail:false,
        groupData:null,
        redBtnUrl: redBtnUrl,
        envelopeUrl: envelopeUrl,
        whiteEnvelopeUrl: whiteEnvelopeUrl,
        closePopUrl: closePopUrl,
        switchUrl: switchUrl,
        show: false,
        comments: [
          '英语这样启蒙效果太棒啦，唱唱这个90天启蒙课程做真不错，推荐给你们！坚持打卡全额返学费，报课即送价值498元教具礼盒。数量有限，抢完即止！',
          '发现一款对宝宝英语启蒙特别有用的产品，每天10分钟宝宝已经爱上英语、爱唱英语。现在他们这个90天课程在做活动，坚持打卡全额返学费。我体验过了，真的很好！快带着宝宝一起唱玩英语吧~',
          '第一次接触线上启蒙英语，发现唱唱课程实在太棒啦，既省事宝宝学起来还方便，每天快乐中学习。现在他们这个90天课程在做活动，限时免费学，不花1分钱，学习90天，还送实物教具，机不可失，速来领取~'
        ],
        commentIndex: 0,
        shareTitle: '钜惠来袭！唱唱启蒙英语90天课程免费学！',
        shareDesc: '报课即送价值498元教具礼盒，坚持打卡全额返学费，让0基础宝宝10分钟开口说英语，速来~'
      }
    },
    mounted(){
      this.getDetail();
    },
    methods:{
      onSwitch(){
         if (this.commentIndex === 0) {
           this.commentIndex = 1;
         } else if (this.commentIndex == 1) {
           this.commentIndex = 2;
         } else if (this.commentIndex == 2) {
           this.commentIndex = 0;
         }
      },
      onCopy(e){
        Toast({
          message: '复制成功',
          position: 'middle',
          className: 'copyToast',
          duration: 2000
        });
        this.show =  false;
      },
      refshow(){
        Indicator.open();
        if(document.body.scrollTop < 10){
          document.body.scrollTop = 20;
          document.documentElement.scrollTop = 20;
        }
        if(localStorage.getItem('cc_token') && localStorage.getItem('cc_token') !== ''){
          if(!this.invite_code){
            this.invite_code = 'CC-USER'
          }
          getUserDetailApi().then(res=>{
            this.user_id=res.user_id;
            let _that = this;
            let invite_code = this.invite_code.split('-');
            if(invite_code.length > 2 && invite_code[1] === 'TEACHER'){
              invite_code[1] = 'USER'
            }
            let code = `${invite_code[0]}-${invite_code[1]}`;
            let URL = `${process.env.BUY_URL}shopId=${this.shopId}&invite_code=${code}-${this.user_id}`;
            if(this.groupId && this.groupId !== 'null'){
              URL += `&groupId=${this.groupId}`
            }
            this.onNewShare(URL);
            this.toDataURLBase64(res.avatar.replace('http://','https://'), function (avatar) {
              _that.avatar = avatar
            });
            _that.qrcode(URL);
            this.refVisible = true;
            this.$nextTick(()=>{
              if(!this.dataURL){
                setTimeout(()=>{
                  let {
                    height,
                    width,
                    top
                  } = document.getElementById('capture').getClientRects()[0]
                  document.getElementById('capture').style.width = width + 'px';
                  let o = this.getOffsetRect(this.$refs.imageWrapper);
                  let {
                    height1,
                    width1
                  } = document.getElementById('capture').getClientRects()[0];
                  console.log('document.getElementById', document.getElementById('capture').getClientRects()[0]);
                  document.getElementById('inviteBtn').style.top = height + top + 20 + 'px';
                  document.getElementById('inviteBtn').style.opacity = 1;
                  html2canvas(document.getElementById('capture'),{
                    async: true,
                    timeout: 500,
                    scrollX:1,
                    scale: 3,
                    width: width1,
                    height: height1,
                    letterRendering: true,
                  }).then((canvas) => {
                    let dataURL = canvas.toDataURL("image/jpg");
                    this.dataURL = dataURL;
                    Indicator.close();
                  }).catch(res=>{alert(res);console.log()});
                },500)
              }else{

              }
            })
          });
        }else{
          let query = {retUrl:this.$route.fullPath,is_new_user_url:'1'};
          this.$router.push({name:'author',query:query})
        }
      },
      getOffsetRect(ele){
        var box=ele.getBoundingClientRect();
        var body=document.body,
          docElem=document.documentElement;
        //获取页面的scrollTop,scrollLeft(兼容性写法)
        var scrollTop=window.pageYOffset||docElem.scrollTop||body.scrollTop,
          scrollLeft=window.pageXOffset||docElem.scrollLeft||body.scrollLeft;
        var clientTop=docElem.clientTop||body.clientTop,
          clientLeft=docElem.clientLeft||body.clientLeft;
        var top=box.top+scrollTop-clientTop,
          left=box.left+scrollLeft-clientLeft;
        return {
          //Math.round 兼容火狐浏览器bug
          top:Math.round(top),
          left:Math.round(left)
        }
      },
      qrcode(data){
        if(this.QRCodeB){
          this.QRCodeB.makeCode(data)
        }else{
          this.QRCodeB = new QRCode('qrcode', {
            width: 80,
            height: 80, // 高度
            text: data, // 二维码内容
            image: ''
          });
        }

      },
      // 分享
      enableShare: function(option) {
        let that = this;
        getwechatParam({
          api_list:   'onMenuShareAppMessage,onMenuShareTimeline',
          url:window.location.href.split('#')[0]
        }).then(wechatRes => {
          console.log('enableShare', wechatRes)
          wx.config({
            debug: false,
            appId: wechatRes.appId,
            timestamp: parseInt(wechatRes.timestamp),
            nonceStr: wechatRes.nonceStr,
            signature: wechatRes.signature,
            jsApiList: wechatRes.jsApiList
          });
          wx.ready(function() {
            wx.onMenuShareTimeline({
              title: that.shareTitle, // 分享标题
              desc: that.shareDesc,// 分享描述
              link: option.shareUrl, // 分享链接
              imgUrl: option.shareIcon || 'https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png', // 分享图标
              success: function() {
                console.log('分享成功');
                window._hmt.push(['_trackEvent', '分享', "商品页好友分享",`id${that.shopId}`,that.invite_code]);//百度统计
              },
              cancel: function() {
                // alert("失败")
                console.log('分享失败')
              }
            });
            wx.onMenuShareAppMessage({
              title: that.shareTitle, // 分享标题
              desc: that.shareDesc,// 分享描述
              link: option.shareUrl, // 分享链接
              imgUrl: option.shareIcon || 'https://cdn.singsingenglish.com/singsing/recommend/logo-refer.png', // 分享图标
              success: function() {
                window._hmt.push(['_trackEvent', '分享', "商品页朋友圈分享",`id${that.shopId}`,that.invite_code]);//百度统计
              },
              cancel: function() {
              }
            });
          })
        })
      },
      onShare: function(type) {
        let URL = `${process.env.BUY_URL}?shopId=${this.shopId}&groupId=${this.groupId}&invite_code=${this.invite_code}`;
        if(type === 1 ){
          URL = `${process.env.BUY_URL}?shopId=${this.shopId}&invite_code=${this.invite_code}`
        }
        this.enableShare({
          product_title: this.groupDetail.share_desc.title,
          desc: this.groupDetail.share_desc.content,
          shareIcon:this.groupDetail.share_desc.img[0].url,
          shareUrl:URL
        })
      },
      onNewShare(url){
        this.enableShare({
          product_title: this.groupDetail.share_desc.title,
          desc: this.groupDetail.share_desc.content,
          shareIcon:this.groupDetail.share_desc.img[0].url,
          shareUrl:url
        })
      },
      toDataURLBase64 (src, callback) {
        let xhttp = new XMLHttpRequest();
        xhttp.onload = function () {
          let fileReader = new FileReader();
          fileReader.onloadend = function () {
            callback(fileReader.result)
          };
          fileReader.readAsDataURL(xhttp.response)
        };
        xhttp.responseType = 'blob';
        xhttp.open('GET', src, true);
        xhttp.send()
      },
      // 初始化
      getDetail(){
        if(window.location.href.indexOf('invite_code')> -1){
          this.invite_code = this.$route.query.invite_code;
          let l = this.invite_code.split('-').length
          if(l < 3){
            this.invite_code_f = false
          }
        }
        if(window.location.href.indexOf('shopId')>-1){
          this.shopId = this.$route.query.shopId;
          getGoodsDetailApi(this.shopId).then(res=>{
            res.desc = JSON.parse(res.desc);
            res.goods_desc = JSON.parse(res.goods_desc);
            res.share_desc = JSON.parse(res.share_desc);
            //商品下架跳转绑定商品
            if(res.status === 2 && res.bind_goods_id){
              this.$router.push({name:'buyDetail',query:{shopId:res.bind_goods_id}});
              this.getDetail();
              return
            }
            this.groupDetail = res;
            for (let i = 0;i<this.groupDetail.header_url.length;i++){
              this.groupDetail.header_url[i]=this.groupDetail.header_url[i].replace('http://','https://')
            }
            this.groupDetail.desc.detail = this.groupDetail.desc.detail.replace(/http:\/\//g,'https://');
            this.groupDetail.desc.qa = this.groupDetail.desc.qa.replace(/http:\/\//g,'https://');
            if(this.groupDetail.share_desc.refImg && this.groupDetail.share_desc.refImg.length === 1){
              this.groupDetail.share_desc.refImg[0].url = this.groupDetail.share_desc.refImg[0].url.replace('http://','https://');
              let _this = this;
              this.toDataURLBase64(this.groupDetail.share_desc.refImg[0].url, function (avatarUrl) {
                _this.groupDetail.share_desc.refImg[0].url = avatarUrl;
              });
            }
            if(this.groupDetail.goods_type === 2){
              if(localStorage.getItem('cc_token')){
                getStatusWechatApi({goods_id:this.shopId}).then(res=>{
                  if(res.out_trade_no){
                    this.$router.push({name:'success',query:{out_trade_no:res.out_trade_no}});
                  } else {
                    this.refshow()
                  }
                });
              } else {
                this.refshow()
              }
            } else {
              this.refshow()
            }
          })
        }

      }
    }
  }
</script>
<style>
  img,video{
    max-width: 100%;
  }
  .copyToast {
    z-index: 9999;
  }
</style>
<style scoped lang="less">
  @import "../../util/public";
  @keyframes marquee {
    0% {
      transform: translateX(0);
    }
    100% {
      transform: translateX(-1000px);
    }
  }
  .marquee {
    display: block;
    width: 100%;
    top: 12 * @toVw;
    left: 0;
    text-align: center;
    position: absolute;
    -webkit-animation: marquee 30s linear infinite;
    animation: marquee 30s linear infinite;
  }
  .elips {
    position: relative;
    width: 170* @toVw;
    height: 100%;
    overflow: hidden;
    white-space: nowrap;
    /*text-overflow: ellipsis;*/
    margin: 0;
    z-index: 1;
  }
  .tips {
    width: 230 * @toVw;
    margin-left: 163 / 2 * @toVw;
    margin-top: 10 * @toVw;
  }
  .img-cvs{
    position: absolute;
    width: 525 / 2 * @toVw;
    top: 90 * @toVh;
    left: 113 / 2 * @toVw;
    .avatar-container {
      position: absolute;
      top: 8 * @toVh;
      left: 8 * @toVw;
      font-size: 12 * @toVw;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #fff;
      img {
        width: 30 * @toVw;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
    img {
      /*border-radius: 10px;*/
    }
  .qrcode{
    position: absolute;
    top: 700 / 2 * @toVw;
    left: 15 * @toVw;
    width: 60 * @toVw;
  }
  }
  .cvs-img{
    position: absolute;
    width: 525 / 2 * @toVw;
    top: 90 * @toVh;
    left: 113 / 2 * @toVw;
    z-index: 10;
  }
  .inviteBtn {
    position: absolute;
    width: 100%;
    opacity: 0;
    text-align: center;

    .i-btn {
      position: relative;
      width: 642 / 2 * @toVw;
      height: 92 / 2 * @toVw;
      text-align: left;
      font-size: 14 * @toVw;
      color: #fff;
      background: url('../../assets/activity/red-bg.png') no-repeat center;
      background-size: cover;
      box-sizing: border-box;
      padding: 2px 58/2*@toVw;
      overflow: hidden;
      .i-env {
        width: 36 / 2 * @toVw;;
        height: auto;
        margin-right: 5px;
        margin-left: 0;
        z-index: 2;
      }
      .i-env-title {
        font-size: 16 * @toVw;
        margin:0;
        z-index: 2;
      }
    }
  }
  .flex-start {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;
  }
  .g-btns {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-around;
    align-items: center;
    width: 642 / 2 * @toVw;
    margin-top: 30 / 2 * @toVw;
    font-size: 14 * @toVw;
    color: #fff;
    img {
      width: 96 / 2 * @toVw;
      height: 96 / 2 * @toVw;
    }
  }
  .copyBtn {
    background: url('../../assets/activity/yellow-bg.png') no-repeat center;
    background-size: cover;
    box-sizing: border-box;
    width: 567 / 2 * @toVw;
    height: 92 / 2 * @toVw;
    text-align: center;
    line-height: 92 / 2 * @toVw;
    color: #fff;
    font-size: 20 * @toVw;
  }
  .flex-bt {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
  }
  .p-tips {
    color: #999;
    font-size: 15 * @toVw;
  }
  .p-envelope {
    width: 22 * @toVw;
    height: 22 * @toVw;
    margin-right: 12 * @toVw;
  }
  .p-switch {
    width: 15 * @toVw;
    height: 15 * @toVw;
  }
  .p-comments {
    margin: 15px 0;
    height: 150 * @toVw;
    overflow-y: scroll;
    p {
      line-height: 2;
    }
  }
  .no-margin {
    margin: 0;
  }
  .ref-content{
    width: 299 * @toVw;
    height: 564 * @toVw;
    background-size: 100% 100%;
    position: relative;
  .tips{
    font-size: 12px;
    position: absolute;
    color: #666;
    right: 10 * @toVw;
    top: 250 * @toVw;
    width: 1em;
  }
  }
  .group-index{
    height: 100%;
    padding-bottom: toVw(150);
    background: #f0f0f0;
    font-family: PingFangSC-Regular;
  .ref-icon{
    position: fixed;
    height: 100/375 * 90vw ;
    top: 70vw;
    z-index: 6;
    right: 10 * 100 /375vw;
    border-radius: 100px;
  }
  .banner{
    background: white;
  img{
    width: 100%;
  }
  }
  .head{
    background: white;
    margin-bottom: 10px;
    padding: 20/7.5vw;
  .title{
    font-size: 20px;
    color: #333333;
    margin-bottom: 15/7.5vw;
  }
  .detail{
    font-size: 12px;
    line-height: 1.6em;
    color: #333333;
    display: block;
    margin-bottom: 15/7.5vw;
  }
  .price{
  .price-content{
    font-family: PingFang-SC-Bold;
    font-size: 20px;
    color: #F83534;
  }
  }
  }
  .head-icon{
    padding: 20/7.5vw;
    background: white;
    margin-bottom: 2px;
  .icon{
    display: inline-block;
    width: 60/7.5vw;
    margin: 0 10/7.5vw;
    border-radius: 1000px;
    vertical-align: middle;
  }
  .more{
    width: 50/7.5vw;
    vertical-align: middle;
  }
  .has{
    font-size: 12px;
    line-height: 60/7.5vw;
    color: #999999;
    float: right;
  }
  }
  .welfare{
    background: white;
    padding:10/7.5vw ;
    font-size: 12px;
    text-align: center;
    color: #999999;
    margin-bottom: 20px;
  }
  .main-detail{
    padding: 20/7.5vw;
    background: white;
  .tab-content{
    border-radius: 9px ;
    border: 1px solid #F63539;
  &:after{
     content: '';
     display: block;
     clear: both;
   }
  .tab-btn{
    width: 50%;
    float: left;
    height: 80/7.5vw;
    line-height: 80/7.5vw;
    text-align: center;
    color: #F63539;
    border-radius:9px ;
  &.active{
     background: #F63539;
     color: white;
   }
  }
  }
  .qa-block{
    padding: 20/7.5vw 0 toVw(150) 0;
  img,video{
    max-width: 100%;
  }
  .qa-content{
    margin: toVw(10) 0;
  .qa-q{
    font-size: 16px;
    color: #666666;
  }
  .qa-a{
    font-size: 16px;
    color: #333333;
  }
  }
  }
  .detail{
    padding: 20/7.5vw 0 150/7.5vw 0;
  .detail-content{
  img,video{
    max-width: 100%;
  }
  }

  }
  }
  footer{
    position: absolute;
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 120/7.5vw;
    display: -webkit-box;      // OLD - iOS 6-, Safari 3.1-6 //
  display: -moz-box;         // OLD - Firefox 19- (buggy but mostly works) //
  display: -ms-flexbox;      // TWEENER - IE 10 //
  display: -webkit-flex;     // NEW - Chrome //
  display: flex;             // NEW, Spec - Opera 12.1, Firefox 20+ //
  background: white;
    padding: 10/7.5vw;
    border-top: 1px solid #d8d8d8;
    justify-content:space-around;
  .btn{
    border: 1px solid #cccccc;
    border-radius: 8px;
    width:0;
    flex-grow:2;
    text-align: center;
    padding: 15/7.5vw 0;
    margin: 0 10/7.5vw;
    line-height: 1.4em;
    font-size: 16px;
    color: #666666;
  span{
    display: block;
    font-size: 20px;
    font-family: PingFang-SC-Bold;
  }
  img{
    width: 50/7.5vw;
  }
  &.big{
     padding: 5/7.5vw 0;
     flex-grow:5;
  &.price{
     background:  #F83534;
     border-color: #F83534;
     color: white;
   }
  }
  }
  }
  .pop-block{
    padding:40/7.5vw 10/7.5vw;
    width: 600/7.5vw;
    text-align: center;
    font-size: 14px;
    color: #666666;
    position: relative;
  img{
    width: 250/7.5vw;
  }
  .close{
    width: 50/7.5vw;
    position: absolute;
    top: 20/7.5vw;
    right: 20/7.5vw;
  }
  }
  .mint-popup{
    border-radius: 10px;
  }
  .pop-fill{
    width: 705 / 2 * @toVw;
    padding:30/7.5vw 30/7.5vw;
    box-sizing: border-box;
    font-size: 16px;
    color: #333333;
    .close {
      position: absolute;
      width: 100%;
      bottom: -60 * @toVw;
      left: 0;
      text-align: center;
    }
    .close-pop {
      width: 75 / 2 * @toVw;
      height: 75 / 2 * @toVw;
    }
  .btn-block{
    margin-top: 30/7.5vw;
  &:after{
     content:'';
     display: block;
     clear: both;
   }
  .btn{
    float: right;
    background: #F83534;
    font-size: 14px;
    padding: 5/7.5vw 10/7.5vw;
    border-radius: 8px;
    color: #FFFFFF;
  }
  }
  }

  }

</style>
