import { plainToInstance } from 'class-transformer';
import { UserEntity } from '../entity/UserEntity';
import { LoginManager } from '../manager/LoginGlobalManager';
import { apiService } from '../net/ApiService';
import { ToastUtils } from '../utils/ToastUtils';
import { BaseViewModel } from './BaseViewModel';

@ObservedV2
export default class BindAccountViewModel extends BaseViewModel {
  @Trace userEntity?: UserEntity;
  @Trace bindInfo?: object;
  @Trace unbindInfo?: string;

  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) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async bindWx(code: string) {
    this.showLoading();
    try {
      const result = await apiService.loginByWX(code, true);
      if (result.isSuccess()) {
        this.bindInfo = new Object();
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async unbind(loginType: string) {
    this.showLoading();
    try {
      const result = await apiService.unbind(loginType);
      if (result.isSuccess()) {
        this.unbindInfo = loginType;
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }
}