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

@ObservedV2
export class UserSettingsViewModel extends BaseViewModel {
  @Trace userEntity?: UserEntity
  @Trace imageEntity?: UploadImgEntity
  @Trace update?: object

  async userinfo() {
    this.showLoading()
    try {
      const result = await apiService.userinfo();
      if (result.isSuccess()) {
        this.userEntity = plainToInstance(UserEntity, result.data);
        LoginManager.setUserInfo(this.userEntity);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading()
    } catch (e) {
      this.dismissLoading()
      console.log(e);
      ToastUtils.show(e);
    }
  }

  async updateUserinfo(params: Record<string, string>) {
    this.showLoading()
    try {
      const result = await apiService.updateUserinfo(params);
      if (result.isSuccess()) {
        this.update = new Object()
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading()
    } catch (e) {
      this.dismissLoading()
      console.log(e);
      ToastUtils.show(e);
    }
  }

  async uploadImage(uri: string) {
    this.showLoading()
    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);
      FileUtil.closeSync(file);

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

      const result = await apiService.uploadImage(base64Str, 'feedback');
      if (result.isSuccess()) {
        this.imageEntity = plainToInstance(UploadImgEntity, result.data);
      } else {
        ToastUtils.show(result.message, true)
      }
      this.dismissLoading()
    } catch (e) {
      this.dismissLoading()
      console.log(e);
      ToastUtils.show(e);
    }
  }
}