import store from "@/store/index.js";
import api from "@/common/api.js";
import { isWeixin, modalComfirm } from "./shared";
import { getQueryString } from "../common/navTo";
export function getCode(url) {
  return new Promise((resolve, reject) => {
    // #ifdef H5
    if (location.search.includes("code")) {
      const code = getQueryString("code");
      uni.setStorageSync("h5_code", code);
      resolve(code);
    } else {
      // 没有code,就重定向到地址https://www.xyyxt.net?ask_type=https://api.xyyxt.net/pages2/order/confirm_pay 去获取code，授权后就会把code带上然后访问域名
      // ?fromCart=&code=061F5a1w3aolh03SLe1w3sMsCF4F5a16&state=STATE
      url = url || window.location.href;
      // if (process.env.NODE_ENV !== "development") {
        // 跳自己授权
        if (store.getters.config.gzhSelfLicense) {
          api.getWxConfig().then((res) => {
            location.replace(
              `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
                res.data.data.gzhAppId
              }&redirect_uri=${encodeURIComponent(
                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);
        }
      // }
    }
    // #endif
    // #ifdef MP-WEIXIN
    uni.login({
      provider: "weixin",
      success: (loginRes) => {
        resolve(loginRes.code);
      },
    });
    // #endif
  });
}

// 获得openid
export async function getOpenid() {
  let openid = uni.getStorageSync("openid");
  if (!openid) {
    let code = await getCode();
    openid = await codeGetOpenid(code);
    uni.setStorageSync("openid", openid);
  }
  return openid;
}

// code去换openid
export async function codeGetOpenid(code) {
  // #ifdef H5
  let { data } = await api.getH5Openid({ code });
  return data.msg;
  // #endif
  // #ifdef MP-WEIXIN
  let { data } = await api.getWxOpenid({ code });
  uni.setStorageSync("unionId", data.data.unionId);
  return data.data.openId;
  // #endif
}

export async function checkOpenidIsUser() {
  let openid = uni.getStorageSync("openid");
  if (!openid) {
    openid = await getOpenid();
  }
  let fromPlat = 1;
  // #ifdef MP-WEIXIN
  fromPlat = 2;
  // #endif
  let { data } = await api.checkBindOpenId({ openid, fromPlat });
  console.log("🚀 ~ file: authority.js:72 ~ checkOpenidIsUser ~ data:", data);
  return data;
}
export function examClientCanLearn(examLimitClient) {
  // 限制学习
  if (!examLimitClient) {
    return true;
  }
  // #ifdef MP-WEIXIN
  if (examLimitClient.includes("2")) {
    return true;
  }
  // #endif
  // #ifdef H5
  if (examLimitClient.includes("1") && isWeixin()) {
    return true;
  }
  // #endif
  modalComfirm(
    "请去" + (examLimitClient == 2 ? "微信小程序" : "公众号") + "学习"
  );
  throw new Error("examLimitClient:" + examLimitClient);
}

export async function isCanDoExam(examLimitClient) {
  if (!examLimitClient || !examClientCanLearn(examLimitClient)) {
    return false;
  }
  let { data } = await checkOpenidIsUser();
  if (!data) {
    modalComfirm({
      content: "该题库只允许同一用户学习",
      scb: () => {
        uni.switchTab({
          url: "/pages/questionBank/index",
        });
      },
    });
    throw new Error("data:" + data);
  }
  return false;
}

export async function goodsExamIsCanLearn(goodsId) {
  if (!goodsId) {
    return true;
  }
  let { data } = await api.goodsDetail(goodsId);
  let { examLimitClient } = data.data;
  if (await isCanDoExam(examLimitClient)) {
    throw new Error("openid不一致");
  }
  return true;
}
