import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

import '../../../../../common/api/index.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/utils/index.dart';
import '../../../../../common/values/index.dart';

class UpdatePasswordController extends GetxController {
  UpdatePasswordController();


  final oldPwdController = TextEditingController();
  final newPwdController = TextEditingController();
  final repeatNewPwdController = TextEditingController();

  // 登录加密
  RSAPublicKeyData? _publicKeyData;

  _initData() {
    update(["update_password"]);
  }
 

  @override
  void onReady() {
    loadRSAPublicKey();
    super.onReady();
    _initData();
  }
 
 ///
  /// 登录加密服务
  ///
  void loadRSAPublicKey() async {
    _publicKeyData = await OrgAuthenticationService.to.getRSAPublicKey();
    OLogger.d('加密服务：${_publicKeyData?.toJson()}');
  }

  void updatePwd() async {
    final oldpwd = oldPwdController.text;
    final newPwd = newPwdController.text;
    final repeatNewPwd = repeatNewPwdController.text;
    if (oldpwd.isEmpty) {
      Loading.toast('account_safe_old_pwd_not_empty'.tr);
      return;
    }
    if (newPwd.isEmpty) {
      Loading.toast('account_safe_new_pwd_not_empty'.tr);
      return;
    }
    if (repeatNewPwd.isEmpty) {
      Loading.toast('account_safe_new_pwd_repeat_not_empty'.tr);
      return;
    }
    if (newPwd != repeatNewPwd) {
      Loading.toast('account_safe_new_pwd_repeat_not_equal'.tr);
      return;
    }
    UpdateLoginPasswordForm form = UpdateLoginPasswordForm(
      oldPassword: oldpwd,
      newPassword: newPwd,
      confirmPassword: repeatNewPwd
    );
    if (_publicKeyData != null &&
          _publicKeyData?.publicKey != null &&
          _publicKeyData!.publicKey!.isNotEmpty &&
          _publicKeyData!.rsaEnable == true) {
        form.isEncrypted = O2.rsaEncryptedYes;
        //加密密码
        String publicKey = _publicKeyData!.publicKey!;
        String oldKey = await RSACryptUtil.encodeString(oldpwd, publicKey);
        OLogger.i("加密后的old密码：$oldKey");
        form.oldPassword = oldKey;
        String key = await RSACryptUtil.encodeString(newPwd, publicKey);
        OLogger.i("加密后的new密码：$key");
        form.newPassword = key;
        form.confirmPassword = key;
    }
    OLogger.d('更新密码: ${form.toJson()}');
    var result = await OrganizationPersonalService.to.updateLoginPassword(form);
    if (result != null) {
      Get.back();
      Loading.toast('account_safe_update_pwd_success'.tr);
    }
  }
}
