<template>
  <div class="sharMake" v-show="isShow" @click="_toggleShare(false)"></div>
</template>

<script>
import { getWxJsapiPackage, shareSuccessBack } from '@/plugins/API/apiAll';
import { mapGetters } from 'vuex';
import UserAgent from '@/plugins/UserAgent/index';
export default {
  name: 'share-box',
  data() {
    return {
      isShow: false
    };
  },
  computed: {
    ...mapGetters({
      channelInfo: 'channelInfo',
      userInfo: 'userInfo',
      showRedInfo: 'showRedInfo'
    }),
    shareConfig() {
      const self = this;
      return {
        title: this.channelInfo.shareTitle || this.channelInfo.channelName,
        desc: this.channelInfo.shareSubTitle || window.location.href,
        link: this.updateQueryStringParameter(window.location.href, 'refererId', this.userInfo.id || 0),
        imgUrl: this.channelInfo.shareImgUrl || this.channelInfo.mpsBackgroundUrl,
        success() {
          self.shareSuccessBack();
        },
        fail() {
          if (process.env.NODE_ENV === 'development') {
            self.shareSuccessBack();
          }
        }
      };
    }
  },
  mounted() {
    this.$Bus.$on('bus-showShare', this._toggleShare);
    this.$Bus.$on('bus-initWX', this._initWXAll);
    this._initWXAll()
  },
  methods: {
    _initWXAll() {
      if (UserAgent.isWx()) {
        this._InitWXShare();
        this._getWxJsapiPackage();
      }
    },
    updateQueryStringParameter(uri, key, value) {
      if (!value) {
        return uri;
      }
      const re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
      const separator = uri.indexOf('?') !== -1 ? "&" : "?";
      if (uri.match(re)) {
        return uri.replace(re, '$1' + key + "=" + value + '$2');
      }
      else {
        return uri + separator + key + "=" + value;
      }
    },
    _toggleShare(bol) {
      if (UserAgent.isWx()) {
        this.isShow = bol;
      } else {
        this.$layer.msg(`请在微信中进行分享`);
      }
    },
    async _getWxJsapiPackage() {
      const res = await getWxJsapiPackage({
        uin: this.channelInfo.uin,
        cname: this.channelInfo.cname,
        href: window.location.href
      });
      if (res.code === 200 && res.errorCode === 0) {
        this._initWXSdk(res.data);
      }
    },
    _initWXSdk(info) {
      window.wx.config({
        debug: false,
        appId: info.appId,
        timestamp: info.timestamp,
        nonceStr: info.nonceStr,
        signature: info.signature,
        jsApiList: [
          'onMenuShareTimeline',
          'onMenuShareAppMessage',
          'uploadImage',
          'chooseImage',
          'previewImage'
        ]
      });
    },
    // 微信分享init
    _InitWXShare() {
      const self = this;
      window.wx.ready(() => {
        window.wx.onMenuShareTimeline(self.shareConfig);
        window.wx.onMenuShareAppMessage(self.shareConfig);
      });
      window.wx.error(err => {
        console.log(err);
      });
    },
    // 分享回调
    async shareSuccessBack() {
      let redId = '';
      if (this.showRedInfo.type === 2 || this.showRedInfo.type === 4) {
        redId = this.showRedInfo.id;
      }
      const res = await shareSuccessBack({
        uin: this.channelInfo.uin,
        channelId: this.channelInfo.id,
        redpacketId: redId
      });
      if (res.code === 200 && res.errorCode === 0) {
        if (this.showRedInfo.type === 2) {
          this.$layer.msg(`获得${res.data}元红包`);
          this.$Bus.$emit('bus-delShareList', redId);
        } else if (this.showRedInfo.type === 4 && res.data.reviveCard) {
          this.$layer.msg(`获得分享获得${res.data.reviveCard}复活卡`);
        }
        this.$Bus.$emit('bus-shareSuccess');
      } else {
        if (this.showRedInfo.type === 2) {
          this.$Bus.$emit('bus-delShareList', redId);
        }
      }
      this.isShow = false;
    }
  },
  beforeDestroy() {
    this.$Bus.$off('bus-showShare', this._toggleShare);
    this.$Bus.$off('bus-initWX', this._initWXAll);
  }
};
</script>

<style lang="less" scoped>
.sharMake {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  background-color: rgba(0, 0, 0, 0.3);
  background-image: url('./img/icon-share.png');
  background-repeat: no-repeat;
  background-position: top right;
  background-size: 3rem auto;
}
</style>
