export const getSuffixName = (str: string) => {
  const matched = str.match(/(.*)\.(.*)$/);
  return matched ? matched[2] : "";
};

export const getFileName = (str: string) => {
  const matched = str.match(/(.*)\.(.*)$/);
  return matched ? matched[1] : "";
};

/**
 *
 * @param file 文件
 * @param fileType accept字段
 */
export const fileTypeChecked = (file: File, fileType: string) => {
  // .jpg,audio/aac
  const types = fileType.split(",");
  return types.some(
    (type) => file.type === type || "." + getSuffixName(file.name) === type
  );
};

export const getFileSize = (size: number) => {
  const k = (size / 1024).toFixed(2);
  if (Number(k) < 900) {
    return k + "K";
  } else {
    const m = (Number(k) / 1024).toFixed(2);
    return m + "M";
  }
};

// blob类型转base64
export function blobToBase64(blob: Blob) {
  return new Promise<string>((resolve, reject) => {
    const fileReader = new FileReader();
    fileReader.onload = (e: any) => {
      let str = e.target.result;
      str = str.split(",");
      resolve(str[1]);
    };
    // readAsDataURL
    fileReader.readAsDataURL(blob);
    fileReader.onerror = () => {
      reject(new Error("blobToBase64 error"));
    };
  });
}
