// 按原比例缩放图片
export const resizeImgSizeByOriginRatio = (
  width: number,
  height: number,
  newWidth: number,
  newHeight: number
): [number, number] => {
  let arr: [number, number] = [0, 0]
  const nRatio = width / height
  const mRatio = newWidth / newHeight
  if (nRatio > mRatio) {
    // 固定宽度
    arr = [newWidth, newWidth / nRatio]
  } else {
    // 固定高度
    arr = [nRatio * newHeight, newHeight]
  }
  return arr
}

// 缩放图片尺寸
export const resizeImgSize = (
  width: number,
  height: number,
  maxWidth?: number,
  maxHeight?: number
): [number, number] => {
  const nRatio = width / height
  let arr: [number, number] = [0, 0]
  if (maxWidth && maxHeight) {
    if (width <= maxWidth && height <= maxHeight) {
      arr = [width, height]
    } else {
      const mRatio = maxWidth / maxHeight
      if (nRatio > mRatio) {
        // 固定宽度
        arr = [maxWidth, maxWidth / nRatio]
      } else {
        // 固定高度
        arr = [nRatio * maxHeight, maxHeight]
      }
    }
  } else if (maxWidth) {
    if (width <= maxWidth) {
      arr = [width, height]
    } else {
      arr = [maxWidth, maxWidth / nRatio]
    }
  } else if (maxHeight) {
    if (height <= maxHeight) {
      arr = [width, height]
    } else {
      arr = [nRatio * maxHeight, maxHeight]
    }
  }
  return arr
}

interface ImageSize {
  width: number
  height: number
}

interface LoadImageResult {
  url: string
  size: ImageSize
}

// 缩放图片
export const resizeImg = (
  imgUrl: string,
  maxWidth?: number,
  maxHeight?: number
): Promise<[number, number]> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.src = imgUrl
    img.onload = () => {
      const arr = resizeImgSize(
        img.naturalWidth,
        img.naturalHeight,
        maxWidth,
        maxHeight
      )
      resolve(arr)
    }
    img.onerror = (e: Event | string) => {
      reject(e)
    }
  })
}

// 获取图片大小
export const getImageSize = (src: string): Promise<ImageSize> => {
  return new Promise(resolve => {
    const img = new Image()
    img.src = src
    img.onload = () => {
      resolve({
        width: img.width,
        height: img.height
      })
    }
    img.onerror = () => {
      resolve({
        width: 0,
        height: 0
      })
    }
  })
}

// 加载图片文件
export const loadImage = (imgFile: File): Promise<LoadImageResult> => {
  return new Promise((resolve, reject) => {
    const fr = new FileReader()
    fr.readAsDataURL(imgFile)
    fr.onload = async (e: ProgressEvent<FileReader>) => {
      const url = e.target?.result as string
      const size = await getImageSize(url)
      resolve({
        url,
        size
      })
    }
    fr.onerror = (error: ProgressEvent<FileReader>) => {
      reject(error)
    }
  })
}

// 图片转成dataURL
export const imgToDataUrl = (
  src: string,
  returnBlob: boolean = false
): Promise<string | Blob> => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    // 跨域图片需要添加这个属性，否则画布被污染了无法导出图片
    img.setAttribute('crossOrigin', 'anonymous')
    img.onload = () => {
      try {
        const canvas = document.createElement('canvas')
        canvas.width = img.width
        canvas.height = img.height
        const ctx = canvas.getContext('2d')
        if (!ctx) {
          throw new Error('Failed to get canvas context')
        }
        // 图片绘制到canvas里
        ctx.drawImage(img, 0, 0, img.width, img.height)
        if (returnBlob) {
          canvas.toBlob(blob => {
            if (blob) {
              resolve(blob)
            } else {
              reject(new Error('Failed to create blob'))
            }
          })
        } else {
          resolve(canvas.toDataURL())
        }
      } catch (e) {
        reject(e)
      }
    }
    img.onerror = (e: Event | string) => {
      reject(e)
    }
    img.src = src
  })
}