/**
 * 微信授权登录（静默）
 */

import { apiWxLogin, getWxSign } from "@/api/api";
import { Toast } from "vant";
import "vant/es/toast/style";

export const wxLogin = async () => {
  // 判断是否在微信浏览器
  const userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.match(/MicroMessenger/i) != "micromessenger") {
    Toast("请在微信内打开");
    return false;
  }

  //判断是否存在token
  let Authorization = localStorage.getItem("Authorization");
  if (Authorization) return;

  //判断当前路由是否是有code
  const url = location.search; //获取url携带的参数
  let urlParams = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      urlParams[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }

  if (urlParams.code) {
    let res = await apiWxLogin({ Code: urlParams.code });
    if (res.Ret === 200) {
      localStorage.setItem("Authorization", res.Data.Token);

      window.location.href = `${window.location.origin}/`;
    }
  } else {
    const redirectUri = encodeURIComponent(`${window.location.origin}/`);
    const appid = import.meta.env.VITE_APP_WX_APPID;
    window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
  }
};

/**
 * 微信js_sdk
 */
export const wxconfig = async () => {
  const res = await getWxSign({ Url: window.location.href });
  if (res.Ret === 200) {
    wx.config({
      debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
      appId: res.Data.AppId, // 必填，公众号的唯一标识
      timestamp: res.Data.Timestamp, // 必填，生成签名的时间戳
      nonceStr: res.Data.NonceStr, // 必填，生成签名的随机串
      signature: res.Data.Signature, // 必填，签名
      jsApiList: ["hideAllNonBaseMenuItem", "wx-open-launch-weapp"],
      openTagList: ["wx-open-launch-weapp"], // 可选，需要使用的开放标签列表，例如['wx-open-launch-app']
    });
    wx.ready(function () {
      setTimeout(() => {
        wx.hideAllNonBaseMenuItem();
      }, 400);
    });
  }
};
