import { plainToInstance } from 'class-transformer';
import { LoginEntity } from '../entity/LoginEntity';
import { SendCodeEntity } from '../entity/SendCodeEntity';
import { apiService } from '../net/ApiService';
import { ToastUtils } from '../utils/ToastUtils';
import { BaseViewModel } from './BaseViewModel';

@ObservedV2
export default class LoginViewModel extends BaseViewModel {
  @Trace codeEntity?: SendCodeEntity;
  @Trace phoneLoginEntity?: LoginEntity;
  @Trace wxLoginEntity?: LoginEntity;

  async sendCode(phone: string) {
    this.showLoading();
    try {
      const result = await apiService.sendCode(phone);
      if (result.isSuccess()) {
        this.codeEntity = plainToInstance(SendCodeEntity, result.data);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async phoneLogin(phone: string, code: string, timestamp: string) {
    this.showLoading();
    try {
      const result = await apiService.loginByPhone(phone, code, timestamp);
      if (result.isSuccess()) {
        this.phoneLoginEntity = plainToInstance(LoginEntity, result.data);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }

  async wxLogin(code: string) {
    this.showLoading();
    try {
      const result = await apiService.loginByWX(code);
      if (result.isSuccess()) {
        this.wxLoginEntity = plainToInstance(LoginEntity, result.data);
      } else {
        ToastUtils.show(result.message, true);
      }
      this.dismissLoading();
    } catch (e) {
      console.log(e);
      ToastUtils.show(e);
      this.dismissLoading();
    }
  }
}