import 'dart:convert';
import 'dart:typed_data';

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

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

class DemoLoginController extends GetxController {
  DemoLoginController();

  final state = DemoLoginState();
 
  @override
  void onReady() {
    loadRSAPublicKey();
    loadLoginMode();
    state.year = '${DateTime.now().year}';
    super.onReady();
  }
 
  
  // 登录用户名的控制器
  final TextEditingController userNameController = TextEditingController();
  // 验证码的控制器
  final TextEditingController codeController = TextEditingController();
  // 密码的控制器
  final TextEditingController passwordController = TextEditingController();
  // 图片验证码的控制器
  final TextEditingController captchaController = TextEditingController();

  // 密码输入框
  final FocusNode passwordNode = FocusNode();
  // 验证码的输入框
  final FocusNode codeNode = FocusNode();
  // 图片验证码输入框
  final FocusNode captchaNode = FocusNode();

  // 图片验证码对象
  CaptchaImgData? _captchaImgData;
  // 登录加密
  RSAPublicKeyData? _publicKeyData;

 

  ///
  /// 登录加密服务
  ///
  void loadRSAPublicKey() async {
    _publicKeyData = await OrgAuthenticationService.to.getRSAPublicKey();
  }

  ///
  /// 登录模式查询，是否开启短信验证码登录，是否显示图片验证码等
  ///
  void loadLoginMode() async {
    LoginModeData? data = await OrgAuthenticationService.to.getLoginMode();
    if (data != null) {
      var isCaptcha = data.captchaLogin ?? false;
      if (isCaptcha) {
        state.isCaptcha = true;
        getCaptchaImageData();
      }
      OLogger.d("登录模式 captcha: $isCaptcha");
    }
  }

  ///
  /// 获取图片验证码
  ///
  void getCaptchaImageData() async {
    _captchaImgData =
        await OrgAuthenticationService.to.getLoginCaptchaImgData(100, 50);
    if (_captchaImgData != null) {
      captchaController.clear();
      state.captchaBase64String = _captchaImgData?.image ?? '';
    } else {
      OLogger.e('获取图片验证码失败！');
    }
  }

  ///
  /// 解析图片验证码
  ///
  Uint8List parseCaptchaImg() {
    return base64Decode(state.captchaBase64String);
  }

  /// 检查手机号码
  bool onCheckMobile() {
    var phone = userNameController.value.text;
    if (phone.isEmpty) {
      Loading.toast('login_form_user_name_not_empty'.tr);
      return false;
    }
    return true;
  }

  /// 发送短信验证码
  void sendSmsCode() async {
    var mobile = userNameController.value.text;
    if (mobile.isEmpty) {
      Loading.toast('login_form_user_name_not_empty'.tr);
      return;
    }
    Loading.show();
    var res = await OrgAuthenticationService.to.getPhoneCode(mobile);
    Loading.dismiss();
    if (res != null) {
      if (Get.context != null) {
        FocusScope.of(Get.context!).requestFocus(codeNode);
      }
      Loading.toast('bind_send_code_success'.tr);
    }
  }

  ///
  /// 登录
  ///
  void login() async {
    var username = userNameController.value.text;
    var code = codeController.value.text;
    var password = passwordController.value.text;
    var captcha = captchaController.value.text;
    OLogger.d(
        "登录， userName: $username code: $code, pwd: $password, captcha: $captcha");
    if (username.isEmpty) {
      Loading.toast('login_form_user_name_not_empty'.tr);
      return;
    }
    if (state.isPasswordLogin) {
      // 密码登录
      if (password.isEmpty) {
        Loading.toast('login_form_user_password_not_empty'.tr);
        return;
      }
      if (state.isCaptcha && captcha.isEmpty) {
        Loading.toast('login_form_user_code_not_empty'.tr);
        return;
      }
      Loading.show();
      var form = LoginForm();
      form.credential = username;
      form.password = password;
      if (state.isCaptcha && _captchaImgData != null) {
        form.captcha = _captchaImgData?.id;
        form.captchaAnswer = captcha;
      }
      if (_publicKeyData != null &&
          _publicKeyData?.publicKey != null &&
          _publicKeyData!.publicKey!.isNotEmpty &&
          _publicKeyData!.rsaEnable == true) {
        form.isEncrypted = O2.rsaEncryptedYes;
        //加密密码
        String publicKey = _publicKeyData!.publicKey!;
        String key = await RSACryptUtil.encodeString(password, publicKey);
        OLogger.i("加密后的密码：$key");
        form.password = key;
      } else {
        form.isEncrypted = O2.rsaEncryptedNo;
      }
      O2Person? person = await OrgAuthenticationService.to.login(form);
      if (person != null) {
        Loading.dismiss();
        // 登录成功
        Get.offNamed(O2OARoutes.home);
      } else {
        // 登录错误，如果有验证码需要刷新，不然还是老的验证码无法使用
        if (state.isCaptcha) {
          OLogger.i("登录错误，刷新验证码");
          getCaptchaImageData();
        }
      }
    } else {
      // 短信验证码登录
      if (code.isEmpty) {
        Loading.toast('login_form_user_code_not_empty'.tr);
        return;
      }
      Loading.show();
      O2Person? person =
          await OrgAuthenticationService.to.loginWithCode(username, code);
      if (person != null) {
        Loading.dismiss();
        // 登录成功
        Get.offNamed(O2OARoutes.home);
      }
    }
  }

  /// 切换绑定的服务器
  void changeBindServer() {
    final context = Get.context;
    if (context == null) {
      return;
    }
    final list = SampleEditionManger.instance.getServerList();
    if (list.isEmpty) {
      Loading.toast('text'.tr);
      return ;
    }
    final menus = list.map((e) => SheetMenuData(e.name ?? '', (){
      _rebindExecute(e);
    })).toList();
    
    O2UI.showBottomSheetWithMenuData(context, menus);
  }
  _rebindExecute(O2CloudServer server) async {
     SampleEditionManger.instance.setCurrentAndReloadApp(server, needReload: true);
  }

  /// 获取账号密码
  void getSampleAccounts() async {
    Loading.show();
    final unit = SampleEditionManger.instance.getCurrent();
    final body = WwwGetSampleAccountPost();
    body.serverId = unit.id;
    final accounts = await O2OAWwwService.to.executeSampleAccountsShell(body);
    if (accounts != null) {
      Loading.dismiss();
      final list = accounts.accountList ?? [];
      if (list.isEmpty) {
        Loading.showError('login_form_demo_no_account_list'.tr);
        return;
      }
      _chooseAccount(accounts);
    }
  }
  // 选择账号密码
  void _chooseAccount(WwwGetSampleAccounts accounts) {
    final context = Get.context;
    if (context == null) {
      return;
    }
    final list = accounts.accountList ?? [];
    final pwd = accounts.password ?? '';
    final menus = list.map((e) => SheetMenuData('${e.name}: ${e.account}', (){
      // 点击把账号密码写入输入框
      userNameController.text = e.account ?? '';
      passwordController.text = pwd;
    })).toList();
    O2UI.showBottomSheetWithMenuData(context, menus);
  }
 
}
