import 'dart:async';
import 'dart:io';
import 'dart:typed_data';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/date_extension.dart';

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/routers/index.dart';
import '../../common/services/index.dart';
import '../../common/utils/index.dart';
import '../../common/values/index.dart';
import '../../common/widgets/index.dart';
import '../../environment_config.dart';
import '../../global.dart';
import '../common/inner_webview/index.dart';
import '../home/settings/account_safe/gesture_unlock/index.dart';
import '../login/server_info/index.dart';
import 'state.dart';

class SplashController extends GetxController {
  SplashController();

  final state = SplashState();
  Uint8List? launchLogo;

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    O2UI.hideStatusBar();
    state.copyright =
        '@ ${DateTime.now().year} ${'appName'.tr} All right reserved.';
    _checkPrivacyAgree();
    super.onReady();
  }

  @override
  void onClose() {
    O2UI.showStatusBar();
    super.onClose();
  }

  /// 是否同意了隐私政策
  void _checkPrivacyAgree() {
    if (EnvironmentConfig.needCheckPrivacyAgree()) {
      final isAgree = SharedPreferenceService.to
          .getBool(SharedPreferenceService.isAgreePrivacyKey);
      if (isAgree) {
        _splashLoading();
        return;
      }
      _privacyDialog();
    } else {
      _splashLoading();
    }
  }

  /// 隐私政策 弹出窗口
  void _privacyDialog() async {
    final context = Get.context;
    if (context == null) {
      OLogger.i('没有 context，退出 APP');
      exit(0);
    }
    RichText richText = RichText(
      text: TextSpan(
          text: 'privacy_policy_dialog_content_part1'.tr,
          style: Theme.of(context).textTheme.bodyMedium,
          children: [
            TextSpan(
                text: 'user_agreement_book_mark'.tr,
                style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => openUserAgreement()),
            TextSpan(
              text: 'privacy_policy_dialog_content_part2'.tr,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
            TextSpan(
                text: 'privacy_policy_book_mark'.tr,
                style: TextStyle(
                    color: Theme.of(context).colorScheme.primary,
                    fontSize: 14),
                recognizer: TapGestureRecognizer()
                  ..onTap = () => openPrivacyPolicy()),
            TextSpan(
              text: 'privacy_policy_dialog_content_part3'.tr,
              style: Theme.of(context).textTheme.bodyMedium,
            ),
          ]),
    );
    final result = await O2UI.showCustomDialog(
        context, 'privacy_policy_dialog_title'.tr, richText,
        positiveBtnText: 'agree'.tr, cancelBtnText: 'disagree'.tr);
    if (result != null && result == O2DialogAction.positive) {
      _agree();
      _splashLoading();
    } else {
      // 退出
      OLogger.i('不同意，退出 APP');
      exit(0);
    }
  }

  /// 写入标记
  void _agree() {
    SharedPreferenceService.to
        .putBool(SharedPreferenceService.isAgreePrivacyKey, true);
  }

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

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

  void _denyRoot() {
    final context = Get.context;
    if (context == null) {
      OLogger.i('没有 context，退出 APP');
      exit(0);
    }
    O2UI.showAlert(context, 'deny_root'.tr, okPressed: () => exit(0));
  }

  /// 启动加载过程
  Future<void> _splashLoading() async {
    // 安全检查
    final result = await O2FlutterMethodChannelUtils().checkRootNative();
    if (result) {
      _denyRoot();
      return;
    }
    Global.initLater(); // 需要同意后执行的
    // 演示版本  app
    if (EnvironmentConfig.isDemoApp()) {
      // 获取演示服务器列表
      await SampleEditionManger.instance.loadServerListFromWwwService();
      await SampleEditionManger.instance.setCurrentAndReloadApp(
          SampleEditionManger.instance.getCurrent(),
          needReload: false);
    } else {
      // 检查绑定服务器和服务器信息
      var hasUnitInfo = await O2ApiManager.instance.loadO2UnitFromSP();
      if (!hasUnitInfo) {
        // 没有服务器信息 去绑定
        OLogger.i('splash_nobind_go'.tr);
        state.tips = 'splash_nobind_go'.tr;
        Get.offNamed(O2OARoutes.bind);
        return;
      }
    }
    // 开始连接 O2OA  服务器
    state.tips = 'splash_connecting'.tr;
    // 连接服务器
    try {
      OLogger.d('开始连接O2OA服务器。。。。。');
      var isLoadO2OA = await ProgramCenterService.to.loadCenterServerOnline();
      if (!isLoadO2OA) {
        _connectServerFail();
      } else {
        // 移除网络监听
        if (Platform.isIOS) {
          NetworkCheckHelper().clearDelegate();
        }
        state.tips = 'splash_logining'.tr;
        try {
          await ProgramCenterService.to.loadCurrentStyle(); // 获取appstyle
          state.showLaunchLogo = true; // 显示 logo
          // 读取设备号
          if (GetPlatform.isMobile) {
            O2ApiManager.instance.getJPushDeviceIdRemote();
          }
        } catch (err, stackTrace) {
          OLogger.e('获取appStyle失败', err, stackTrace);
        }
        // 登录判断
        final isLogin = await _checkLogin();
        OLogger.d('登录： $isLogin');
        // 先显示推广页
        await _checkAndShowPromotionPages();
        if (isLogin) {
          _gotoHome();
        } else {
          // 清除保存的用户信息
          O2ApiManager.instance.cleanUser();
          _goToLogin();
        }
      }
    } catch (err, stackTrace) {
      OLogger.e('连接服务器失败', err, stackTrace);
      _connectServerFail();
    }
  }

  // int _iosReconnectTimes = 0;
  /// 显示连接错误信息
  void _connectServerFail() {
    /// ios 初次连接的是网络权限还没开 开启网络监听
    // if (Platform.isIOS && _iosReconnectTimes < 3) {
    //   state.tips = 'splash_connect_fail_ios_waiting'.tr;
    //   _iosReconnectTimes++;
    //   OLogger.i('添加网络监听 $_iosReconnectTimes');
    //   NetworkCheckHelper().setDelegate((result) {
    //     OLogger.i('网络连接情况切换： $result');
    //     _splashLoading();
    //   });
    // } else {
    OLogger.i('splash_connect_fail'.tr);
    state.tips = 'splash_connect_fail'.tr;
    if (!EnvironmentConfig.isDirectConnectMode()) {
      List<DialogActionData> actions = [
        DialogActionData(title: 'cancel'.tr, pressedCall: () => exit(0)),
        DialogActionData(
            title: 'sample_server_name'.tr,
            pressedCall: () => O2ApiManager.instance.putSampleUnitServerAndReload()),
        DialogActionData(
            title: 'login_form_rebind'.tr,
            pressedCall: () => _rebind()),
      ];
       O2UI.showConfirmWithActions(
          Get.context, 'connect_o2_server_fail_go_to_sample'.tr, actions);
      // O2UI.showConfirm(Get.context, 'connect_o2_server_fail_go_to_sample'.tr,
      //     okText: 'sample_server_name'.tr,
      //     okPressed: () => O2ApiManager.instance.putSampleUnitServerAndReload(),
      //     cancelPressed: () => exit(0));
    } else {
      // 通过重试按钮处理网络问题
      List<DialogActionData> actions = [
        DialogActionData(title: 'cancel'.tr, pressedCall: () => exit(0)),
        DialogActionData(
            title: 'connect_o2_server_fail_go_to_edit'.tr,
            pressedCall: () => ServerInfoPage.open(finishSelf: true)),
        DialogActionData(
            title: 'connect_o2_server_fail_refresh'.tr,
            pressedCall: () => _splashLoading()),
      ];
      O2UI.showConfirmWithActions(
          Get.context, 'connect_o2_server_fail_confirm_edit'.tr, actions);
      // O2UI.showConfirm(Get.context, 'connect_o2_server_fail_confirm_edit'.tr,
      //     okText: 'connect_o2_server_fail_go_to_edit'.tr,
      //     okPressed: () => ServerInfoPage.open(finishSelf: true),
      //     cancelPressed: () => exit(0));
    }
    // }
  }

  /// 检测是否有登录信息 并获取用户最新登录信息
  Future<bool> _checkLogin() async {
    O2Person? userJson = O2ApiManager.instance.loadUserFromSP();
    if (userJson == null) {
      return false;
    } else {
      try {
        O2Person? person = await OrgAuthenticationService.to.who();
        if (person == null || person.token == null || person.token!.isEmpty) {
          return false;
        } else {
          // 更新用户信息
          await O2ApiManager.instance.setupUser(person);
          return true;
        }
      } catch (err, stackTrace) {
        OLogger.e('检查用户登录情况失败', err, stackTrace);
        return false;
      }
    }
  }

  /// 去登录
  void _goToLogin() {
    if (EnvironmentConfig.o2AppIsDemo) {
      Get.offNamed(O2OARoutes.demoLogin);
    } else {
      Get.offNamed(O2OARoutes.login);
    }
  }

  /// 去主页
  void _gotoHome() {
    final openBioAuth = SharedPreferenceService.to
        .getBool(SharedPreferenceService.appBiometricAuthKey);
    final gesturePassword = SharedPreferenceService.to
        .getString(SharedPreferenceService.appGestureUnlockAuthKey);
    if (openBioAuth) {
      // 人脸或指纹认证
      Get.offNamed(O2OARoutes.homeSettingsAccountSafeBiometricAuth);
    } else if (gesturePassword.isNotEmpty) {
      GestureUnlockPage.openGestureUnlock();
    } else {
      Get.offNamed(O2OARoutes.home);
    }
  }

  final Completer<void> _promotionPageCompleter = Completer<void>();

  /// 检查是否要打开推广页
  Future<void> _checkAndShowPromotionPages() async {
    final script = ProgramCenterService.to.promotionPageScript();
    OLogger.d('脚本：$script');
    if (script.isNotEmpty) {
      Map<String, dynamic> body = <String, dynamic>{};
      final result =
          await ProgramCenterService.to.executeScript(script, body);
      final res = SplashPromotionPageScriptResponse.fromJson(result);
      if (res.images != null && res.images!.isNotEmpty) { // 有推广页
        final frequency = res.frequency ?? '';
        final lasShowDate = SharedPreferenceService.to.getString(SharedPreferenceService.promotionPageShowDateKey);
        final today = DateTime.now().ymd();
        bool isShowPromotionPage = false;
        if (frequency == SplashPromotionPageScriptResponse.always) {
          isShowPromotionPage = true;
        } else if (frequency == SplashPromotionPageScriptResponse.daily && lasShowDate != today) { // 今天没有展现过
          isShowPromotionPage = true;
        } else if (lasShowDate.isEmpty) { // 从来没有展现过
          isShowPromotionPage = true;
        }
        if (isShowPromotionPage) {
          state.promotionPageList.addAll(res.images!);
          SharedPreferenceService.to.putString(SharedPreferenceService.promotionPageShowDateKey, today);
          await _promotionPageCompleter.future; // 等待
        }
        OLogger.d('推广页 业务完成！');
      }
    }
  }

  /// 关闭推广页
  void closePromotionPage() {
    OLogger.d('关闭推广页');
    _promotionPageCompleter.complete();
  }

   Future<void> _rebind () async {
     await O2ApiManager.instance.cleanO2UnitAndSp();
    _splashLoading();
  }
}
