/*
 * @Author: ZhengXiaowei
 * @Date: 2019-09-02 11:26:34
 * @LastEditors: ZhengXiaowei
 * @LastEditTime: 2019-09-02 17:54:09
 * @Description: 微信分享
 */

import { getWxConfig } from "../api";

const u = navigator.userAgent;

const isAndroid = u.indexOf("iPhone") === -1;

const shareTemplate = [
  "onMenuShareTimeline",
  "onMenuShareAppMessage",
  "onMenuShareQQ",
  "onMenuShareWeibo"
];

function initWxConfig(wx, config) {
  // * 配置微信config
  return new Promise((resolve, reject) => {
    wx.config({
      debug: !!window.options.xiyue_info.debug, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: config.appId, // 必填，公众号的唯一标识
      timestamp: config.timestamp, // 必填，生成签名的时间戳
      nonceStr: config.nonceStr, // 必填，生成签名的随机串
      signature: config.signature,
      jsApiList: [
        "onMenuShareTimeline",
        "onMenuShareAppMessage",
        "onMenuShareQQ",
        "onMenuShareWeibo"
      ]
    });
    wx.ready(() => resolve());
    wx.error(res => reject(res));
  });
}

export default function useWxConfig(wx, { book, link }) {
  let href = window.signUrl;
  // * 如果当前环境为android的话 则使用当前路由做为注册href
  if (isAndroid) href = location.href;
  console.log("config url:", href);
  console.log("config encode url:", encodeURIComponent(href));
  getWxConfig(encodeURIComponent(href)).then(r =>
    initShareConfig(wx, { config: r, book, link })
  );
}

function initShareConfig(wx, { config, book, link }) {
  console.log(config);
  console.log(book);
  console.log(link);
  initWxConfig(wx, config)
    .then(_ => {
      console.log("wx config suc");
      let {
        book_summary: bookSummary,
        book_name: bookName,
        cover_url: coverImage
      } = book;
      console.log("wx share list", shareTemplate);
      let shareConfig = {
        title: bookName,
        desc: bookSummary,
        link: link, // 分享链接
        imgUrl: coverImage
      };
      // wx.updateAppMessageShareData(shareConfig);
      // wx.updateTimelineShareData(shareConfig);
      wx.onMenuShareTimeline(shareConfig);
      wx.onMenuShareAppMessage(shareConfig);
      wx.onMenuShareQQ(shareConfig);
      wx.onMenuShareWeibo(shareConfig);
    })
    .catch(res => {
      console.log("wx config err", res);
    });
}
