import 'dart:async';

import 'package:fis_common/env/env.dart';
import 'package:fis_common/js_plateform/js_platform.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_lib_report/converts/event_type.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/desktop/routes.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/modules/area_region.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/window_state.dart';
import 'package:flyinsono/architecture/values/features.dart';
import 'package:flyinsono/managers/interfaces/network_error_handler.dart';
import 'package:flyinsono/managers/interfaces/user_info.dart';
import 'package:flyinsono/managers/interfaces/webview_controller.dart';
import 'package:flyinsono/pages/main/home/widgets/dialog_page.dart';
import 'package:flyinsono/pages/main/profile_complete/bindings.dart';
import 'package:flyinsono/pages/main/profile_complete/view.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'index.dart';

///主页页面控制器
class HomeController extends FControllerBase {
  HomeController();

  static const String _windowName = "Main";

  /// 响应式成员变量

  final state = HomeState();

  /// 成员变量

  /// 事件

  ///是否已有完善信息弹窗
  bool _isopenProfileCompletePage = false;
  var networkErrorHandlerManager = Get.find<INetworkErrorHandlerManager>();

  void switchThemeMode() {
    var mode = state.isDarkMode ? ThemeMode.light : ThemeMode.dark;
    FTheme.ins.switchThemeMode(mode);
    state.isDarkMode = !state.isDarkMode;
  }

  /// 生命周期
  @override
  void onInit() {
    super.onInit();
    _initWindowState();
    state.isDarkMode = FTheme.ins.isDarkMode;
    HomeTaskSchedule().run();
    //Future.delayed(Duration(milliseconds: 1000), checkProfileComplete);
    networkErrorHandlerManager.onNetworkInterruption
        .addListener(_onNetworkInterruption);
  }

  @override
  void dispose() {
    networkErrorHandlerManager.onNetworkInterruption
        .removeListener(_onNetworkInterruption);
    super.dispose();
  }

  /// 检查用户信息是否完善
  void checkProfileComplete(
      [VoidCallback? callback, bool isRealName = false]) async {
    final ifNeedCompleteProfile = await _ifNeedCompleteProfile(isRealName);
    state.isNoRealName = ifNeedCompleteProfile;
    if (ifNeedCompleteProfile) {
      if (kIsMobile) {
        await router.to(RouteNames.Home.Profile);
      } else {
        final webViewManager = Get.find<IWebviewControllerManager>();
        if (webViewManager.webViewXController != null) {
          _openProfileCompletePage();
        } else {
          webViewManager.onInit.addListener((sender, e) {
            if (!_isopenProfileCompletePage) {
              _openProfileCompletePage();
            }
          });
        }
      }
    } else {
      callback?.call();
    }
  }

  ///开启拖拽
  Future<void> onStartDrag() async {
    JSPlateForm.beginWindowDrag(_windowName);
  }

  ///结束拖拽
  Future<void> onEndDrag() async {
    JSPlateForm.endWindowDrag(_windowName);
  }

  ///最小化
  Future<void> onMinimize() async {
    JSPlateForm.minimizeWindow(_windowName);
  }

  ///最大化
  Future<void> onMaximize() async {
    JSPlateForm.maximizeWindow(_windowName);
  }

  ///关闭
  Future<void> onWindowClose() async {
    JSPlateForm.closeWindow(_windowName);
  }

  ///双击最大化或还原
  Future<void> onDoubleTap() async {
    await rpc.platform.maximizeWindow(_windowName);
  }

  ///窗口改变事件
  void onWindowStateChange(WindowState? windowState) {
    if (windowState != null) {
      switch (windowState) {
        case WindowState.Normal:
          state.isMaximized = false;
          break;
        case WindowState.Minimized:
          break;
        case WindowState.Maximized:
          state.isMaximized = true;
          break;
        case WindowState.FullScreen:
          break;
      }
    }
  }

  void _onNetworkInterruption(sender, e) {
    state.isNetworkAbnormal = e;
  }

  Future<bool> _ifNeedCompleteProfile([bool isRealName = false]) async {
    try {
      final userInfo = await rpc.user.getUserInfoAsync(
        GetUserInfoRequest(token: Store.user.token),
      );
      Store.user.handleUserSyncUpdate(userInfo);
      if (isRealName) {
        if (userInfo.departmentCode?.isNotEmpty ?? false) {
          return false;
        }
      }
      if (userInfo.departmentCode == '' || userInfo.departmentCode == '0') {
        return true;
      }
    } catch (e) {
      logger.e("[SignIn] check is first login error", e);
    }
    return false;
  }

  Future<void> _initWindowState() async {
    if (FPlatform.isWindows) {
      var windowState = await rpc.platform.getWindowState(_windowName);
      if (windowState == WindowState.Maximized.index) {
        state.isMaximized = true;
      }
    }
  }

  Future<void> _openProfileCompletePage() async {
    _isopenProfileCompletePage = true;
    Get.find<FWebviewInteractiveController>().onDialogCreate();
    final result = await router.dialog(
      () => ProfileCompletePage(),
      binding: ProfileCompleteBinding(),
      transitionDuration: Duration(milliseconds: 500),
      transitionCurve: Curves.easeInCirc,
    );
    if (result is bool) {
      state.isNoRealName = false;
      var manager = Get.find<IUserInfoManager>();
      final result = await manager.getUserInfoAsync();
      print('Complete result: $result');
    }
    Get.find<FWebviewInteractiveController>().onDialogDispose();
  }
}

///主页导航控制器
class HomeNavigatorController extends GetxController {
  bool _isReady = false;
  final _currentIndex = FRx<int>(0);
  final _routeStack = FRxList<String>();

  /// 响应式成员变量

  final state = HomeState();

  /// 当前路由下标
  int get currentIndex => _currentIndex.value;

  /// 当前路由是否二级路由
  bool get isCurrSubRoute => _routeStack.length > 1;

  /// 路由深度
  int get routeDepth => _routeStack.length;

  /// 路由栈
  List<String> get routeStack => _routeStack.toList();

  bool get hasAssociatedFeature => Store.user.associatedFeatures
      .any((element) => element.associatedPosition == MAINMENU);

  ///顶级路由中的第三方平台入口
  List<AssociatedFeatureInfoDTO> get thirdpartyPageInfos =>
      Store.user.associatedFeatures
          .where((element) => element.associatedPosition == MAINMENU)
          .toList();

  /// 顶级路由中的第三方平台入口路由名称
  List<String> get otherThirdPartyNavNames =>
      thirdpartyPageInfos.map((e) => e.title ?? '').toList();

  /// 路由切换事件
  FEventHandler<void> onRouterToPersonCenter = FEventHandler<void>();

  /// 导航路由名
  late List<String> _navNames = [
    RouteNames.Home.MainPage,
    if (state.hasPatientListsAuth) RouteNames.Remedical.ConsultationRecordView,
    if (state.hasConsultationAuth)
      RouteNames.RealTimeRemedical.RealTimeConsultation,
    if (state.hasConsultationAuth) RouteNames.RealTimeRemedical.CalendarPage,
    RouteNames.Live.DeviceList,
    if (state.hasCollegeAuth) RouteNames.College.FlyinsonoCollege,
    if (hasAssociatedFeature) ...otherThirdPartyNavNames,
  ];

  List<String> get navNames => _navNames;

  /// 其他不在导航栏里的导航路由名
  List<String> get _otherNavNames => <String>[
        RouteNames.User.Center,
        RouteNames.Thirdparty.ThirdpartyPage,
      ];

  /// 一级路由名
  late final _topRouteNames = <String>[
    ..._navNames,
    ..._otherNavNames,
  ];

  /// 已注册的路由名字
  late final _registeredNames = [
    ..._topRouteNames,
    RouteNames.User.Profile,
    RouteNames.User.RoleAuth,
    RouteNames.User.Setting,
    RouteNames.User.Device,
    RouteNames.User.GroupList,
    RouteNames.User.Entry,
    RouteNames.User.ReportTemplate,
    RouteNames.User.ReportTemplate,
    RouteNames.User.ReportTemplateDesigner,
    RouteNames.Org.Info,
    RouteNames.Org.Personnel,
    RouteNames.Org.Device,
    RouteNames.Org.Entry,
    RouteNames.Org.ReportTemplate,
    RouteNames.Remedical.ImagePool,
    RouteNames.Remedical.Measure,
    RouteNames.Remedical.ReportEdit,
    RouteNames.Remedical.ReportPreview,
    RouteNames.Remedical.Consultation,
    RouteNames.Remedical.ConsultationRecordView,
    RouteNames.Remedical.ConsultationPatientView,
    RouteNames.RealTimeRemedical.RealTimeConsultation,
    RouteNames.RealTimeRemedical.LiveConsultation,
    RouteNames.Live.DeviceList,
    RouteNames.Live.DeviceDetail,
    RouteNames.Live.RemoteController,
    RouteNames.Laboratory.AiLaboratoryFolder,
    RouteNames.Laboratory.LaboratoryReportFolder,
    RouteNames.College.LiveCourseDetail,
    RouteNames.College.ExamPage,
    RouteNames.College.PastVideos,
    RouteNames.College.PastVideoPlayer,
  ];

  ///修改当前页面
  ///
  ///[index] 改变路由下标，切换路由
  void changePage(int index) {
    print('changePage $index');
    try {
      if (index == currentIndex) {
        return;
      }
      _currentIndex.value = index;
      if (index == -1) {
        return;
      }
      updateMobileHomePageNavNames();
      // 检查更新后的路由表，修正下标
      if (index >= _navNames.length) {
        index = _navNames.length - 1;
      }
      var routerName = _navNames[index];
      logger.i("changePage to $routerName");
      Map<String, String> parameters = {};

      ///第三方平台地址参数传入
      if (otherThirdPartyNavNames.contains(routerName)) {
        var thirdpartyPageInfo = thirdpartyPageInfos
            .firstWhereOrNull((element) => element.title == routerName);
        routerName = RouteNames.Thirdparty.ThirdpartyPage;
        parameters = {
          "source": MAINMENU,
          "url": thirdpartyPageInfo?.url ?? '',
          "name": i18nBook.isCurrentChinese
              ? thirdpartyPageInfo?.cTitle ?? ''
              : thirdpartyPageInfo?.eTitle ?? '',
        };
      }
      router.replace(routerName, id: NavIds.HOME, parameters: parameters);
    } catch (e) {
      logger.e('HomeController changePage ex:', e);
      print(e);
    }
  }

  /// 根据当前状态生成路由
  void updateMobileHomePageNavNames() {
    _navNames = [
      RouteNames.Home.MainPage,
      if (state.hasPatientListsAuth)
        RouteNames.Remedical.ConsultationRecordView,
      if (state.hasConsultationAuth)
        RouteNames.RealTimeRemedical.RealTimeConsultation,
      if (state.hasConsultationAuth) RouteNames.RealTimeRemedical.CalendarPage,
      RouteNames.Live.DeviceList,
      if (state.hasCollegeAuth) RouteNames.College.FlyinsonoCollege,
      if (hasAssociatedFeature) ...otherThirdPartyNavNames,
    ];
  }

  /// 路由生成器
  Route? onGenerateRoute(RouteSettings settings) {
    final route = router.onGenerateRoute(
      settings,
      registeredNames: _registeredNames,
      id: NavIds.HOME,
    );
    bool isSubRoute = false;
    final name = settings.name ?? '';
    if (route != null) {
      isSubRoute = _checkIsSubRoute(name);
    }
    _updateSubRouteRecords(isSubRoute, name);
    return route;
  }

  /// 二级路由回退
  void subBack() {
    _routeStack.removeLast();
  }

  /// 回到指定路由
  ///
  /// [routeName] 路由
  ///
  /// [isResetStack] 重置路由栈
  void backTo(String routeName, [bool isResetStack = false]) {
    if (_routeStack.isNotEmpty && routeName == _routeStack.last) {
      // 当前路由，无需处理
      return;
    }

    Get.nestedKey(NavIds.HOME)!
        .currentState!
        .popUntil((route) => route.settings.name == routeName);

    if (isResetStack) {
      _routeStack.clear();
      _routeStack.add(routeName);
    } else {
      final len = _routeStack.length;
      for (var i = len - 1; i > 0; i--) {
        final name = _routeStack[i];
        if (name == routeName) {
          break;
        } else {
          _routeStack.removeLast();
        }
      }
    }
  }

  bool _checkIsSubRoute(String name) {
    if (name == RouteNames.Thirdparty.ThirdpartyPage) {
      final args = router.getParams(NavIds.HOME) ?? {};
      if (args.containsKey('source')) {
        if (args['source'] == PERSONCENTER) {
          return true;
        }
      }
    }
    if (!_topRouteNames.contains(name)) {
      final depth = name.length - name.replaceAll('/', '').length;
      if (depth > 1 && _registeredNames.contains(name)) {
        return true;
      }
    }
    return false;
  }

  void _updateSubRouteRecords(bool isSub, String name) {
    if (!_isReady) return;

    if (!isSub) {
      _routeStack.clear();
    }
    _routeStack.add(name);
  }

  @override
  void onReady() {
    Store.user.onAssociatedFeatureChange
        .addListener(_onAssociatedFeatureChange);
    _handleReady();
    super.onReady();
  }

  @override
  void dispose() {
    Store.user.onAssociatedFeatureChange
        .removeListener(_onAssociatedFeatureChange);

    super.dispose();
  }

  void _onAssociatedFeatureChange(
      Object sender, List<AssociatedFeatureInfoDTO> e) {
    if (e.isEmpty) {
      return;
    }
    updateMobileHomePageNavNames();
  }

  void _handleReady() {
    _isReady = true;
    _routeStack.add(_navNames[_currentIndex.value]);
  }
}

///主页计划面板控制器
class HomeTaskSchedule extends FControllerBase {
  static bool hasRun = false;
  static bool running = false;

  final _frontTasks = <Future Function()>[
    () async {
      final service = Get.find<AreaRegionService>();
      await service.init();
      await service.checkUpdate();
    },
  ];
  final _backgroundTasks = <void Function()>[];

  ///运行计划任务
  Future<void> run() async {
    if (hasRun || running) return;
    running = true;

    _backgroundTasks.forEach((fn) {
      fn();
    });

    await busyHandle(
      () async {
        final futures = _frontTasks.map(
          (fn) => fn(),
        );
        await Future.wait(futures);
      },
    );

    running = false;
    hasRun = true;
  }
}

/// 手机端导航路由控制器
class HomeMobileNavController extends GetxController {
  var _currentIndex = 0.obs;

  /// 当前路由下标
  int get currentIndex => _currentIndex.value;

  /// 是否是首页
  bool get isHomePage => currentIndex == 0;

  bool get hasPatientLists => Store.user.hasFeature(FeatureKeys.PatientLists);

  bool get hasConsultation => Store.user.hasFeature(FeatureKeys.Consultation);

  bool get hasAssociatedFeature => Store.user.associatedFeatures
      .any((element) => element.associatedPosition == MAINMENU);

  ///顶级路由中的第三方平台入口
  List<AssociatedFeatureInfoDTO> get thirdpartyPageInfos =>
      Store.user.associatedFeatures
          .where((element) => element.associatedPosition == MAINMENU)
          .toList();

  /// 顶级路由中的第三方平台入口路由名称
  List<String> get otherThirdPartyNavNames =>
      thirdpartyPageInfos.map((e) => e.title ?? '').toList();

  /// 手机端路由
  late var _navNames = [
    RouteNames.Home.MainPage,
    if (hasAssociatedFeature) ...otherThirdPartyNavNames,
    if (hasConsultation) RouteNames.RealTimeRemedical.MobileConsultation,
    // if (kDebugMode) RouteNames.Remedical.Consultation,
    if (hasPatientLists) RouteNames.Remedical.ConsultationRecordView,
    // if (Store.user.hasFeature(FeatureKeys.FlyinsonoCollege))
    //   RouteNames.College.FlyinsonoCollege,
    RouteNames.User.Center,
  ];

  List<String> get navNames => _navNames;

  @override
  void onInit() {
    Store.user.onAssociatedFeatureChange
        .addListener(_onAssociatedFeatureChange);
    super.onInit();
  }

  @override
  void dispose() {
    Store.user.onAssociatedFeatureChange
        .removeListener(_onAssociatedFeatureChange);

    super.dispose();
  }

  /// 切换路由方法
  void changePage(int index) {
    if (index == currentIndex) return;
    updateMobileHomePageNavNames();
    // 检查更新后的路由表，修正下标
    if (index >= _navNames.length) {
      index = _navNames.length - 1;
    }
    routerChange(index);
  }

  /// 根据当前状态生成路由
  void updateMobileHomePageNavNames() {
    _navNames = [
      RouteNames.Home.MainPage,
      if (hasAssociatedFeature) ...otherThirdPartyNavNames,
      if (hasConsultation) RouteNames.RealTimeRemedical.MobileConsultation,
      // if (kDebugMode) RouteNames.Remedical.Consultation,
      if (hasPatientLists) RouteNames.Remedical.ConsultationRecordView,
      // if (Store.user.hasFeature(FeatureKeys.FlyinsonoCollege))
      //   RouteNames.College.FlyinsonoCollege,
      RouteNames.User.Center,
    ];
  }

  void routerChange(int index) {
    _currentIndex.value = index;
    var routerName = navNames[index];
    Map<String, String> parameters = {};
    if (otherThirdPartyNavNames.contains(routerName)) {
      var thirdpartyPageInfo = thirdpartyPageInfos
          .firstWhereOrNull((element) => element.title == routerName);
      routerName = RouteNames.Thirdparty.ThirdpartyPage;
      parameters = {
        "source": MAINMENU,
        "url": thirdpartyPageInfo?.url ?? '',
        "name": i18nBook.isCurrentChinese
            ? thirdpartyPageInfo?.cTitle ?? ''
            : thirdpartyPageInfo?.eTitle ?? '',
      };
    }
    router.replace(routerName, id: NavIds.HOME, parameters: parameters);
  }

  /// 路由生成器
  Route? onGenerateRoute(RouteSettings settings) {
    return router.onGenerateRoute(
      settings,
      registeredNames: [...navNames, RouteNames.Thirdparty.ThirdpartyPage],
      id: NavIds.HOME,
    );
  }

  void _onAssociatedFeatureChange(
      Object sender, List<AssociatedFeatureInfoDTO> e) {
    if (e.isEmpty) {
      return;
    }
    updateMobileHomePageNavNames();
  }
}
