import { getWxConfig, getMobileConfig, OfficialLogin } from "@/utils/user";
import { getOpenId } from "@/utils/login";

export function getQueryString(name) {
  const url = location.search; //获取url中"?"符后的字串
  let theRequest = new Object();
  if (url.indexOf("?") != -1) {
    let str = url.substr(1);
    let strs = str.split("&");
    for (let i = 0; i < strs.length; i++) {
      theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
    }
  }
  if (name) {
    return theRequest[name];
  }
  return theRequest;
}
// 授权
export function authorize(url = window.location.href) {
  if (!isWechat()) {
    return;
  }
  if (uni.getStorageSync("openid")) {
    return;
  }
  if (getQueryString("code")) {
    return;
  }
  // 没有code,就重定向到地址https://www.xyyxt.net?ask_type=https://api.xyyxt.net/pages2/order/confirm_pay 去获取code，授权后就会把code带上然后访问域名
  // ?fromCart=&code=061F5a1w3aolh03SLe1w3sMsCF4F5a16&state=STATE
  getMobileConfig().then((res) => {
    if (JSON.parse(res.mobileConfig).gzhSelfLicense) {
      getWxConfig().then((res) => {
        location.replace(
          `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
            res.gzhAppId
          }&redirect_uri=${encodeURIComponent(
            "https://" + url
          )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
        );
      });
    } else {
      url = url.split("//")[1];
      location.replace("https://www.xyyxt.net/home/index2?ask_type=" + url);
      // location.replace("https://www.xyyxt.net/?ask_type=" + url);
    }
  });
}
export function bindCode(code) {
  if (!uni.getStorageSync("user_account")) {
    return;
  }
  OfficialLogin({
    code,
  }).then((res) => {});
}
export function backCode(cb = bindCode) {
  let code = getQueryString("code");
  if (!code) {
    return;
  }
  cb(code);
}

export function backOpenId(cb) {
  let openid = uni.getStorageSync("openid");
  if (openid) {
    cb && cb(openid);
    return;
  }
  let code = getQueryString("code");
  if (!code) {
    return;
  }
  getOpenId({ code }).then((res) => {
    uni.setStorageSync("openid", res.openid);
    uni.setStorageSync("unionid", res.unionid);
    cb && cb(res.openid);
  });
}

export function isWechat() {
  var ua = window.navigator.userAgent.toLowerCase();
  return ua.match(/micromessenger/i) == "micromessenger";
}
