<template>
  <div class="group-index" ref="index" v-if="groupDetail">
    <swiper :options="swiperOption" class="banner" ref="mySwiper">
      <swiper-slide v-if="groupDetail.goods_desc" v-for="(data,index) in groupDetail.goods_desc.img" :key="index">
        <img :src="data.url"/>
      </swiper-slide>
      <div class="swiper-pagination" slot="pagination"></div>
    </swiper>
    <img :src="refIcon" class="ref-icon" @click="refshow()" v-if="groupDetail.is_auth_user === 1">
    <div class="head">
      <div class="title">
        {{groupDetail.name}}
      </div>
      <span class="detail">
                {{groupDetail.goods_desc.desc}}
            </span>
      <div class="price">
        <span class="price-content">¥{{groupDetail.current_price/100}}元</span>
      </div>

    </div>
    <div class="head-icon">
      <img class="icon" v-for="(data,index) in groupDetail.header_url" v-if="index<5" :src="data" :key="data">
      <img class="more" :src="moreUrl"/>
      <span class="has">已售{{groupDetail.has_group_num}}件</span>
    </div>
    <div class="welfare" v-if="groupDetail.head_welfare && groupDetail.head_welfare !== '' && groupDetail.head_welfare !== null">
      团长福利:{{groupDetail.head_welfare}}
    </div>
    <div class="main-detail">
      <div class="tab-content">
        <div :class="{'tab-btn':true,active:tabType}" @click="tabType=true">图文详情</div>
        <div :class="{'tab-btn':true,active:!tabType}" @click="tabType=false">购买须知</div>
      </div>
      <div v-if="tabType" class="detail">
        <div v-html="groupDetail.desc.detail" class="detail-content"></div>
      </div>
      <div v-if="!tabType" class="qa-block">
        <div class="qa-content qaDetail" v-html="groupDetail.desc.qa">
        </div>
      </div>
    </div>
    <mt-popup v-model="popupVisible">
      <div class="pop-block">
        <img v-if="popType" :src="qrCode"/>
        <img v-if="!popType" :src="groupDetail.desc.customer_service[0].url"/>
        <div>
          <span v-if="popType" v-html="popcontentW"></span>
          <span v-if="!popType" v-html="popcontentT"></span>
        </div>
        <img class="close" :src="closeUrl" @click="popupVisible = false">
      </div>
    </mt-popup>
    <mt-popup v-model="popFill" :closeOnClickModal="false">
      <div class="pop-fill">
        您好,本次拼团已经结束。您可以选择重新开团或单独购买
        <div class="btn-block">
          <div class="btn" @click="rePlay()">重新开团</div>
        </div>
      </div>
    </mt-popup>
    <mt-popup v-model="refVisible" style="background-color: transparent;margin-top: -80vw;margin-left: -40vw;transform: none">
      <div :style="{backgroundImage:`url(${refBg})`}" class="ref-content"
           v-if="groupDetail.share_desc.refImg && groupDetail.share_desc.refImg.length > 0">
        <div class="tips">
          长按保存图片
        </div>
      </div>
      <div class="img-cvs" id="capture" ref="imageWrapper" v-if="groupDetail.share_desc.refImg && groupDetail.share_desc.refImg.length > 0">
        <img :src="groupDetail.share_desc.refImg[0].url">
        <div id="qrcode" class="qrcode">
        </div>
      </div>
      <img :src="dataURL" class="cvs-img"/>
    </mt-popup>
    <div v-if="groupDetail.status === 1 && invite_code_f">
    <footer v-if="groupDetail.goods_type && groupDetail.goods_type === 2">
      <div class="btn" @click="showTeacher()">
        <img :src="weChatIcon"/>
      </div>
      <div class="btn big" @click="groupPay(0)" :id="groupId ? 'reGroup':'singleBuy'">
        <span v-if="!groupId">¥{{groupDetail.original_price/100}}</span>
        <div v-if="!groupId">单独购</div>
        <span v-if="groupId">¥{{groupDetail.current_price/100}}</span>
        <div v-if="groupId">重新开团</div>
      </div>
      <div class="btn big price" @click="groupPay(1)" :id="groupId ? 'joinGroup':'newGroup'">
        <span>¥{{groupDetail.current_price/100}}</span>
        <div v-if="!groupId">{{groupDetail.desc.group_number}}人团</div>
        <div v-if="groupId">立即参团</div>
      </div>
    </footer>
    <footer v-if="groupDetail.goods_type && groupDetail.goods_type !== 2">
      <div class="btn" @click="showTeacher()">
        <img :src="weChatIcon"/>
      </div>
      <div class="btn big price" @click="groupPay(1)">
        <span>¥{{groupDetail.current_price/100}}</span>
        <div>立即购买</div>
      </div>
    </footer>
    </div>
    <div v-if="groupDetail.status !== 1">
      <footer>
        <div style="color: #888">
          已售罄
        </div>
      </footer>
    </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 html2canvas from 'html2canvas'
  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,
        refIcon:refIcon,
        swiperOption: {
          pagination: {
            el: '.swiper-pagination'
          }
        },
        QRCodeB:false,
        dataURL:null,
        user_id:null,
        invite_code_f:true,
        invite_code:'',
        shopId:'',
        groupId:null,
        groupDetail:false,
        groupData:null,
      }
    },
    mounted(){
      this.getDetail();
    },
    methods:{
      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') !== ''){
          setTimeout(()=>{
            Indicator.close();
            if(!this.invite_code){
              this.invite_code = 'CC-USER'
            }
              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.qrcode(URL);
              this.refVisible = true;
              this.$nextTick(()=>{
                if(!this.dataURL){
                  setTimeout(()=>{
                    let {
                      height,
                      width
                    } = 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];
                    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;
                    }).catch(res=>{alert(res);console.log()});
                  },500)
                }else{

                }
              })
          },500)

        }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 => {
          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: option.product_title, // 分享标题
              desc: option.desc,// 分享描述
              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: option.product_title, // 分享标题
              desc: option.desc,// 分享描述
              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 = '';
        //团购 不处理invite_code
        if(type === 0 ){
          URL = `${process.env.BUY_URL}shopId=${this.shopId}&groupId=${this.groupId}&invite_code=${this.invite_code}`;
        }else{
          // 处理invite_code
          if(!this.invite_code){
            this.invite_code = 'CC-USER-'+this.user_id;
            URL = `${process.env.BUY_URL}shopId=${this.shopId}&invite_code=${this.invite_code}`
          }else{
            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]}`;
            URL = `${process.env.BUY_URL}shopId=${this.shopId}&invite_code=${code}-${this.user_id}`
          }
        }
        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 === 2 ){
            this.invite_code_f = false
          }
        }
        getUserDetailApi().then(res=>{
            this.user_id=res.user_id;
        });
        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){
                    if(res.buy_type === 1){
                      this.$router.push({name:'buySuccess',query:{out_trade_no:res.out_trade_no}});
                    }else{
                      this.$router.push({name:'success',query:{out_trade_no:res.out_trade_no}});
                    }
                  }
                });
              }
              if(window.location.href.indexOf('groupId')>-1){
                this.groupId = this.$route.query.groupId;
                getGroupDetailApi(this.groupId).then(res=>{
                  this.groupData = res
                });
                this.onShare(0)
              }else{
                this.onShare(1)
              }
            }
          })
        }

      },
      showTeacher(){
        this.popType = false;
        this.popupVisible = true
      },
      groupPay(type){
        let query = {shopId: this.shopId,invite_code:this.invite_code};
        if(this.groupId){
          query.group_order_id = this.groupId
        }
        if(type === 0 && !this.groupId){
          query.type='single';
          window._hmt.push(['_trackEvent', '购买', "商品页团购单独购买",`id${this.shopId}`,this.invite_code]);//百度统计
        }else if (type === 0 && this.groupId){
          window.location.href = `/#/buyDetail?shopId=${this.shopId}`;
          window._hmt.push(['_trackEvent', '购买', "商品页团购重新开团",`id${this.shopId}`,this.invite_code]);//百度统计
        } else{
          window._hmt.push(['_trackEvent', '购买', "商品页购买",`id${this.shopId}`,this.invite_code]);//百度统计
          query.type=''
        }
        this.$router.push({
          name: 'buy',
          query:query
        })
      }
    }
  }
</script>
<style>
  img,video{
    max-width: 100%;
  }
</style>
<style scoped lang="less">
  @import "../../util/public";
  .img-cvs{
    position: absolute;
    width: 233 * @toVw;
    top: 176 * @toVw;
    left: 29 * @toVw;
    .qrcode{
      position: absolute;
      top: 305 * @toVw;
      left: 15 * @toVw;
      width: 60 * @toVw;
    }
  }
  .cvs-img{
    position: absolute;
    width: 233 * @toVw;
    top: 176 * @toVw;
    left: 29 * @toVw;
    z-index: 10;
  }
  .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: 500/7.5vw;
      padding:30/7.5vw 30/7.5vw;
      font-size: 16px;
      color: #333333;
      .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>