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

import '../../common/index.dart';
import '../common/inner_webview/index.dart';
import 'index.dart';

class BindController extends GetxController {
  BindController();

  final state = BindState();
  final GlobalKey<FormState> formKey = GlobalKey();
  final FocusNode codeNode = FocusNode();
  final List<O2CloudServer> unitList = [];

  // 手机号码的控制器
  final TextEditingController phoneController = TextEditingController();
  // 验证码的控制器
  final TextEditingController codeController = TextEditingController();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

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

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

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 检查手机号码
  bool onCheckMobile() {
    var phone = phoneController.value.text;
    OLogger.d('手机号码:$phone');
    if (!O2Utils.isMobilePhoneNumber(phone)) {
      Loading.toast('bind_mobile_error_message'.tr);
      return false;
    }
    return true;
  }

  /// 发送短信验证码
  void sendSmsCode() async {
    Loading.show();
    var data = CollectCodeData();
    data.mobile = phoneController.value.text;
    var res = await CollectService.to.getCode(data);
    Loading.dismiss();
    if (res != null) {
      if (Get.context != null) {
        FocusScope.of(Get.context!).requestFocus(codeNode);
      }
      Loading.toast('bind_send_code_success'.tr);
    } else {
      Loading.showError('bind_send_code_fail'.tr);
    }
  }

  ///
  /// 获取服务器列表
  /// 如果当前手机号码绑定了多个o2oa服务器，则进入第二步选择服务器
  /// 如果当前手机号码只有一个绑定的o2oa服务器，直接登录进入
  /// 如果当前手机号码没有绑定的o2oa服务器，提示进入演示服务器
  ///
  void nextStep() async {
    if (!state.isAgree) {
      Loading.showError('privacy_policy_bind_disagree_alert'.tr);
      return;
    }
    FormState? form = formKey.currentState;
    if (form?.validate() == true) {
      form?.save();
      OLogger.d('绑定服务器');
      final phone = phoneController.value.text;
      final code = codeController.value.text;
      if (!O2Utils.isMobilePhoneNumber(phone)) {
        Loading.toast('bind_mobile_error_message'.tr);
        return;
      }
      if (code.isEmpty) {
        Loading.toast('bind_code_error_message'.tr);
        return;
      }
      // 审核登录用的 
      if (phone == "13912345678" && code == "5678") {
        _mockLoginToApp();
      } else {
        Loading.show();
        final list = await CollectService.to.getUnitList(phone, code);
        if (list != null) {
          Loading.dismiss();
          if (list.isNotEmpty) {
            //只有一个o2oa服务器就直接进入，如果有多个就进入第二步选择绑定的服务器
            if (list.length == 1) {
              chooseUnit(list[0]);
            } else {
              unitList.clear();
              unitList.addAll(list);
              state.isStepOne = false; // 进入第二步
            }
          } else {
            gotoSample('bind_phone_no_bind_message'.tr);
          }
        } else {
          gotoSample('bind_phone_no_bind_message'.tr);
        }
      }
    }
  }

  /// 选择一个o2oa服务器进行连接
  void chooseUnit(O2CloudServer unit) async {
    OLogger.i('选择绑定服务器: ${unit.toJson()}');
    var deviceId = O2ApiManager.instance.deviceID;
    if (deviceId.isEmpty) {
      var remoteId = await O2ApiManager.instance.getJPushDeviceIdRemote();
      if (remoteId.isEmpty) {
        Loading.toast('bind_no_device_message'.tr);
        return;
      } else {
        deviceId = remoteId;
      }
    }
    Loading.show(text: 'bind_loading'.tr);
    var mobilePhone = phoneController.value.text;
    var code = codeController.value.text;
    O2CloudBindData data = O2CloudBindData();
    data.code = code;
    data.mobile = mobilePhone;
    data.name = deviceId;
    data.unit = unit.name;
    data.deviceType = GetPlatform.isAndroid ? 'android' : 'ios';

    // 开始绑定
    IdData? id = await CollectService.to.bindDevice(data);
    if (id != null) {
      // 绑定成功 存储服务器信息
      await O2ApiManager.instance.putO2UnitJson2SP(unit);
      // 连接绑定的服务器
      var isLoadO2OA = await ProgramCenterService.to.loadCenterServerOnline();
      if (!isLoadO2OA) {
        OLogger.e('连接服务器失败！！！！');
        Loading.dismiss();
        gotoSample('connect_o2_server_fail_go_to_sample'.tr);
      } else {
        OLogger.d('连接服务器成功，开始下载配置登录o2oa....');
        await ProgramCenterService.to.loadCurrentStyle(); // 获取appstyle
        // login
        O2Person? person =
            await OrgAuthenticationService.to.loginWithCode(mobilePhone, code);
        Loading.dismiss();
        if (person == null) {
          OLogger.e('登录失败，跳转到登录界面！');
          // 登录失败
          Get.offNamed(O2OARoutes.login);
        } else {
          // 登录成功
          Get.offNamed(O2OARoutes.home);
        }
      }
    } else {
      OLogger.e('绑定失败， 返回第一步！！！！');
      Loading.dismiss();
      state.isStepOne = true; // 返回第一步
    }
  }

  /// 连接到 sample 服务器
  void gotoSample(String message) {
    O2UI.showConfirm(Get.context, message, okText: 'sample_server_name'.tr,
        okPressed: () {
      O2ApiManager.instance.putSampleUnitServerAndReload();
    }, cancelPressed: () {
      state.isStepOne = true; // 返回第一步
    });
  }

  void changeAgree(bool? v) {
    state.isAgree = v == true;
  }

  void openUserAgreement() {
    InnerWebviewPage.open(O2.userAgreementUrl);
  }

  void openPrivacyPolicy() {
    InnerWebviewPage.open(O2.privacyPolicyUrl);
  }

  /// 模拟登录   app.o2oa.net 服务器
  void _mockLoginToApp() async {
    final cloud = O2CloudServer(
        id: 'app',
        name: 'app.o2oa.net',
        centerHost: 'app.o2oa.net',
        centerContext: '/x_program_center',
        centerPort: 443,
        httpProtocol: 'https');
    Loading.show();

    /// 绑定服务器
    await O2ApiManager.instance.putO2UnitJson2SP(cloud);
    // 连接绑定的服务器
    final isLoadO2OA = await ProgramCenterService.to.loadCenterServerOnline();
    if (!isLoadO2OA) {
      OLogger.e('连接服务器失败！！！！');
      Loading.dismiss();
      Get.offNamed(O2OARoutes.login);
    } else {
      OLogger.d('连接服务器成功，开始下载配置登录o2oa....');
      await ProgramCenterService.to.loadCurrentStyle();
      // rsa
      final publicKeyData = await OrgAuthenticationService.to.getRSAPublicKey();
      // login
      var form = LoginForm();
      form.credential = "13912345678";
      form.password = "345678";
      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("345678", publicKey);
        OLogger.d("加密后的密码：$key");
        form.password = key;
      } else {
        form.isEncrypted = O2.rsaEncryptedNo;
      }
      O2Person? person = await OrgAuthenticationService.to.login(form);
      // O2Person? person = await OrgAuthenticationService.to.loginWithCode(mobilePhone, code);
      Loading.dismiss();
      if (person == null) {
        OLogger.e('登录失败，跳转到登录界面！');
        // 登录失败
        Get.offNamed(O2OARoutes.login);
      } else {
        // 登录成功
        Get.offNamed(O2OARoutes.home);
      }
    }
  }
}
