export const requestSignature = async () => {
  //  //# ????
  let href = window.location.href.split("#")[0];
  console.log(window.location.href);
  console.log("href===", href)
  let failData = {
    result: false,
    data: {
      agentId: "",
      corpId: "",
      noncestr: "",
      signature: "",
      timestamp: "",
    },
  };
  href = encodeURIComponent(href);
  const url =
    `${window.location.origin}` +
    `/mobile-appstore/qywx/getAppSignature?url=${href}&appCode=` + import.meta.env.VITE_QW_APP_CODE;

  return fetch(url, {method: "GET"})
    .then((response) => response.json())
    .then((response) => {
      console.log("response===", response);
      const conditionSecond = "errcode" in response && response.errcode === 1;
      if (conditionSecond) {
        return {result: true, data: response};
      } else {
        return failData;
      }
    })
    .catch(() => {
      return failData;
    });
};


export const wxReady = async (signData) => {
  console.log("wxReady signData===", signData);
  return new Promise((resolve, reject) => {
    window.wx.config({
      beta: true,
      debug: false,
      appId: import.meta.env.VITE_QW_APP_ID,
      nonceStr: signData.noncestr,
      signature: signData.signature,

      timestamp: signData.timestamp,
      jsApiList: ["hideOptionMenu", "checkJsApi"],
    });
    window.wx.ready(function () {
      //隐藏右上角菜单接口
      window.wx.hideOptionMenu();
      window.wx.invoke("ext_baowu_user", {}, (res) => {
        console.log("wxReady res===", res);
        const msg = res.err_msg || res.errMsg || "";
        if (msg == "ext_baowu_user:ok") {
          return  resolve(res);
        } else if (msg === "ext_baowu_user:fail unspport api") {
          console.log("ext_baowu_user:fail unspport api");
          return reject(new Error('ext_baowu_user:fail unspport api'));
        } else {
          console.log("ext_baowu_user:fail");
          return reject(new Error('ext_baowu_user:fail'));
        }
      });
    });
    window.wx.error(function (res) {
      // callback({ status: false });
      console.log("wx.error:" + JSON.stringify(res));
      reject(res);
    });
  })




};

