<template>
  <div class="share-page">
    <div class="share-block">
      <div class="bg-title" :style="{backgroundImage:`url('${shareBg}')`}">
      </div>
      <div class="bg-desc">
      </div>
      <img :src="dataURL" class="cvs-img" id="cvs-img"/>
      <div class="content" v-if="userDetail"  ref="imageWrapper" id="capture">
        <img :src="shareConBg" class="content-black"/>
        <div class="main-content">
          <div class="head-block">
            <img :src="userDetail.avatar"/>
          </div>
          <div class="content-title" :style="{backgroundImage:`url('${shareTitle}')`}">
            {{userDetail.nickname}}
          </div>
          <div class="main-text">
            <div class="title">累计学习</div>
            <div v-if="watchDetail" class="day">
              {{watchDetail.total_day}} <span>Days</span>
            </div>
          </div>
          <div class="main-desc">
            <span>
            继续坚持
            </span>
            <br>
            学无涯  行必知
          </div>
        </div>
        <div class="main-content-desc">
          <img :src="share_code_bg">
          <div id="qrcode" class="qrcode"></div>
        </div>
      </div>
      <div class="share-btn">
        <img :src="shareBtn" @click="showShare()"/>
      </div>
    </div>
    <img :src="share_close" class="share_close" @click="$emit('closeShare')"/>
    <div class="tips" v-if="shareVisible" @click="shareVisible=false">
      <img :src="share_tips">
    </div>
  </div>
</template>

<script>
  import shareBg from '../../assets/newLesson/shareBg.png'
  import shareConBg from '../../assets/newLesson/shareConBg.png'
  import shareTitle from '../../assets/newLesson/shareTitle.png'
  import shareBtn from '../../assets/newLesson/share_button.png'
  import share_close from '../../assets/newLesson/share_close.png'
  import  QRCode from 'qrcodejs2'
  import html2canvas from 'html2canvas'
  import {getwechatParam,getUserWatchApi,getShortApi,subUserLessonApi} from "../../service/api";
  import share_code_bg from '../../assets/newLesson/share-code-bg.png'
  import share_tips from '../../assets/Bitmap@2x.png'

  export default {
    name: "share",
    data(){
      return {
        shareVisible:false,
        shareBg:shareBg,
        share_close:share_close,
        share_tips:share_tips,
        shareConBg:shareConBg,
        shareTitle:shareTitle,
        shareBtn:shareBtn,
        userDetail:null,
        dataURL:null,
        watchDetail:null,
        share_code_bg:share_code_bg
      }
    },
    mounted(){
      this.initPage()
    },
    methods:{
      showShare(){
        this.shareVisible = true;
        this.$sa.track('watchClick',{
          dayModule:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9),
          weekName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
          elementName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9) + '-'+ JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
          themeID:JSON.parse(localStorage.getItem('lessonDetail')).themeID,
          themeName:JSON.parse(localStorage.getItem('lessonDetail')).themeName,
          goodsID:JSON.parse(localStorage.getItem('lessonDetail')).goodsID,
          classID:JSON.parse(localStorage.getItem('lessonDetail')).classID,
          buttonName:'分享到微信',
          partName:this.contentData.partName,
          elementID:this.$route.query.elementId.toString(),
        });
        let lessonDetail = JSON.parse(localStorage.getItem('lessonDetail'));
        let nowTime = Date.parse(new Date());
        let json = {
          page_type:0,
          page_id:4,
          stay_time:0,
        };
        subUserLessonApi(this.$route.query.elementId,this.$route.query.category_id,this.$route.query.periods_id,json).then(res=>{
          lessonDetail.total_watch_time = res;
          lessonDetail.nowTime = nowTime;
          localStorage.setItem('lessonDetail',JSON.stringify(lessonDetail));
        });
      },
      initPage(){
          this.userDetail = JSON.parse(localStorage.getItem('userDesc'));
          this.toDataURLBase64(this.userDetail.avatar.replace('http://','https://'),  (avatar) =>{
            this.toDataURLBase64(this.shareConBg,(cal)=>{
              this.shareConBg = cal;
              this.userDetail.avatar = avatar;
              getUserWatchApi().then(res=>{
                this.watchDetail = res;
                this.refshow()
              })
            })
          });
      },
      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('分享成功');
                that.$emit('backList')
              },
              cancel: function() {
                console.log('分享失败');
                that.$emit('backList')
              }
            });
            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() {
                this.$sa.track('watchClick',{
                  dayModule:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9),
                  weekName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
                  elementName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9) + '-'+ JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
                  themeID:JSON.parse(localStorage.getItem('lessonDetail')).themeID,
                  themeName:JSON.parse(localStorage.getItem('lessonDetail')).themeName,
                  goodsID:JSON.parse(localStorage.getItem('lessonDetail')).goodsID,
                  classID:JSON.parse(localStorage.getItem('lessonDetail')).classID,
                  buttonName:'完成分享',
                  partName:this.contentData.partName,
                  elementID:this.$route.query.elementId.toString(),
                });
                that.$emit('backList')
              },
              cancel: function() {
                this.$sa.track('watchClick',{
                  dayModule:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9),
                  weekName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
                  elementName:JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(0,9) + '-'+ JSON.parse(localStorage.getItem('lessonDetail')).domTitle.slice(10,JSON.parse(localStorage.getItem('lessonDetail')).domTitle.length),
                  themeID:JSON.parse(localStorage.getItem('lessonDetail')).themeID,
                  themeName:JSON.parse(localStorage.getItem('lessonDetail')).themeName,
                  goodsID:JSON.parse(localStorage.getItem('lessonDetail')).goodsID,
                  classID:JSON.parse(localStorage.getItem('lessonDetail')).classID,
                  buttonName:'取消分享',
                  partName:this.contentData.partName,
                  elementID:this.$route.query.elementId.toString(),
                });
              }
            });
          })
        })
      },
      onShare(URL) {
        this.enableShare({
          product_title: `我家宝宝正在【唱唱启蒙英语】唱学英语，已坚持${this.watchDetail.total_day}天`, // 分享标题
          desc: `赠您【1元领取价值398元课程】特权，和我们一起快乐启蒙英语吧`,//
          shareIcon:'https://cdn.singsingenglish.com/logo/logo.jpg',
          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()
      },
      refshow(){
        let URL = process.env.API_URL+'#/shareGoods?userID='+ this.userDetail.user_id;
        this.onShare(URL);
        getShortApi({url:URL}).then(res=>{
          this.qrcode(res.url);
          this.$nextTick(()=>{
            let {
              width,
            } = document.getElementById('capture').getClientRects()[0];
            document.getElementById('capture').style.width = width + 'px';
            let {
              height1,
              width1
            } = document.getElementById('capture').getClientRects()[0];
            setTimeout(()=>{
              html2canvas(document.getElementById('capture'),{
              async: true,
              timeout: 500,
              scrollX:1,
              scale: 4,
              width: width1,
              height: height1,
              letterRendering: true,
            }).then((canvas) => {
              let dataURL = canvas.toDataURL("image/jpg");
              this.dataURL = dataURL;
            }).catch(res=>{alert(res);console.log()});},500)

          })
        })

      },
      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: 70,
            height: 70, // 高度
            text: data, // 二维码内容
            image: ''
          });
        }
      },
    },
    props:[
      'contentData'
    ]
  }
</script>
<style scoped lang="less">
  @import "../../util/public";
  .share-page{
    position: fixed;
    background: #EEEEEE;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    z-index: 10;
    .share-block{
      position: absolute;
      border-radius: 8*@toVw;
      top: 20*@toVw;
      left: 20*@toVw;
      right: 20*@toVw;
      bottom: 20*@toVw;
      overflow: auto;
      .bg-title{
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        height: 60*@toVw;
        background-size: 100% 100%;
        z-index: -1;
      }
      .bg-desc{
        position: absolute;
        top: 58*@toVw;
        left: 0;
        right: 0;
        bottom: 0;
        background: white;
        z-index: -1;
        border-radius: 0 0 8*@toVw 8*@toVw;
      }
      #cvs-img{
        position: absolute;
        width: 291*@toVw;
        top: 21*@toVw;
        left: 23*@toVw;
        z-index: 1;
      }
      .content{
        width: 291*@toVw;
        height: (422-53)*@toVw;
        padding-top: 53*@toVw;
        margin-top: 20*@toVw;
        background-size: 100% 100%;
        position: relative;
        .content-black{
          position: absolute;
          z-index: -1;
          width: 100%;
          top: 0;
          right: 0;
          left: 0;
          bottom: 0;
        }
      }
      .main-content{
        width: 261*@toVw;
        height: 263*@toVw;
        background: white;
        border-radius: 8*@toVw;
        position: relative;
        .main-text{
          padding-top: 100*@toVw;
          width: 215*@toVw;
          text-align: center;
          margin: auto;
          border-bottom: 1*@toVw solid #EEEEEE;
          .title{
            font-size:16*@toVw;
            font-family:PingFang-SC-Medium;
            font-weight:500;
            color:rgba(51,51,51,1);
          }
          .day{
            font-size:48px;
            margin: 5*@toVw 0;
            font-family:PingFang-SC-Bold;
            font-weight:bold;
            color:rgba(105,192,255,1);
            span{
              font-size:20px;
              font-family:PingFang-SC-Bold;
              font-weight:bold;
              color:rgba(105,192,255,1);
            }
          }
        }
        .main-desc{
          margin-top: 10*@toVw;
          text-align: center;
          font-size:12px;
          font-family:PingFang-SC-Medium;
          font-weight:500;
          color:rgba(0,0,0,1);
          span{
            font-size:16px;
            font-family:PingFang-SC-Medium;
            font-weight:500;
            display: inline-block;
            margin: 0 0 5*@toVw 0;
          }
        }
        .head-block{
          position: absolute;
          height: 85*@toVw;
          width: 85*@toVw;
          text-align: center;
          border-radius: 200*@toVw;
          left: 50%;
          margin-left: -40*@toVw;
          background: white;
          top: -38*@toVw;
          img{
            border-radius: 200*@toVw;
            width: 64*@toVw;
            margin-top: 7*@toVw;
            height: 64*@toVw;
          }
        }
        .content-title{
          width: 226*@toVw;
          height: 54*@toVw;
          line-height: 50*@toVw;
          color: white;
          background: white;
          font-size: 14*@toVw;
          text-align: center;
          background-size: 99.99% 99.99%;
          position: absolute;
          top: 26*@toVw;
          left: 50%;
          margin-left: -112.5*@toVw;
        }
      }
      .share-btn{
        margin-top: 22*@toVw;
        text-align: center;
        img{
          width: 240*@toVw;
        }
      }
      .main-content-desc{
        width: 261*@toVw;
        height: 82*@toVw;
        background: white;
        border-radius: 8*@toVw;
        margin-top: 10*@toVw;
        position: relative;
        img{
          width: 100%;
        }
        .qrcode{
          position: absolute;
          top: 5*@toVw;
          right: 5*@toVw;
        }
      }
    }
    .share_close{
      position: fixed;
      width: 20*@toVw;
      top: 19*@toVw;
      right: 13*@toVw;
    }
    .tips{
      background: rgba(0,0,0,0.5);
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      z-index: 99999999;
      text-align: right;
      img{
        width: 80%;
      }
    }
  }
</style>
