import { Base64Util, FileUtil } from '@pura/harmony-utils';
import { plainToInstance } from 'class-transformer';
import { UploadImgEntity } from '../entity/UploadImgEntity';
import { apiService } from '../net/ApiService';
import { ToastUtils } from '../utils/ToastUtils';
import { BaseViewModel } from './BaseViewModel';
import { fileIo } from '@kit.CoreFileKit';

@ObservedV2
export class FeedbackViewModel extends BaseViewModel {
  @Trace feedback?: object

  async sendFeedback(type: string, content: string, contact: string, images: Array<string>) {
    this.showLoading();
    try {
      const result = await apiService.feedback(type, content, contact, images)
      if (result.isSuccess()) {
        this.feedback = new Object()
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async uploadImages(photos: Array<string>): Promise<Array<string>> {
    this.showLoading();
    let uploadList = new Array<string>()
    for (let i = 0;i < photos.length;i++) {
      let imageEntity = await this.uploadImage(photos[i])
      if (imageEntity) {
        uploadList.push(imageEntity.url)
      } else {
        break
      }
    }
    this.dismissLoading();
    if (uploadList.length === photos.length) {
      return Promise.resolve(uploadList)
    } else {
      ToastUtils.show('图片上传失败')
      return Promise.reject()
    }
  }

  async uploadImage(uri: string): Promise<UploadImgEntity | null> {
    try {
      let file = FileUtil.openSync(uri, fileIo.OpenMode.READ_ONLY);
      // 复制文件到缓存目录下
      let cacheFilePath = FileUtil.getCacheDirPath() + '/' + FileUtil.getFileName(uri)
      FileUtil.copyFileSync(file.fd, cacheFilePath)
      // 读取文件为ArrayBuffer
      const file2 = FileUtil.openSync(cacheFilePath, 0o2);
      const stat = FileUtil.lstatSync(cacheFilePath);
      const buffer = new ArrayBuffer(stat.size);
      FileUtil.readSync(file2.fd, buffer);
      FileUtil.fsyncSync(file2.fd);
      FileUtil.closeSync(file2.fd);

      const base64Str = Base64Util.encodeToStrSync(new Uint8Array(buffer))

      const result = await apiService.uploadImage(base64Str, 'feedback');
      if (result.isSuccess()) {
        const imageEntity = plainToInstance(UploadImgEntity, result.data);
        return Promise.resolve(imageEntity)
      } else {
        return Promise.resolve(null)
      }
    } catch (e) {
      console.log(e);
      return Promise.resolve(null)
    }
  }
}