// 将 File 对象转为 buffer
function convertFileToBuffer(file: File) {
  return new Promise((resolve, reject) => {
    const fileReader = new FileReader()
    fileReader.onload = () => {
      const uint8Array = new Uint8Array(fileReader.result as ArrayBuffer)
      resolve(uint8Array)
    }
    fileReader.onerror = () => {
      reject(fileReader.error)
    }
    fileReader.readAsArrayBuffer(file)
  })
}

// 将 base64 转为字节码
function convertBase64ToBytes(imageBase64: string): Uint8Array {
  const dataUrl = imageBase64.split(';base64,')[1]
  const imageData = atob(dataUrl)
  const bytes = new Uint8Array(imageData.length)
  for (let i = 0; i < imageData.length; i++) {
    bytes[i] = imageData.charCodeAt(i)
  }
  return bytes
}

// @ts-ignore
// 根据 base64 获取图片的格式
function getImageFormateFromBase64(imageBase64: string): string {
  const dataArray = imageBase64.split(';base64,')
  if (dataArray.length !== 2) {
    throw new Error('Invalid base64 image')
  }
  const mimeType = dataArray[0].split(':')[1]
  return mimeType.split('/')[1]
}

function convertbase64ToJpgBuffer(imageBase64: string, width: number, height: number): Promise<Uint8Array> {
  return new Promise((resolve, reject) => {
    const image = new Image()
    image.src = imageBase64
    image.onload = () => {
      const width = image.width
      const height = image.height

      const canvas = document.createElement('canvas')
      canvas.width = width
      canvas.height = height
      const ctx = canvas.getContext('2d')
      if (!ctx) {
        reject(new Error('Invalid canvas context'))
        return
      }
      ctx.drawImage(image, 0, 0, width, height)
      const jpgBuffer = canvas.toDataURL()

      const bytes = convertBase64ToBytes(jpgBuffer)
      resolve(bytes)
    }
  })
}

export {
  convertFileToBuffer,
  convertbase64ToJpgBuffer,
  convertBase64ToBytes
}
