import 'dart:convert';

import 'package:account_center/api/base_model.dart';
import 'package:account_center/common/sp/sp_util.dart';
import 'package:account_center/common/utils/reg_exp.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_clx_base/flutter_clx_base.dart';

import 'change_password_state.dart';

class ChangePasswordLogic extends GetxController {
  final ChangePasswordState state = ChangePasswordState();

  bool codeErr = false;
  String codeErrText = '请输入正确的验证码';
  bool passErr = false;
  String passErrText = '密码8-16位，需包含数字、大写字母及小写字母。';
  bool confirmPassErr = false;
  String confirmPassErrText = '两次输入的密码不一致!';

  @override
  void onReady() {
    var phone = getUserMobile() ?? "";
    state.userMobile = phone;
    update();
    super.onReady();
  }

  @override
  void onInit() {
    state.vCodeController.addListener(() {
      if (codeErr) {
        codeErr = state.vCodeController.text.length != 6;
        update();
      }
    });
    state.newPwdController.addListener(() {
      if (passErr) {
        passErr = RegExpUtil.checkPwd(state.newPwdController.text) == false;
        update();
      }
    });
    state.confirmPwdController.addListener(() {
      if (confirmPassErr) {
        confirmPassErr =
            state.newPwdController.text != state.confirmPwdController.text;
        if (state.confirmPwdController.text.isEmpty) {
          confirmPassErrText = '请输入确认密码';
        } else {
          confirmPassErrText = '两次输入的密码不一致!';
        }
        update();
      }
    });
    super.onInit();
  }

  //修改密码
  void updateLoginUserForPwd() {
    String vCode = state.vCodeController.text;
    String newPwd = state.newPwdController.text;
    String confirmPwd = state.confirmPwdController.text;

    var error = false;
    if (vCode.isEmpty) {
      codeErr = true;
      error = true;
    }
    if (newPwd.isEmpty) {
      passErr = true;
      passErrText = '请输入新密码';
      error = true;
    } else if (RegExpUtil.checkPwd(newPwd) == false) {
      passErr = true;
      passErrText = '密码8-16位，需包含数字、大写字母及小写字母。';
      error = true;
    }
    if (confirmPwd.isEmpty) {
      confirmPassErr = true;
      confirmPassErrText = '请输入确认密码';
      error = true;
    } else if (newPwd != confirmPwd) {
      confirmPassErr = true;
      confirmPassErrText = '两次输入的密码不一致!';
      error = true;
    }
    if (error) {
      update();
      return;
    }

    var content = Utf8Encoder().convert(newPwd);
    var digest = md5.convert(content);

    var params = {
      "captcha": vCode,
      "pwd": digest.toString(),
      "userMobile": state.userMobile,
    };

    fetch(Method.post, url: HttpApi.updateUserForPwd, params: params,
        onSuccess: (data) {
      Get.back();
      ToastUtil.showToast("修改成功");
    }, onError: (code, msg) {});
  }

}
