/**
 * 普通跳转客服
 * 注意:小程序需要额外增加业务域名 https://duiba.qiyukf.com/
 */
export function jumpService() {
  location.href = location.origin + "/faq/index";
}

// app跳转
export function appJump(url) {
  console.info("app跳转:", url);

  if (url.indexOf("http") > -1) {
    window.location.href = url;
    return;
  }

  const setting = {
    page: url,
  };
  window.c_plugins.merchantBridge.goToNative(
    function (res) {
      console.info(res);
    },
    function (err) {
      console.info(err);
    },
    setting
  );
}

function caesarCipher(str, shift) {
  let result = "";
  for (let i = 0; i < str.length; i++) {
    const char = str.charCodeAt(i);
    if (char >= 65 && char <= 90) {
      result += String.fromCharCode(((char - 65 + shift) % 26) + 65);
    } else if (char >= 97 && char <= 122) {
      result += String.fromCharCode(((char - 97 + shift) % 26) + 97);
    } else {
      result += str[i];
    }
  }
  return result;
}
export function caesarDecipher(str, shift) {
  return caesarCipher(str, 26 - shift);
}

export const urlToBase64 = async (url) => {
  try {
    const response = await fetch(url);
    const blob = await response.blob();
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onloadend = () => resolve(reader.result);
      reader.onerror = reject;
      reader.readAsDataURL(blob);
    });
  } catch (error) {
    console.error("Error converting image to base64:", error);
    throw error;
  }
};

// app分享
export async function appShare(shareInfo) {
  console.info("app分享", shareInfo);
  // const base64String = await urlToBase64(shareInfo.thumbnail);
  const base64String = (await urlToBase64(shareInfo.thumbnail))?.split("base64,")[1];
  console.info("base64String", base64String); // 输出base64编码后的字符串
  window.c_plugins.merchantBridge.weixinShare(
    function () {
      console.info("这是成功回调");
    },
    function () {
      console.info("这是失败回调");
    },
    {
      title: shareInfo.title, // 分享标题
      description: shareInfo.content, // 分享内容
      url: shareInfo.url, // 分享链接
      img: base64String, // 分享缩略图必须是base64图片
    }
  );
}

// app 组合分享 （没有落地页）
export async function appMultiShareTools(shareInfo) {
  console.info("app组合分享", shareInfo);
  const base64String = (await urlToBase64(shareInfo.thumbnail))?.split("base64,")[1];
  // console.info('base64String', base64String); // 输出base64编码后的字符串
  window.c_plugins &&
    window.c_plugins.merchantBridge.multiShareTools(
      function (data) {
        console.info("这是成功回调", data);
      },
      function (err) {
        console.info("这是失败回调", err);
      },
      {
        // 公共参数
        commonInfo: {
          internalCode: "2d146069343c4120b43b00691ac68f95", // 对应投放的商户code
          internalParams: JSON.stringify({
            interpretedID: "merchant", // 固定
            showPage: shareInfo.showPage || "", // 唤端需要带回来的参数
          }),
        },
        // 分享参数
        shareParams: [
          {
            shareTypeLink: {
              externalUrl: shareInfo.url, // 传进去也没用 不会有落地页
              title: shareInfo.title,
              description: shareInfo?.content,
              encryEnable: "N",
              img: base64String, // 分享缩略图必须是base64图片
            },
          },
          // 海报分享
          // {
          //   shareTypePoster: {
          //     Imgurl: posterImg, // base64图片或者图片链接
          //     // Imgurl: shareInfo?.posterImg.replace(/^data:.+;base64,/, ''), // base64图片或者图片链接
          //   },
          // },
        ],
      }
    );
}

// app打开微信小程序
export async function appOpenMiniProgram(userName, url) {
  console.info("app打开微信小程序", url);
  window.c_plugins.merchantBridge.weixinOpenMiniProgram(
    function () {
      // 这是成功回调
      console.info("这是成功回调");
    },
    function () {
      // 这是失败回调
      console.info("这是失败回调");
    },
    {
      userName, // 小程序名称id
      path: url,
    }
  );
}

// 获取机构号
export async function getBranchId() {
  const merId = {
    merId: CFG.MER_ID,
  };
  return new Promise((resolve, reject) => {
    if (location.href.indexOf("localhost") !== -1) resolve({ cipherText: "11" });
    window.c_plugins.merchantBridge.getBocCustomerAllInfo(
      function (data) {
        console.info("getBocCustomerAllInfo suc: ", data);
        resolve(data);
      },
      function (err) {
        console.info("getBocCustomerAllInfo fail: ", err);
        reject(err);
      },
      merId
    );
  });
}
