import 'dart:io';

import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:local_auth/local_auth.dart';
import 'package:local_auth_android/local_auth_android.dart';
import 'package:local_auth_ios/local_auth_ios.dart';

import '../../../../common/routers/index.dart';
import '../../../../common/services/index.dart';
import '../../../../common/utils/index.dart';
import 'gesture_unlock/index.dart';
import 'index.dart';

class AccountSafeController extends GetxController {
  AccountSafeController();

  final state = AccountSafeState();
  final LocalAuthentication auth = LocalAuthentication();

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    _loadBiometricInfo();
    state.biometricAuthSwitch = SharedPreferenceService.to
        .getBool(SharedPreferenceService.appBiometricAuthKey);
    state.gestureUnlockAuthSwitch = SharedPreferenceService.to
        .getString(SharedPreferenceService.appGestureUnlockAuthKey)
        .isNotEmpty;
    super.onReady();
  }

  /// 修改登录密码
  void goUpdatePassword() {
    Get.toNamed(O2OARoutes.homeSettingsAccountSafeUpdatePwd);
  }

  /// 变更手机号码
  void goChangeMobile() {}

  /// 外出授权
  void goEmpower() {
    Get.toNamed(O2OARoutes.homeSettingsAccountSafeEmpower);
  }

  Future<void> _loadBiometricInfo() async {
    state.title = 'account_safe_local_auth'.tr;
    final typeList = await _loadBiometricTypes();
    OLogger.d(typeList.length);
    if (typeList.contains(BiometricType.face)) {
      state.title = 'account_safe_local_auth_faceid'.tr;
    } else if (typeList.contains(BiometricType.fingerprint)) {
      state.title = 'account_safe_local_auth_touchid'.tr;
    }
  }

  Future<List<BiometricType>> _loadBiometricTypes() async {
    final deviceInfoPlugin = DeviceInfoPlugin();
    if (Platform.isAndroid) {
      final android = await deviceInfoPlugin.androidInfo;
      OLogger.d(android);
      //  API 29 (Android Q)
      if ((android.version.sdkInt ?? 0) >= 29) {
        return await auth.getAvailableBiometrics();
      }
    } else if (Platform.isIOS) {
      return await auth.getAvailableBiometrics();
    }
    return [];
  }

  void switchLocalAuth(bool auth) {
    if (auth) {
      _openBiometricAuth();
    } else {
      _setBiometricAuthSwitch(false);
    }
  }

  Future<void> _openBiometricAuth() async {
    try {
      final didAuthenticate = await auth.authenticate(
          localizedReason: 'account_safe_local_auth_open_confirm'.tr,
          authMessages: [
            AndroidAuthMessages(
                biometricRequiredTitle:
                    'account_safe_local_auth_biometric_required'.tr,
                goToSettingsDescription:
                    'account_safe_local_auth_android_description'.tr,
                cancelButton: 'cancel'.tr,
                goToSettingsButton: 'account_safe_local_auth_go_to_setting'.tr,
                biometricNotRecognized:
                    'account_safe_local_auth_not_recognized'.tr,
                biometricHint: 'account_safe_local_auth_android_bio_hint'.tr,
                signInTitle:
                    'account_safe_local_auth_android_bio_sign_in_title'.tr),
            IOSAuthMessages(
              goToSettingsButton: 'account_safe_local_auth_go_to_setting'.tr,
              goToSettingsDescription:
                  'account_safe_local_auth_ios_description'.tr,
              cancelButton: 'cancel'.tr,
            )
          ],
          options: const AuthenticationOptions(biometricOnly: false));
      _setBiometricAuthSwitch(didAuthenticate);
    } on PlatformException catch (e) {
      OLogger.e('认证失败', e);
      _setBiometricAuthSwitch(false);
    }
  }

  void _setBiometricAuthSwitch(bool isOpen) {
    SharedPreferenceService.to
        .putBool(SharedPreferenceService.appBiometricAuthKey, isOpen);
    state.biometricAuthSwitch = isOpen;
  }

  /// 手势密码开启关闭
  void switchGestureUnlock(bool isOpen) async {
    if (isOpen) {
      await GestureUnlockPage.setupGesturePassword();
      // 检查是否设置成功
      state.gestureUnlockAuthSwitch = SharedPreferenceService.to
          .getString(SharedPreferenceService.appGestureUnlockAuthKey)
          .isNotEmpty;
    } else {
      // 清空密码
      SharedPreferenceService.to
          .putString(SharedPreferenceService.appGestureUnlockAuthKey, '');
      state.gestureUnlockAuthSwitch = false;
    }
  }
}
