import 'package:domain/repository/auth_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import 'reset_psd_state.dart';

class ResetPasswordController extends GetxController with DioCancelableMixin{
  final AuthRepository _authRepository = Get.find();
  final ResetPasswordState state = ResetPasswordState();

  //执行注册操作
  void doResetPassword() {
    state.passwordErrorText = null;
    state.confirmPasswordErrorText = null;
    update();

    var oldPasswordController = state.formData['old_password']!['controller'];
    var passwordController = state.formData['new_password']!['controller'];
    var confirmController = state.formData['confirm_password']!['controller'];

    state.oldPassword = oldPasswordController.text;
    state.password = passwordController.text;
    state.confirmPassword = confirmController.text;

    Log.d('当前待提交的 password:${state.password} confirmPassword:${state.confirmPassword}');

    if (Utils.isEmpty(state.oldPassword)) {
      state.passwordErrorText = "The password cannot be empty!".tr;
      update();
    } else if (Utils.isEmpty(state.password)) {
      state.confirmPasswordErrorText = "The new password cannot be empty!".tr;
      update();
    } else if (Utils.isEmpty(state.confirmPassword)) {
      state.confirmPasswordErrorText = "The confirm password cannot be empty!".tr;
      update();
    } else if (state.confirmPassword != state.password) {
      state.confirmPasswordErrorText = "Please confirm your confirmed password!".tr;
      update();
    } else {
      //执行密码登录
      _request2ResetPassword();
    }
  }

  // 调用接口重置密码
  void _request2ResetPassword() async {
    var result = await _authRepository.resetPassword(state.oldPassword, state.password, state.confirmPassword, cancelToken: cancelToken);

    //处理数据
    if (result.isSuccess) {
      //提交成功
      NotifyEngine.showSuccess("Successful".tr);
      Get.back();
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

}
