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 'sign_up_state.dart';

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

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

    var emailController = state.formData['email']!['controller'];
    var passwordController = state.formData['password']!['controller'];
    var confirmController = state.formData['confirm_password']!['controller'];

    state.email = emailController.text;
    state.password = passwordController.text;
    state.confirmPassword = confirmController.text;

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

    if (Utils.isEmpty(state.email)) {
      state.emailErrorText = "The email cannot be empty!".tr;
      update();
    } else if (Utils.isEmpty(state.password)) {
      state.passwordErrorText = "The 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 {
      //执行密码登录
      _request2Signup();
    }
  }

  // 调用接口注册
  void _request2Signup() async {
    var result = await _authRepository.hotelRegister(state.email, state.password, state.confirmPassword, cancelToken: cancelToken);

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

}
