import 'package:get/get.dart';
import 'package:vitalapp/architecture/defines.dart';
import 'package:vitalapp/architecture/utils/prompt_box.dart';
import 'package:vitalapp/managers/interfaces/account.dart';
import 'package:vitalapp/managers/interfaces/doctor.dart';
import 'package:vitalapp/pages/home/personal_center/state.dart';
import 'package:vitalapp/store/store.dart';
import 'package:fis_common/helpers/encrypt.dart';

class PersonalCenterController extends FControllerBase {
  final state = PersonalCenterState();
  final _accountManager = Get.find<IAccountManager>();
  @override
  void onReady() {
    super.onReady();
    _loadData();
    _updateSignature(Store.user.signature);
  }

  void _loadData() async {
    var result = await _accountManager.getUserDetailAsync();
    if (result != null) {
      state.updateDto(result);
    }
  }

  /// 重新签名
  Future<void> rewrite() async {
    final result = await Get.toNamed("/contract/signature");
    if (result != null) {
      final saved = await Get.find<IDoctorManager>().setSignature(result);
      if (saved) {
        _updateSignature(result);
      } else {
        PromptBox.toast("设置签名失败");
      }
    }
  }

  void _updateSignature(String value) {
    state.signaturUrl = value;
  }

  Future<bool> updateUserInfo() async {
    state.dto.realName = state.name;
    state.dto.phone = state.phone;
    state.dto.headImageToken = state.headImageToken;
    final result = await _accountManager.updateUserAsync(state.dto);
    return result;
  }

  Future<void> setPassword() async {
    final oldPassword = await _accountManager.getUserPasswordDetailAsync();
    var oldPasswordEncrypt = FEncryptHelper.symmetryEncrypt(state.oldPassword);
    if (state.oldPassword.isEmpty) {
      PromptBox.toast("原密码不能为空！");
      return;
    }
    if (state.newPassword.isEmpty) {
      PromptBox.toast("新密码不能为空！");
      return;
    }
    if (state.confirmPassword.isEmpty) {
      PromptBox.toast("确认密码密码不能为空！");
      return;
    }
    if (oldPassword != oldPasswordEncrypt) {
      PromptBox.toast("原密码输入错误！");
      return;
    }
    if (state.newPassword != state.confirmPassword) {
      PromptBox.toast("密码输入不一致！");
      return;
    }
    var newPassword = FEncryptHelper.symmetryEncrypt(state.newPassword);
    if (oldPasswordEncrypt == newPassword) {
      PromptBox.toast('新密码不能与旧密码相同！');
      return;
    }
    final result = await _accountManager.updateUserPasswordAsync(newPassword);
    if (result) {
      PromptBox.toast("密码更新成功！");
    }
  }
}
