import jsEncrypt from "jsencrypt";
import _ from "lodash";
// rsa非对称加密
export const rsaEncrypt = (pubKey: string, data: string) => {
  const encrypt = new jsEncrypt();
  encrypt.setPublicKey(pubKey);
  return encrypt.encrypt(data);
};
// 格式化接口返回的错误信息
export const formatError = (res: any) => _.get(res, "response.data.msg", "");

//数字单位转换，s：带单位字符串，数字和单位以空格分割；d：计划转换的单位，默认MB；t：测试使用，打印s
export const transNum = (s: string, d?: string, t?: string) => {
  if (t) {
    console.log(s);
  }
  // 未传参返回0
  if (!s) {
    return 0;
  }
  let n = Number(s.split(" ")[0]);
  const list = ["B", "KB", "MB", "GB", "TB"];
  // 数字单位由d转换为MB
  if (d && d !== "MB") {
    let a = list.indexOf(d);
    if (a < 2) {
      while (2 - a) {
        n *= 1024;
        a += 1;
      }
    } else if (a > 2) {
      while (a - 2) {
        n /= 1024;
        a -= 1;
      }
    }
  }
  // 单位由s转换为d
  const b = s.split(" ")[1];
  if (b) {
    if (b.indexOf("KB") !== -1) {
      return Number((n / 1024).toFixed(3));
    } else if (b.indexOf("MB") !== -1) {
      return Number(n.toFixed(3));
    } else if (b.indexOf("GB") !== -1) {
      return Number((n * 1024).toFixed(3));
    } else if (b.indexOf("TB") !== -1) {
      return Number((n * 1024 * 1024).toFixed(3));
    } else return Number((n / 1024 / 1024).toFixed(3));
  }
  return 0;
};
// 获取设备类型
export const isMobile = () => {
  return !!window.navigator.userAgent.match(
    /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i,
  );
};
