/**
 * 防抖函数
 * @param func 目标函数
 * @param wait 延迟执行毫秒数
 * @param immediate 立即执行， false - 延迟执行
 */
export const onDebounce = <T>(fn: T, delay: number): (() => void) => {
  let timer;
  return function (...args) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(
      () => {
        typeof fn === "function" && fn.apply(null, [...args]);
        clearTimeout(timer);
      },
      delay > 0 ? delay : 100
    );
  };
};

/**
 * 根据url后拽判断文件类型
 */
export const judgeFileType = (fileUrl: string) => {
  // base64
  const reg =
    /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@//?%\s]*?)\s*$/i;
  if (reg.test(fileUrl)) {
    return "base64";
  }
  // 后缀获取
  let suffix = "";
  try {
    const flieArr = fileUrl.split(".");
    suffix = flieArr[flieArr.length - 1];
  } catch (err) {
    suffix = "";
  }
  // fileName无后缀返回 false
  if (!suffix) return "";
  suffix = suffix.toLocaleLowerCase();
  const txtlist = ["txt"];
  const pdflist = ["pdf"];
  const pptlist = ["ppt", "pptx"];
  const excelist = ["xls", "xlsx"];
  const wordlist = ["doc", "docx"];
  const videolist = ["mp4", "avi", "mov"];
  const radiolist = ["mp3", "wav", "wmv"];
  const imglist = ["png", "jpg", "jpeg", "bmp", "gif"];
  if (txtlist.includes(suffix)) {
    return "txt";
  } else if (pdflist.includes(suffix)) {
    return "pdf";
  } else if (pptlist.includes(suffix)) {
    return "ppt";
  } else if (excelist.includes(suffix)) {
    return "excel";
  } else if (wordlist.includes(suffix)) {
    return "word";
  } else if (videolist.includes(suffix)) {
    return "video";
  } else if (radiolist.includes(suffix)) {
    return "radio";
  } else if (imglist.includes(suffix)) {
    return "image";
  } else {
    return "";
  }
};

/**
 * 获取URL参数
 * @param variable 参数名称
 */
export const getQueryVariable = (variable: string) => {
  const query = window.location.search.substring(1);
  const vars = query.split("&");
  for (let i = 0; i < vars.length; i++) {
    const pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  }
  return "";
};

/**
 * 判断是否为空
 * @param value
 */
export const isEmpty = (value: any) => {
  if (value === null || value === "" || value === undefined || value === "null" || value === "0") {
    return true;
  } else if (typeof value === "string") {
    value = value.replace(/\s/g, "");
    if (value === "") {
      return true;
    }
    return false;
  }
  return false;
};

/**
 * 字节转成 B KB MB GB
 * @param func 目标函数
 */
export const sizeTostr = (bytes: any) => {
  if (isEmpty(bytes)) return "0 B";
  const k = 1024,
    sizes = ["B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toPrecision(3) + " " + sizes[i];
};

/**
 * a标签实现电话呼叫
 * @param tel 电话号码
 */
export const callTelephone = (tel) => {
  const a = document.createElement("a"); // 创建a标签
  a.setAttribute("href", `tel:${tel}`); // href链接
  a.click(); // 自执行点击事件
};

/**
 * 图片加载监测
 */
export const loadImage = (url) => {
  return new Promise((resolve, reject) => {
    const newImg = new Image();
    newImg.src = url;
    newImg.onerror = () => {
      reject("failure");
    };
    newImg.onload = (e) => {
      resolve(e.target);
    };
  });
};

/**
 * 判断是否是腾讯云的图片
 */
export const isTencentCosPic = (url) => {
  return url.includes("wlmvp-cos.weiling.cn");
};

/**
 * 判断是否是base64
 */
export const isBase64 = (str) => {
  return str.indexOf("data:") != -1 && str.indexOf("base64") != -1;
};

/**
 * 判断是否是闰年
 * @param year 年份
 */
export const isLeapYear = (year): boolean => {
  if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
    return true;
  }
  return false;
};

/**
 * 是否在iframe中
 * @returns boolean 是否在iframe中
 */
export const isIframe = () => {
  return window.parent !== window;
};

/**
 * 获取vant4中picker日期默认选择数据
 * @param time 时间
 * @returns string[]
 */
export const getVantDateValue = (time: number | string | Date): string[] => {
  time = time instanceof Date ? time : new Date(parseInt(time as string));
  return [
    time.getFullYear(),
    `${time.getMonth() + 1 > 9 ? "" : "0"}${time.getMonth() + 1}`,
    `${time.getDate() + 1 > 9 ? "" : "0"}${time.getDate() + 1}`,
  ];
};

/**
 * base64转成file对象
 * @param data base64字符串
 * @param filename 文件名
 */
import { Base64 } from "js-base64";
export const base64ToFile = (base64Url: any, filename: any) => {
  function dataURLtoBlob(toDataURL: any) {
    const arr = toDataURL.split(","),
      mime = arr[0].match(/:(.*?);/)[1],
      bstr = Base64.atob(arr[1]);
    let n = bstr.length;
    const u8arr = new Uint8Array(n);
    while (n--) {
      u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
  } //转成file
  function blobToFile(Blob: any) {
    Blob.lastModifiedDate = new Date();
    Blob.name = filename;
    return Blob;
  }

  // 调用如下
  const bold = dataURLtoBlob(base64Url);
  return blobToFile(bold);
};

/**
 * 查看ids是否有subIds中的元素
 */
export const includesArr = (ids: string[], subIds: string[]): boolean => {
  return subIds.filter((res) => ids.includes(res)).length > 0;
};

/**
 * 判断是pc还是h5
 * @returns Mobile | PC
 */
export const judgePcOrH5 = () => {
  const userAgent = navigator.userAgent;
  if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)) {
    return "Mobile";
  } else {
    return "PC";
  }
};

/**
 * 去掉对象中的空值
 * @param obj 要去掉空值的对象
 */
export const removeEmptyField = (obj) => {
  let newObj = {};
  if (typeof obj === "string") {
    obj = JSON.parse(obj);
  }
  if (obj instanceof Array) {
    newObj = [];
  }
  if (obj instanceof Object) {
    for (let attr in obj) {
      // 属性值不为'',null,undefined才加入新对象里面(去掉'',null,undefined)
      if (obj[attr] !== "" && obj[attr] !== null && obj[attr] !== undefined) {
        if (obj[attr] instanceof Object) {
          // 空数组或空对象不加入新对象(去掉[],{})
          if (JSON.stringify(obj[attr]) === "{}" || JSON.stringify(obj[attr]) === "[]") {
            continue;
          }
          // 属性值为对象,则递归执行去除方法
          newObj[attr] = removeEmptyField(obj[attr]);
        } else if (
          typeof obj[attr] === "string" &&
          ((obj[attr].indexOf("{") > -1 && obj[attr].indexOf("}") > -1) ||
            (obj[attr].indexOf("[") > -1 && obj[attr].indexOf("]") > -1))
        ) {
          // 属性值为JSON时
          try {
            let attrObj = JSON.parse(obj[attr]);
            if (attrObj instanceof Object) {
              newObj[attr] = removeEmptyField(attrObj);
            }
          } catch (e) {
            newObj[attr] = obj[attr];
          }
        } else {
          newObj[attr] = obj[attr];
        }
      }
    }
  }
  return newObj;
};

/**
 * 全局环境的配置
 */
export const setStoreData = (Store: TEnv.TEnvData, envData: TEnv.TEnvData) => {
  console.log("envData",envData)
  Store.sid = envData.sid;
  Store.token = envData.token;
  Store.user_id = envData.user_id;
  Store.corp_id = envData.corp_id;
  Store.node_env = envData.node_env;
  Store.card_resource = envData.card_resource;
};
