/*
 * @Description: weixin-js-sdk
 * @LastEditors: gzw
 * @Date: 20120-08-30 18:40:11
 * @LastEditTime: 2020-09-01 21:00:22
 */
import cfg from "@/config/index";
import { getwxAuth } from "@/api/user";
import wx from "weixin-js-sdk";
import { isWeixinBrower } from "@/service/validation";
import { parseSearch } from "@/service/utils";
import localStorage from "@/service/localStorage";

/**
 * @description: 微信分享
 */
export async function setShare({
  title = "",
  desc = "",
  url = window.location.origin,
  imgUrl = ""
}) {
  const currentUrl = location.href.split("#")[0];
  const res = await getwxAuth({
    appId: cfg.wxAppId,
    url: currentUrl
  });
  const { appId, timestamp, nonceStr, signature } = res;
  wx.config({
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
    appId, // 必填，公众号的唯一标识，填自己的！
    timestamp, // 必填，生成签名的时间戳，刚才接口拿到的数据
    nonceStr, // 必填，生成签名的随机串
    signature, // 必填，签名，见附录1
    jsApiList: ["updateAppMessageShareData", "updateTimelineShareData"]
  });
  wx.ready(function() {
    //分享到朋友圈
    wx.updateTimelineShareData({
      title, // 分享时的标题
      link: url, // 分享时的链接
      imgUrl, // 分享时的图标
      success: function() {
        console.log("分享成功");
      },
      cancel: function() {
        console.log("取消分享");
      }
    });
    //分享给朋友
    wx.updateAppMessageShareData({
      title,
      desc,
      link: url, // 分享时的链接
      imgUrl,
      type: "link",
      dataUrl: "",
      success: function() {
        console.log("分享成功");
      },
      cancel: function() {
        console.log("取消分享");
      }
    });
  });
}

/**
 * @description: 检查微信环境，分享进入，是否存在openid，否则重定向加载
 */
export function checkOpenId() {
  const openId = localStorage.get("openId");
  const _param = parseSearch(window.location.href);
  const local = window.location.href;
  console.log(!openId, isWeixinBrower, !_param.code, window.location.href);
  if (!openId && isWeixinBrower && !_param.code) {
    var nextPage = document.createElement("a");
    nextPage.setAttribute(
      "href",
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        cfg.wxAppId +
        "&redirect_uri=" +
        encodeURIComponent(local) +
        "&response_type=code&scope=snsapi_base&state=1#wechat_redirect"
    );
    nextPage.click();
  }
}
