import API from "@/api";
import {isWeiXin} from "@/AppTools.ts";

export interface IWxShareInfo {
  title: string,
  desc: string,
  link: string,
  imgUrl: string,
}

function invokeWX(shareInfo: IWxShareInfo) {

  wx.onMenuShareTimeline({
    title: shareInfo.title,
    link: shareInfo.link,
    imgUrl: shareInfo.imgUrl,
    success: function () {
    },
    cancel: function () {
    }
  });
  wx.onMenuShareAppMessage({
    title: shareInfo.title,
    desc: shareInfo.desc,
    link: shareInfo.link,
    imgUrl: shareInfo.imgUrl,
    success: function () {
    },
    cancel: function () {
    }
  });
}

export async function initWx(shareInfo: IWxShareInfo) {

  if (!isWeiXin()) {
    return;
  }

  const {
    success,
    // @ts-ignore
    data,
    timestamp,
  } = await API.getShareInfo({wxdebug: false, url: shareInfo.link,isMiniApp:true,apk:'2J2Dt6DHw8bGf2vZb14E34Uthr6q',});
// wxappid, wxtimestamp, wxnonceStr, wxsignature
  if (!success) {
    return;
  }
  wx.config({
    debug: false,
    appId: data.wxAppId,
    timestamp: data.wxTimestamp,
    nonceStr: data.wxNonceStr,
    signature: data.wxSignature,
    jsApiList: ['onMenuShareTimeline', 'onMenuShareAppMessage']
  });

  wx.error(function (res) {
    console.error("wx error", res);
  });

  wx.ready(function () {
    invokeWX(shareInfo);
  });

}
