import { makeAutoObservable } from 'mobx';
import { CHANNEL_PARAMS } from '@src/utils/constants';
import { isWeChat, onUpdateShare } from '@src/utils/share';
import { showShareGuide } from "@spark/share";
import store from '.';
import { isWechatMini } from '@src/utils/utils';
import { accessLog } from 'duiba-utils';

const shareStore = makeAutoObservable({
  /**
   * 被动分享
   **/
  async doShare() {
    accessLog(503, { from: CFG.channel })
    // 首页链接（不带邀请参数）
    let shareUrl = `${CFG.index}&shareCode=${store.homeInfo?.shareCode}${!!store.userInfo?.unionId ? `&uid=${store.userInfo.unionId}` : ""}`
    this.initShareInfo(shareUrl)
    // 分享引导蒙层
    if (isWeChat()) {
      showShareGuide()
    }
  },

  /**
   * 初始化分享
   * @param shareTargetUrl 分享链接
   **/
  async initShareInfo(shareTargetUrl) {
    // 首页 （页面初始化分享 用到的当前页面链接 + 长航参数 + 用户uid）
    const initUrl = location.href + `&shareCode=${store.homeInfo?.shareCode}` + (!!store.userInfo?.unionId ? `&uid=${store.userInfo.unionId}` : "")
    let { miniProgramUrl = {}, shareInfo = {}, shareMiddle = '' } = store.frontVariable || {}

    const {
      title,      // 分享标题
      content,    // 分享描述
      thumbnail,       // 缩略图-非小程序端
      thumbnail_mini   // 缩略图-小程序端
    } = shareInfo

    // const isMini = await isWechatMini() == 'mini'

    // 分享主副标题
    const share_title = title
    const share_content = content

    let link = ''
    link = shareMiddle?.replace("channelName", CFG.channel)
    if (store.homeInfo?.changHangParam) {
      link = link?.replace("changHangParam", store.homeInfo.changHangParam)
    }
    link = link.replace("activityUrl", encodeURIComponent(shareTargetUrl || initUrl))
    link = encodeURIComponent(link);
    const shareData = {
      sharedesc: share_title,
      shareimg: thumbnail_mini,
      shareurl: `/pages/webviewByToken/index?url=${link}`
    }

    console.info('shareData', shareData);
    if (CFG.channel == CHANNEL_PARAMS.THD_MINI) {
      wx.miniProgram.postMessage({
        data: {
          title: share_title, // 标题
          desc: share_content, // 描述
          imageUrl: thumbnail_mini, // 图片
          path: `${miniProgramUrl?.['taihaodian']}?shareUrl=${link}&source=crhd`
        }
      });
      return;
    } else {
      wx.miniProgram.postMessage({
        data: shareData
      });
    }
    // else {
    //     let wxLink = `${CFG.domain}${miniProgramUrl?.['gongzhong']}&redirectUrl=${encodeURIComponent(link)}`;
    //     onUpdateShare({
    //         title: share_title,
    //         content: share_content,
    //         thumbnail: thumbnail,
    //         url: wxLink
    //     })
    // }

  },

})
export default shareStore;
