import axios, { AxiosProgressEvent } from '@ohos/axios';
import fileIo from '@ohos.file.fs';
import { util } from '@kit.ArkTS';
import { fileUri } from '@kit.CoreFileKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { image } from '@kit.ImageKit';
import { BusinessError, emitter } from '@kit.BasicServicesKit';
import { YTLog } from '../../../../Index';

export class DownLoadFileHelper {
  private cashPaths: string[] = []
  private currentIndex: number = 0

  //传入需要下载得url数组并下载文件，通过回调函数返回对应cashPaths数组
  async loadFiles(urls: string[], finishDownLoad: (cashPaths: string[]) => void) {
    let filePath = getContext(this).cacheDir + '/' + util.generateRandomUUID() + '.jpg'
    // Download the file. If the file already exists, delete the existing one first.
    try {
      fileIo.accessSync(filePath);
      fileIo.unlinkSync(filePath);
    } catch (err) {
    }

    await axios({
      url: urls[this.currentIndex],
      method: 'get',
      context: getContext(this),
      filePath: filePath,
      onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
        // console.info("progress: " + progressEvent && progressEvent.loaded && progressEvent.total ?
        // Math.ceil(progressEvent.loaded / progressEvent.total * 100) : 0)
      }
    })
    this.currentIndex++
    this.cashPaths.unshift(filePath)
    if (this.currentIndex < urls.length) {
      this.loadFiles(urls, finishDownLoad)
    } else {
      finishDownLoad(this.cashPaths)
    }
  }

  //传入需要保存得cashPaths数组，并通过ShowAssetsCreationDialog保存文件
  async saveByShowAssetsCreationDialog(cashPaths: string[], context: Context, success?: () => void) {
    const phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    const uris = cashPaths.map(item => fileUri.getUriFromPath(item))
    try {
      // 指定待保存照片的创建选项，包括文件后缀和照片类型，标题和照片子类型可选。
      const photoCreationConfigs = uris.map(() => {
        const photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
          fileNameExtension: 'jpg',
          photoType: photoAccessHelper.PhotoType.IMAGE,
        }
        return photoCreationConfig
      })
      // 基于弹窗授权的方式获取媒体库的目标uri。
      let desFileUris: Array<string> =
        await phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfigs);

      let index = 0
      while (index < uris.length) {
        //通过该uri打开图片
        let file = await fileIo.open(desFileUris[index], fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
        //获取流
        const buffer = await this.getFileBuffer(cashPaths[index])
        //通过流写入相册
        let writeLen = await fileIo.write(file.fd, buffer)
        //关流
        await fileIo.close(file)
        index++
      }
      success?.()
    } catch (err) {
      emitter.emit('hide')
    }
  }

  //传入图片地址,转化为流
  async getFileBuffer(filePath: string): Promise<ArrayBuffer> {
    try {
      const imageSource = image.createImageSource(filePath)
      let imagePackerApi = image.createImagePacker();
      let buffer = await imagePackerApi.packing(imageSource, {
        quality: 100,
        format: 'image/jpeg'
      })
      return buffer
    } catch (err) {
      let error: BusinessError = err as BusinessError;
      console.error(`read file failed, errCode:${error.code}, errMessage:${error.message}`);
      return Promise.reject(err)
    }
  }

  //须先申请权限ohos.permission.WRITE_IMAGEVIDEO
  async saveImgToAssets(cashPaths: string[]) {
    try {
      let index = 0;
      while (index < cashPaths.length) {
        //获取当前上下文
        //通过accessHelper模块获取accessHelper对象
        let accessHelper = photoAccessHelper.getPhotoAccessHelper(getContext())
        //指定待创建的文件类型、后缀和创建选项，创建图片或视频资源 返回创建的图片和视频的uri
        let uri = await accessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
        //通过该uri打开图片
        let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
        //获取流
        const buffer = await this.getFileBuffer(cashPaths[index])
        //通过流写入相册
        let writeLen = await fileIo.write(file.fd, buffer)
        //关流
        await fileIo.close(file)
        index++
      }

    } catch (e) {
      YTLog.error(e)
    }
  }


  getType(imgUrl: string) {
    return imgUrl.split('.').pop()
  }
}