<template>
  <div class="share">
    <cr-share
      v-model="showShare"
      :types="types"
      @close="shareCloseChange"
      @click-share-item="bundleShareClickItem"
    />
    <share-pic ref="sharePic" :share-pic-data="sharePicData" @outputPicUrl="outputPicUrl" />
  </div>
</template>
<script>
import groupBuyApi from '@/api/groupBuy';
import sharePic from './sharePic';
import MpBridge from '@/service/mp';
import Bridge from '@qg/js-bridge';
// import { mapState } from 'vuex';
// import { registeredEvents } from '@/service/sa.service';
import { EventBus } from '@/service/utils.service';
import { isApp, isWxMp } from '@/service/validation.service';
import qs from 'qs';
import config from '@/config';
import { saTrackEvent } from '@/service/sa.service';

export default {
  name: 'GroupShare',
  components: {
    sharePic
  },
  props: {},
  data() {
    return {
      showShare: false,

      showFlag: false,
      shareOptions: null,
      nativeBridge: null,
      types: [
        { value: 'weixin', disabled: false },
        { value: 'pic', disabled: false }
      ],

      sharePicData: {},

      shareInfo: {},
      type: 0,
      typeStatus: {
        0: '入口活动页面',
        1: '拼团列表页面',
        2: '详情页面分享',
        3: '支付成功分享'
      }
    };
  },
  created() {
    if (isWxMp) {
      this.nativeBridge = new MpBridge();
      return;
    }
    this.nativeBridge = new Bridge();
  },
  mounted() {
    EventBus.$on('goods_share_info', ({ shareInfo, type }) => {
      if (!isApp && !isWxMp) {
        this.tipDialogMessage();
        return;
      }
      this.$store.dispatch('change_loading', true);
      this.type = type;

      // 如果shareInfo为data数据则直接创建海报
      if (typeof shareInfo === 'object') {
        this.sharePicData = shareInfo;
        this.handleShareInfo(shareInfo);
        return;
      }

      this.getGroupShareInfo(shareInfo);
    });
  },
  methods: {
    async outputPicUrl(posterUrl) {
      this.sharePicData.posterUrl = posterUrl;
      this.getShareData();
      // 弹出分享框
      if (isApp) {
        // 如果是app环境直接调用app方法
        this.appShareEventChange();
      }
      if (isWxMp) {
        this.shareOpenWechat();
      }
      this.$store.dispatch('change_loading', false);
    },
    handleShareInfo(shareInfo) {
      // 处理是否已经有 海报地址，如果有，小程序弹出地步框，App直接弹出分享
      if (shareInfo.posterUrl) {
        this.getShareData();
        if (isWxMp) {
          // 弹出弹出框
          this.shareOpenWechat();
        }
        if (isApp) {
          // 直接调用app分享方法
          this.appShareEventChange();
        }
        this.$store.dispatch('change_loading', false);
        return;
        // 如果传递的数据有海报则不处理
      }
      // 否则直接创建海报
      this.$refs.sharePic.createAndUploadPic(this.sharePicData);
    },
    async getGroupShareInfo(orderNo) {
      try {
        const [res] = await groupBuyApi.getGroupShareInfo(orderNo);
        this.$store.dispatch('change_loading', true);
        this.sharePicData = res;
        this.$refs.sharePic.createAndUploadPic(this.sharePicData);
      } catch (err) {
        this.$store.dispatch('change_loading', false);
        console.log(err);
      }
    },
    async getShareData() {
      let sharePicData = this.filterShareInfo();
      this.shareInfo = {
        title: sharePicData.skuName,
        desc: sharePicData.desc || '',
        link: sharePicData.linkPath, // 页面地址
        imgUrl: sharePicData.skuImg, // 图片地
        posterUrl: sharePicData.posterUrl
      };
      // this.shareInfo = {
      //   title: '超值0元购',
      //   desc: '拼团成功全额退款免费送回家',
      //   link: 'http://192.168.29.73:8080/groupBuy/list?activityId=82&vccToken={token}', // 页面地址
      //   imgUrl: 'https://appsync.lkbang.net/FrAnqyCCc2lLl13p_bW0hDCNvmqP', // 图片地
      //   posterUrl: 'https://kdspstatic.q-gp.com/sku_pic_3761633428276594.png'
      // };
    },
    filterShareInfo() {
      const type = this.type;
      let shareInfo = this.sharePicData;
      let linkPath = '';
      let detailData = {
        skuNo: shareInfo.skuNo,
        goodsSpecialId: shareInfo.goodsSpecialId,
        activityId: shareInfo.activityId,
        templateId: shareInfo.templateId,
        templateDetailId: shareInfo.templateDetailId,
        vccToken: encodeURIComponent('{token}')
      };
      switch (type) {
        case 0:
          linkPath = `${config.localHost}/groupBuy/list?activityId=${
            shareInfo.activityId
          }&vccToken=${encodeURIComponent('{token}')}`;
          break;
        case 1:
        case 2:
        case 3:
          if (shareInfo.groupBuyGroupId) {
            detailData.groupBuyGroupId = shareInfo.groupBuyGroupId;
          }
          linkPath = qs.stringify(detailData);
          linkPath = `${config.localHost}/groupBuy/skuInfo?${linkPath}`;
          break;
      }
      shareInfo.linkPath = this.weixinHandleLink(linkPath);
      return shareInfo;
    },
    weixinHandleLink(linkPath) {
      if (isWxMp) {
        return `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(linkPath))}`;
      }
      // // 本地测试时走的逻辑
      // if (isApp) {
      //   const linkPrve = `https://mall.q-gp.com/common/launch?wxapp=gh_e1d790d67513&jumpUrl=${encodeURIComponent(
      //     'pages/groupbuy/webview'
      //   )}&terminal=1`;
      //   const linkParams = encodeURIComponent(JSON.stringify({ url: linkPath }));
      //   return `${linkPrve}&extraInfo=${linkParams}`;
      // }
      return linkPath;
    },
    shareOpenWechat() {
      this.showShare = true;
    },
    shareCloseChange() {
      this.showShare = false;
    },
    bundleShareClickItem(ev) {
      // 小程序的操作
      if (ev === 'weixin') {
        // 弹窗提示需要右上角
        this.shareDialogConfirm();
        this.emitRunPostMessage();
      }
      if (ev === 'pic') {
        // 直接进行小程序海报页面跳转
        this.openTenetPosterUrl();
      }
      let sharePicData = this.sharePicData;
      saTrackEvent('H5_GroupZeroYuanPurchaseActivityPageSharePopupWindowBtnClick', {
        sku_no: sharePicData.skuNo || '',
        buttons_name: ev,
        activity_id: sharePicData.activityId || '',
        page_title: sharePicData.skuName || '',
        group_id: sharePicData.groupBuyGroupId || ''
      });
    },
    emitRunPostMessage() {
      const shareDic = this.shareInfo;
      this.nativeBridge.run({
        event: 'showShareView',
        data: {
          shareDic
        }
      });
    },
    openTenetPosterUrl() {
      // 打开小程序的海报下载页面
      const { posterUrl } = this.shareInfo;
      this.nativeBridge.openNewUrl({
        newUrl: `/pages/groupbuy/goodshare?url=${encodeURIComponent(JSON.stringify(posterUrl))}`
      });
    },
    shareDialogConfirm() {
      this.$store.dispatch('goods_share_close');
      this.$dialog({
        message: '请点击小程序右上角更多进行分享~',
        showCancelButton: false,
        confirmButtonText: '我知道了哦～',
        closeOnClickOverlay: !isApp && !isWxMp ? false : true,
        onConfirm: () => {}
      });
    },
    appShareEventChange() {
      const { title, desc, link, imgUrl, posterUrl } = this.shareInfo;
      // 进行App分享
      const data = {
        event: 'showShareView',
        data: {
          platform: ['weChat', 'timeLine', 'QQ', 'CopyLink', 'GeneratePoster'], //依次分别是微信、朋友圈、QQ好友、QQ空间、复制链接
          shareDic: {
            title,
            desc,
            link, // 页面地址
            imgUrl, // 图片地址
            posterUrl
          }
        }
      };
      this.nativeBridge.showShareView(data);
    },
    tipDialogMessage() {
      this.$dialog({
        message: '请在App或小程序中进行分享~',
        closeOnClickOverlay: !isApp && !isWxMp ? false : true,
        title: '',
        showCancelButton: false,
        confirmButtonText: '我知道了'
      });
    }
  }
};
</script>
<style lang="less"></style>
