<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 { EventBus } from '@/service/utils.service';
import { isApp, isWxMp, appVersion } 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,
      nativeBridge: null,
      types: [
        { value: 'weixin', disabled: false },
        { value: 'pic', disabled: false }
      ],

      sharePicData: {},
      shareInfo: {},
      type: 0,
      dataType: false,
      isCreatePic: isApp && +appVersion.replace(/\./g, '') < 8260 // 8251
      // 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.dataType = typeof shareInfo === 'object';
      this.$store.dispatch('change_loading', true);
      this.type = type;
      this.sharePicData = shareInfo;
      // 如果shareInfo为data数据则直接创建海报
      if (isApp) {
        this.createAppShareInfo(shareInfo);
      }
      if (isWxMp) {
        this.shareOpenWechat();
        this.$store.dispatch('change_loading', false);
      }
    });
  },
  methods: {
    outputPicUrl(posterUrl) {
      // 海报创建成功
      this.sharePicData.posterUrl = posterUrl;
      // 弹出分享框
      if (isApp) {
        // 如果是app环境直接调用app方法
        this.appShareEventChange();
      }
      if (isWxMp) {
        // 如果是小程序则直接跳转海报保存页面
        this.getShareData(); // 创建分享数据
        this.openTenetPosterUrl();
      }
      this.$store.dispatch('change_loading', false);
    },
    // 创建app前置分享
    createAppShareInfo(params) {
      if (this.dataType) {
        // 有海报数据时
        if (params.posterUrl) {
          this.appShareEventChange(); // 调用app分享
        } else {
          if (this.isCreatePic) {
            this.appShareEventChange(); // 调用app分享
          } else {
            this.$refs.sharePic.createAndUploadPic(params);
          }
        }
        this.$store.dispatch('change_loading', false);
        return;
      }
      // 通过orderNo创建分享数据
      this.getGroupShareInfo(params);
      this.$store.dispatch('change_loading', false);
    },
    async getGroupShareInfo(orderNo, isNotPic) {
      try {
        const [res] = await groupBuyApi.getGroupShareInfo(orderNo);
        this.$store.dispatch('change_loading', true);
        this.sharePicData = res;
        isWxMp && this.sendSaTrackEvent(res, !isNotPic ? 'pic' : 'weixin');
        this.$store.dispatch('change_loading', false);
        if (this.isCreatePic) {
          this.appShareEventChange(); // 调用app分享
        } else {
          !isNotPic && this.$refs.sharePic.createAndUploadPic(res);
        }
      } catch (err) {
        this.$store.dispatch('change_loading', false);
        console.log(err);
      }
    },

    // 点击微信弹出框按钮
    bundleShareClickItem(ev) {
      let params = this.sharePicData;
      this.dataType = typeof params === 'object' ? true : false;
      if (this.dataType) {
        // 发宋埋点
        this.sendSaTrackEvent(params, ev);
        // 获取分享数据
        this.getShareData();
        if (ev === 'weixin') {
          // 弹窗提示需要右上角点击分享
          this.shareDialogConfirm();
          this.emitRunPostMessage();
        }
        if (ev === 'pic') {
          if (params.posterUrl) {
            this.openTenetPosterUrl();
            return;
          }
          this.$refs.sharePic.createAndUploadPic(params);
        }
        return;
      }
      this.bundleClickOrderNo(params, ev);
    },
    sendSaTrackEvent(params, ev) {
      saTrackEvent('H5_GroupZeroYuanPurchaseActivityPageSharePopupWindowBtnClick', {
        sku_no: params.skuNo || '',
        buttons_name: ev,
        activity_id: params.activityId || '',
        page_title: params.skuName || '',
        group_id: params.groupBuyGroupId || ''
      });
    },

    async bundleClickOrderNo(params, ev) {
      if (ev === 'weixin') {
        // 只获取分享数据
        // 弹窗提示需要右上角点击分享
        await this.getGroupShareInfo(params, true);
        this.getShareData();
        this.shareDialogConfirm();
        this.emitRunPostMessage();
      }
      if (ev === 'pic') {
        this.getGroupShareInfo(params);
      }
    },
    getShareData() {
      // 创建分享数据
      const sharePicData = this.filterShareInfo();
      const tagName = this.type ? '[0元购] ' : '';
      const shareInfo = {
        title: `${tagName}${sharePicData.skuName}`,
        desc: sharePicData.desc || '',
        link: sharePicData.linkPath, // 页面地址
        imgUrl: sharePicData.skuImg, // 图片地
        posterUrl: sharePicData.posterUrl
      };
      this.shareInfo = shareInfo;
    },
    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.sharePicData = {};
      this.shareInfo = {};
      this.type = 0;
      this.dataType = false;
      this.showShare = false;
    },

    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() {
      this.getShareData();
      const { title, desc, link, imgUrl, posterUrl } = this.shareInfo;
      let shareDic = { title, desc, link, imgUrl };
      let platform = ['weChat', 'timeLine', 'QQ', 'CopyLink']; //依次分别是微信、朋友圈、QQ好友、QQ空间、复制链接
      if (!this.isCreatePic) {
        shareDic.posterUrl = posterUrl;
        platform.push('GeneratePoster');
      }
      // 进行App分享
      this.nativeBridge.showShareView({
        event: 'showShareView',
        data: {
          platform,
          shareDic
        }
      });
    },
    tipDialogMessage() {
      this.$dialog({
        message: '请在App或小程序中进行分享~',
        closeOnClickOverlay: !isApp && !isWxMp ? false : true,
        title: '',
        showCancelButton: false,
        confirmButtonText: '我知道了'
      });
    }
  }
};
</script>
<style lang="less"></style>
