function getMimetype(signature: string) {
  switch (signature) {
    case "89504E47":
      return "image/png";
    case "47494638":
      return "image/gif";
    case "25504446":
      return "application/pdf";
    case "FFD8FFE0":
    case "FFD8FFE1":
    case "FFD8FFE2":
    case "FFD8FFE3":
      return "image/jpeg";
    case "504B0304":
      return "application/zip";
    case "504B34":
      return "application/zip";
    default:
      return "Unknown filetype";
  }
}

const mimeTypeSuffix: Record<string, string[]> = {
  "image/png": ["png"],
  "image/gif": ["gif"],
  "image/jpeg": ["jpeg", "jpg"],
  "application/zip": ["zip"],
  "application/pdf": ["pdf"],
};

export function fileFormatCheck(file: File, validFileType: string) {
  return new Promise((resolve, reject) => {
    const filereader = new FileReader();
    filereader.onloadend = (evt) => {
      if (evt.target?.readyState === FileReader.DONE) {
        const uint = new Uint8Array(evt.target.result as ArrayBuffer);
        const bytes: string[] = [];
        uint.forEach((byte) => bytes.push(byte.toString(16)));
        const hex = bytes.join("").toUpperCase();
        const mimeType = getMimetype(hex);
        if (!mimeType.toUpperCase().includes(validFileType)) {
          return reject(
            `${file.name}文件内容与所选文件类型${validFileType}不一致`
          );
        }

        const suffix = file.name.split(".").pop() || "";
        const validSuffix: string[] = mimeTypeSuffix[mimeType] || [];
        if (validSuffix.length && suffix && validSuffix.includes(suffix)) {
          resolve(true);
        } else {
          reject(`${file.name}文件内容与文件的后缀不一致，或文件已损坏！`);
        }
      }
    };
    const blob = file.slice(0, 4);
    filereader.readAsArrayBuffer(blob);
  });
}
