<template>
  <div>
    <div class="activity">
      <img class="headerImg" :src="header1">
      <img class="headerImg" :src="header2">
      <div class="inviteContainer">
        <img class="invite-title" :src="inviteResultTitle">
        <div class="invite-list">
          <div class="flex-center i-title">
            <span>受邀购买</span>
            <span>已获奖金</span>
          </div>
          <div class="flex-center i-num red">
            <span>{{userNum}}人</span>
            <span>{{earnings / 100}}元</span>
          </div>
        </div>
        <img class="noData" :src="noData" v-if="userNum === 0"/>
        <template v-if="userNum != 0">
          <ul class="p-list">
            <li v-for="data in inviteList">
              <div class="flex-start no-margin">
                <img :src="data.avatar"/>
                <span>{{data.nickname}}</span>
              </div>
              <span class="no-margin">{{data.pay_at | formatDate}}</span>
            </li>
          </ul>
          <img v-if="inviteList && inviteList.length > 3" class="moreBtn" :src="moreResult" @click="goToInviteList">
        </template>
      </div>
      <img class="headerImg" :src="header4">
      <div class="invite-btn">
        <img :src="inviteBtn" @click="goToInvite">
      </div>
    </div>
  </div>
</template>

<script>
  import  QRCode from 'qrcodejs2'
  import { Indicator } from 'mint-ui';
  import {getwechatParam,getGoodsDetailApi,getGroupDetailApi,getStatusWechatApi,getUserDetailApi,getInviteResultApi,getInviteListApi} 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'

  // import header_1 from '../../assets/activity/header_01.png'
  import header_1 from '../../assets/activity/header_t01.png'
  import header_2 from '../../assets/activity/header_02.png'
  // import header_4 from '../../assets/activity/header_04.png'
  import header_4 from '../../assets/activity/header_t04.png'
  import invite_result_title from '../../assets/activity/invite_result.png'
  import more_result from '../../assets/activity/more.png'
  import invite_poster from '../../assets/activity/btn.png'
  import noData from '../../assets/activity/no_data.png'
  export default {
    name: "index",
    data(){
      return {
        header1: header_1,
        header2: header_2,
        header4: header_4,
        inviteResultTitle: invite_result_title,
        moreResult: more_result,
        inviteBtn: invite_poster,
        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,
        noData: noData,
        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,
        earnings: 0,
        userNum: 0,
        inviteList: [],
        shareTitle: '唱唱启蒙英语邀友返现金',
        shareDesc: '唱唱英语90天成长营，每成功邀请1人即可返现金88元，多邀多得，速来~'
      }
    },
    filters: {
      formatDate(value){
          if(value) {
              return value.split(' ')[0]
          } else {
              return ''
          }
      }
    },
    mounted(){
      this.getInviteResult();
      this.getInviteList();
      this.enableShare();
    },
    methods:{
      goToInvite(){
        let query = {}
        if(window.location.href.indexOf('shopId')>-1){
          query.shopId = this.$route.query.shopId;
        }
        if(window.location.href.indexOf('groupId')>-1){
          query.groupId = this.$route.query.groupId;
        }
        if(window.location.href.indexOf('invite_code')> -1) {
          query.invite_code = this.$route.query.invite_code;
        }
        this.$router.push({name:'activityInvite',query:query})
      },
      goToInviteList(){
        let query = {}
        if(window.location.href.indexOf('shopId')>-1){
          query.shopId = this.$route.query.shopId;
        }
        if(window.location.href.indexOf('groupId')>-1){
          query.groupId = this.$route.query.groupId;
        }
        if(window.location.href.indexOf('invite_code')> -1) {
          query.invite_code = this.$route.query.invite_code;
        }
        this.$router.push({name:'inviteList',query:query})
      },
      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'
            }
            getUserDetailApi().then(res=>{
              this.user_id=res.user_id;
              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}`
              }
              console.log(URL);
              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() {
        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: that.shareTitle, // 分享标题
              desc: that.shareDesc,// 分享描述
              link: window.location.href, // 分享链接
              imgUrl: '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: window.location.href, // 分享链接
              imgUrl: '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
//        })
      },
      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}});
                  }
                });
              }
              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)
              }
            }
          })
        }

      },
      getInviteResult(){
        getInviteResultApi().then(res=>{
          this.earnings = res.earnings;
          this.userNum = res.user_num;
        });
      },
      getInviteList(){
        let json = {
          page: 1,
          limit: 4
        }
        getInviteListApi(json).then(res=>{
          this.inviteList = res.list
        });
      }
    }
  }
</script>
<style>
  img,video{
    max-width: 100%;
  }
</style>
<style scoped lang="less">
  @import "../../util/public";
  @red: #fc4a1b;
  @borderRadius: 8px;
  .activity {
    padding-bottom: 120 * @toVh;
    background-color: #1a65f7;
  }
  .headerImg {
    width: 100%;
  }
  .inviteContainer {
    position: relative;
    margin-left:29 / 2 * @toVw;
    margin-right:29 / 2 * @toVw;
    margin-top: 128 / 2 * @toVh;
    min-height: 100px;
    text-align: center;
    background-color: #fff;
    border-radius: @borderRadius;
    padding-top: 80 / 2 * @toVw;
    padding-bottom: 38 / 2 * @toVh;
  }
  .invite-title {
    position: absolute;
    width: 527 / 2 * @toVw;
    left: 50%;
    margin-left: -527 / 4 * @toVw;
    top: -60 / 2 * @toVw;
    height: auto;
  }
  .invite-list {
    margin-left: 32 / 2 * @toVw;
    margin-right: 32 / 2 * @toVw;
    padding: 28 / 2 * @toVh;
    border: 1px solid @red;
    border-radius: @borderRadius;
    .i-title {
      font-size: 14px;
    }
    .i-num {
      font-size: 18px;
    }
  }
  .flex-center {
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    align-items: center;
  }
  .flex-start {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;
  }
  .red{
    color: @red;
  }
  .p-list {
    margin: 0 32 / 2 * @toVw;
    padding: 0;
    li {
      display: flex;
      flex-flow:  row nowrap;
      justify-content: space-between;
      align-items: center;
      margin: 0;
      padding: 8 * @toVw;
      img {
        width: 74 / 2 * @toVw;
        height: 74 / 2 * @toVw;
        margin-right: 5px;
        border-radius: 50%;
      }
    }
  }
  .no-margin {
    margin: 0;
  }
  .moreBtn {
    width: 220 / 2 * @toVw;
    height: auto;
  }
  .invite-btn {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding-top: 10 * @toVw;
    box-sizing: content-box;
    text-align: center;
    background-color: #fff;
    img {
      width: 504 / 2 * @toVw;
      height: auto;
    }
  }
  .noData {
    width: 80%;
    margin-top: 15px;
  }
</style>
