<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';
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: {},

      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.type = type;
      if (typeof shareInfo === 'object') {
        this.sharePicData = shareInfo;
        this.handleShareInfo(shareInfo);
        // 如果shareInfo为data数据则直接创建海报
        return;
      }
      // 调用分享数据接口
      this.getGroupShareInfo(shareInfo);
    });
  },
  methods: {
    async outputPicUrl(posterUrl) {
      this.sharePicData.posterUrl = posterUrl;
      this.getShareData();
      // 弹出分享框
      if (isApp) {
        // 如果是app环境直接调用app方法
        this.appShareEventChange();
      }
      if (isWxMp) {
        this.shareOpenWechat();
      }
    },
    handleShareInfo(shareInfo) {
      // 处理是否已经有 海报地址，如果有，小程序弹出地步框，App直接弹出分享
      if (shareInfo.posterUrl) {
        this.getShareData();
        if (isWxMp) {
          // 弹出弹出框
          this.shareOpenWechat();
        }
        if (isApp) {
          // 直接调用app分享方法
          this.appShareEventChange();
        }
        return;
        // 如果传递的数据有海报则不处理
      }
      // 否则直接创建海报
      this.$refs.sharePic.createAndUploadPic();
    },
    async getGroupShareInfo(orderNo) {
      try {
        const [res] = await groupBuyApi.getGroupShareInfo(orderNo);
        this.sharePicData = res;
        this.$refs.sharePic.createAndUploadPic();
      } catch (err) {
        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
      };
    },
    filterShareInfo() {
      const type = this.type;
      let shareInfo = this.sharePicData;
      let linkPath = '';
      switch (type) {
        case 0:
          linkPath = `${config.localHost}/groupBuy/list?h=0&activityId=${shareInfo.activityId}`;
          break;
        case 1:
          linkPath = qs.stringify({
            skuNo: shareInfo.skuNo,
            groupBuyGroupId: shareInfo.groupBuyGroupId,
            goodsSpecialId: shareInfo.goodsSpecialId,
            activityId: shareInfo.activityId,
            templateId: shareInfo.templateId,
            templateDetailId: shareInfo.templateDetailId
          });
          linkPath = `${config.localHost}/groupBuy/skuInfo?h=0&${linkPath}`;
          break;
      }
      shareInfo.linkPath = this.weixinHandleLink(linkPath);
      return shareInfo;
    },
    weixinHandleLink(linkPath) {
      if (isWxMp) {
        return `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(linkPath))}`;
      }
      return linkPath;
    },
    shareOpenWechat() {
      this.showShare = true;
    },
    shareCloseChange() {
      this.showShare = false;
    },
    bundleShareClickItem(ev) {
      // 小程序的操作
      if (ev === 'weixin') {
        // 弹窗提示需要右上角
        this.shareDialogConfirm();
        this.emitRunPostMessage();
      }
      if (ev === 'pic') {
        // 直接进行小程序海报页面跳转
        this.openTenetPosterUrl();
      }
    },
    emitRunPostMessage() {
      const shareDic = this.shareInfo;
      console.log(shareDic);
      this.nativeBridge.run({
        event: 'showShareView',
        data: {
          shareDic
        }
      });
    },
    openTenetPosterUrl() {
      // 打开小程序的海报下载页面
      const { posterUrl } = this.shareInfo;
      console.log(posterUrl);
      this.nativeBridge.openNewUrl({
        newUrl: `/pages/goodshare/index?url=${encodeURIComponent(JSON.stringify(posterUrl))}`
      });
    },
    shareDialogConfirm() {
      this.$store.dispatch('goods_share_close');
      this.$dialog({
        message: '请点击小程序右上角更多进行分享~',
        showCancelButton: false,
        confirmButtonText: '我知道了哦～',
        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或小程序中进行分享~',
        title: '',
        showCancelButton: false,
        confirmButtonText: '我知道了'
      });
    }
  }
};
</script>
<style lang="less"></style>
