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 '../../../environment_config.dart';
import '../../common/inner_webview/view.dart';
import 'index.dart';

class RegisterController extends GetxController {
  RegisterController();

  final state = RegisterState();

  // 注册用户名的控制器
  final TextEditingController userNameController = TextEditingController();
  // 密码的控制器
  final TextEditingController passwordController = TextEditingController();
  //  第二次密码的控制器
  final TextEditingController repeatPasswordController =
      TextEditingController();
  // 邮箱的控制器
  final TextEditingController emailController = TextEditingController();
  // 手机号码的控制器
  final TextEditingController phoneController = TextEditingController();
  // 图片验证码的控制器
  final TextEditingController captchaController = TextEditingController();
  // 验证码的控制器
  final TextEditingController codeController = TextEditingController();

  final FocusNode passwordNode = FocusNode();
  final FocusNode repeatPasswordNode = FocusNode();
  final FocusNode emailNode = FocusNode();
  final FocusNode phoneNode = FocusNode();

  final FocusNode codeNode = FocusNode();
  final FocusNode captchaNode = FocusNode();

  // 图片验证码对象
  CaptchaImgData? _captchaImgData;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.isVisibleAgree = EnvironmentConfig.needCheckPrivacyAgree();
    loadRegisterMode();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  Future<void> loadRegisterMode() async {
    ValueStringData? data = await OrganizationPersonalService.to.registerMode();
    if (data != null && data.value?.isNotEmpty == true) {
      if (data.value == O2.registerModeDisable) {
        OLogger.e('错误，注册已经关闭！ ${data.value}');
        Get.back();
        return;
      }
      state.isCaptcha = (data.value == O2.registerModeCaptcha);
      if (state.isCaptcha) {
        getCaptchaImageData();
      }
      OLogger.d("注册模式：${data.value} ");
    }
  }

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

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

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

  /// 发送短信验证码
  Future<void> sendSmsCode() async {
    var mobile = phoneController.value.text;
    if (mobile.isEmpty) {
      Loading.toast('login_form_register_phone_not_empty'.tr);
      return;
    }
    var res = await OrganizationPersonalService.to.getRegisterCode(mobile);
    if (res != null && res.value == true) {
      if (Get.context != null) {
        FocusScope.of(Get.context!).requestFocus(codeNode);
        Loading.toast('bind_send_code_success'.tr);
      }
    }
  }

  Future<bool> checkUserName(String username) async {
    final res =
        await OrganizationPersonalService.to.checkRegisterUserName(username);
    return (res != null && res.value != null && res.value == true);
  }

  Future<void> register() async {
    final username = userNameController.value.text;
    if (username.isEmpty) {
      Loading.toast('login_form_user_name_not_empty'.tr);
      return;
    }
    final checkName = await checkUserName(username);
    if (!checkName) {
      return;
    }
    final password = passwordController.value.text;
    if (password.isEmpty) {
      Loading.toast('login_form_user_password_not_empty'.tr);
      return;
    }
    final repeatPassword = repeatPasswordController.value.text;
    if (repeatPassword.isEmpty) {
      Loading.toast('login_form_user_password_repeat_not_empty'.tr);
      return;
    }
    if (password != repeatPassword) {
      Loading.toast('login_form_user_password_repeat_not_equals'.tr);
      return;
    }
    final mobile = phoneController.value.text;
    if (mobile.isEmpty) {
      Loading.toast('login_form_register_phone_not_empty'.tr);
      return;
    }
    Map<String, String> post = {};
    post['name'] = username;
    post['password'] = password;
    post['mobile'] = mobile;
     
    if (state.isCaptcha) {
      final captchaInput = captchaController.value.text;
      if (captchaInput.isEmpty) {
         Loading.toast('login_form_user_code_not_empty'.tr);
        return;
      }
      // 图片验证码注册
      post['captchaAnswer'] = captchaInput;
      post['captcha'] = _captchaImgData?.id ?? '';
    } else {
       final codeInput = codeController.value.text;
      if (codeInput.isEmpty) {
        Loading.toast('login_form_user_code_not_empty'.tr);
        return;
      }
      // 短信验证码
      post['codeAnswer'] = codeInput;
    }

    post['mail'] = emailController.value.text;
    post['genderType'] = 'd';


    final result = await OrganizationPersonalService.to.register(post);
    if (result != null && result.value == true) {
      Loading.toast('register_success_to_login'.tr);
      gotoLogin();
    } else {
      if (state.isCaptcha) {
        getCaptchaImageData();
      }
    }

  }

  void gotoLogin() {
    Get.offAllNamed(O2OARoutes.login);
  }

  /// 同意协议
  void changeAgree(bool? v) {
    state.isAgree = v == true;
  }

  /// 打开用户协议
  void openUserAgreement() {
    InnerWebviewPage.open(O2.userAgreementUrl);
  }

  /// 打开隐私政策
  void openPrivacyPolicy() {
    InnerWebviewPage.open(O2.privacyPolicyUrl);
  }
}
