import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { util } from '@kit.ArkTS'
import { fileIo } from '@kit.CoreFileKit'
import { YTLog } from '../../../../Index'


export class Upload {
  // static uploadImage(context: Context) {
  //   const option = new photoAccessHelper.PhotoSelectOptions()
  //   option.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE
  //   option.maxSelectNumber = 5 // 设置最多选择5张
  //   option.isOriginalSupported = true
  //
  //   const picker = new photoAccessHelper.PhotoViewPicker()
  //   picker.select(option)
  //     .then(async res => { // 改为async/await语法
  //       try {
  //         const formData = new FormData()
  //
  //         // 并行处理多图
  //         await Promise.all(res.photoUris.map(async (uri, index) => {
  //           const photoName = util.generateRandomUUID()
  //           const photoType = '.' + uri.split('.').pop()
  //           const fullPath = context.cacheDir + '/' + photoName + photoType
  //
  //           const photo = fileIo.openSync(uri)
  //           try {
  //             await fileIo.copyFile(photo.fd, fullPath)
  //             formData.append('file' + index, 'internal://cache/' + photoName + photoType)
  //           } finally {
  //             fileIo.closeSync(photo.fd) // 确保关闭文件描述符
  //           }
  //         }))
  //
  //
  //         // 统一提交所有文件
  //         // 这里添加实际的上传代码，例如：
  //         // const response = await axios.post('your_api_url', formData)
  //         // YTLog.info('Upload success:' + JSON.stringify(response.data))
  //
  //       } catch (err) {
  //         YTLog.error('Upload failed:' + JSON.stringify(err))
  //       }
  //     })
  // }

  static selectImage(context: Context, isReady: (fullPath: string) => void) {
    const option = new photoAccessHelper.PhotoSelectOptions()
    option.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE
    option.maxSelectNumber = 1
    const picker = new photoAccessHelper.PhotoViewPicker()
    picker.select(option)
      .then(res => {
        const photoName = util.generateRandomUUID()
        const photoType = '.' + res.photoUris[0].split('.').pop()
        const fullPath = context.cacheDir + '/' + photoName + photoType
        const photo = fileIo.openSync(res.photoUris[0])
        try {
          fileIo.copyFile(photo.fd, fullPath)
            .then(() => {
              YTLog.info(fullPath)
              isReady(fullPath)
            })
        } catch (err) {
          YTLog.error(err)
        }
      })
  }
}

