export function takePhoto(): Promise<File> {
  return new Promise((resolve, reject) => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.capture = 'environment'
    input.onchange = (e) => {
      const files = (e.target as HTMLInputElement).files
      if (files?.length) compressImage(files[0]).then(resolve).catch(reject)
      else reject(new Error('未选择图片'))
    }
    input.click()
  })
}

export function pickFromAlbum(multiple = false): Promise<File[]> {
  return new Promise((resolve, reject) => {
    const input = document.createElement('input')
    input.type = 'file'
    input.accept = 'image/*'
    input.multiple = multiple
    input.onchange = (e) => {
      const files = (e.target as HTMLInputElement).files
      if (files?.length) {
        Promise.all(Array.from(files).map(compressImage)).then(resolve).catch(reject)
      } else reject(new Error('未选择图片'))
    }
    input.click()
  })
}

export function compressImage(file: File): Promise<File> {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onload = (e) => {
      const img = new Image()
      img.onload = () => {
        const max = 1080
        let w = img.width, h = img.height
        if (w > max || h > max) {
          if (w > h) { h = (h / w) * max; w = max }
          else { w = (w / h) * max; h = max }
        }
        const c = document.createElement('canvas')
        c.width = w; c.height = h
        c.getContext('2d')!.drawImage(img, 0, 0, w, h)
        c.toBlob((b) => resolve(new File([b!], file.name, { type: 'image/jpeg' })), 'image/jpeg', 0.8)
      }
      img.src = e.target!.result as string
    }
    reader.readAsDataURL(file)
  })
}
