import 'package:fis_common/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/login.m.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/base_define/page.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/values/font_sizes.dart';
import 'package:fis_ui/values/spacings.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/states/states.dart';
import 'package:flyinsono/architecture/utils/web.dart';
import 'package:flyinsono/global.dart';
import 'package:flyinsono/managers/interfaces/network_error_handler.dart';
import 'package:flyinsono/pages/others/title_bar_buttons.dart';
import 'package:flyinsono/pages/schedule/schedule_notification/global_notification_layer.dart';
import 'package:flyinsono/views/desktop/notification_list/index.dart';
import 'package:get/get.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'index.dart';
import 'widgets/index.dart';

class HomePage extends FStatelessWidget implements FPage {
  const HomePage({this.pageName = 'HomePage', Key? key}) : super(key: key);
  @override
  final String pageName;

  @override
  FWidget build(BuildContext context) {
    return kIsMobile ? _MobileLayout() : _DesktopLayout(this);
  }
}

///主页界面
class _DesktopLayout extends FStatefulWidget {
  _DesktopLayout(this.businessParent);

  final FPage businessParent;

  @override
  FState<FStatefulWidget> createState() {
    return _DesktopLayoutState();
  }
}

class _DesktopLayoutState extends FState<_DesktopLayout> {
  final _navController = Get.find<HomeNavigatorController>();
  final _colorScheme = FTheme.ins.colorScheme;
  final controller = Get.find<HomeController>();
  var networkErrorHandlerManager = Get.find<INetworkErrorHandlerManager>();
  bool _isNetworkAbnormal = false;
  double headHeight = 68;
  double leftWidth = 90;

  @override
  void initState() {
    Store.user.onAssociatedFeatureChange
        .addListener(_onAssociatedFeatureChange);
    networkErrorHandlerManager.onNetworkInterruption
        .addListener(_onNetworkInterruption);
    GlobalFullScreenEvent.stream.listen((value) {
      if (value) {
        setState(() {
          headHeight = 0;
          leftWidth = 0;
        });
      } else {
        setState(() {
          headHeight = 68;
          leftWidth = 90;
        });
      }
    });
    super.initState();
  }

  @override
  void dispose() {
    Store.user.onAssociatedFeatureChange
        .removeListener(_onAssociatedFeatureChange);
    networkErrorHandlerManager.onNetworkInterruption
        .removeListener(_onNetworkInterruption);
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    AppWebUtils.setTitle("homePage");
    var page = FFlex(
      direction: Axis.vertical,
      children: [
        FFlexible(
          child: _builderHeader(context),
          flex: 0,
        ),
        FContainer(
          height:
              MediaQuery.of(context).size.height - (kIsMobile ? 0 : headHeight),
          child: FFlex(
            direction: Axis.horizontal,
            children: [
              if (!kIsMobile)
                FFlexible(
                  child: _buildNav(),
                  flex: 0,
                ),
              FFlexible(
                child: _buildBody(kIsMobile),
                flex: 1,
              ),
            ],
          ),
        ),
      ],
    );

    return FScaffold(
      appBar: kIsMobile
          ? FAppBar(
              backgroundColor: _colorScheme.header,
              actions: [
                _builderHeader(
                  context,
                ),
              ],
            )
          : null,
      body: FGlobalNotificationLayer(child: page),
    );
  }

  FWidget _buildBody(bool isMobile) {
    final EdgeInsetsGeometry padding = EdgeInsets.zero;
    return FContainer(
      padding: padding,
      child: _HomeNavigator(),
    );
  }

  FWidget _builderHeader(BuildContext context) {
    FWidget child = FRow(
      children: [
        FContainer(
          height: headHeight,
          decoration: new BoxDecoration(
            border: new Border.all(
              width: 1,
              color: _colorScheme.header,
            ),
          ),
          width: MediaQuery.of(context).size.width,
        ),
      ],
    );

    ///Todo:finlay  推车不支持拖动窗口
    if (!CartSystemPlatform.isCartSystemVersion) {
      child = FGestureDetector(
        businessParent: widget.businessParent,
        name: "TitleBar",
        onPanStart: (event) {
          controller.onStartDrag();
        },
        onPanEnd: (e) {
          controller.onEndDrag();
        },
        onDoubleTap: () {
          controller.onMaximize();
        },
        onPanCancel: () {
          controller.onEndDrag();
        },
        child: child,
      );
    }
    return FContainer(
      height: headHeight,
      color: _colorScheme.header,
      child: FStack(
        children: [
          FObx(() {
            controller.state.currentRouter;
            if (FPlatform.isWindows) {
              return child;
            } else {
              return FSizedBox();
            }
          }),
          _buildHeaderLeft(),
          FContainer(
            margin: EdgeInsets.all(10),
            child: FRow(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                _isNetworkAbnormal
                    ? _buildTopRightNetworkErrorTip()
                    : FSizedBox(),
              ],
            ),
          ),
          FObx(() {
            controller.state.currentRouter;

            ///Todo:finlay  推车不显示最大化、最小化以及关闭按钮
            if (FPlatform.isWindows &&
                !CartSystemPlatform.isCartSystemVersion) {
              return _buildWindowOperateButtons();
            } else {
              if (!Get.isRegistered<NotificationListController>()) {
                Get.put(NotificationListController());
              }
              return _buildTopRightNotificationButton();
            }
          }),
        ],
      ),
    );
  }

  FWidget _buildTopRightNetworkErrorTip() {
    return FContainer(
      decoration: BoxDecoration(
        color: FTheme.ins.colorScheme.secondary.withOpacity(0.5),
        borderRadius: BorderRadius.all(
          Radius.circular(4),
        ),
      ),
      padding: EdgeInsets.only(left: 15, right: 16, top: 10, bottom: 10),
      child: FRow(
        children: [
          FIcon(
            Icons.wifi_off,
            color: Colors.red,
          ),
          FSizedBox(
            width: 10,
          ),
          FText(
            i18nBook.remoteControl.networkConnectionError.t,
            style: TextStyle(
              fontSize: 18,
              // fontWeight: FontWeight.bold,
              color: Colors.red,
            ),
          ),
        ],
      ),
    );
  }

  FWidget _buildTopRightNotificationButton() {
    return FPositioned(
      top: 10,
      right: 20,
      child: FRow(
        children: [
          NotificationListButton(),
        ],
      ),
    );
  }

  FWidget _buildHeaderLeft() {
    return FContainer(
      child: FRow(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          HomeUserAvatarEnterance(),
          _buildAavtarRightBlock(),
        ],
      ),
    );
  }

  FWidget _buildAavtarRightBlock() {
    return FContainer(
      margin: EdgeInsets.only(left: 8),
      child: FRow(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          _buildNickNameText(),
          const FSizedBox(width: 8),
          _buildCrumbs(),
        ],
      ),
    );
  }

  FWidget _buildCrumbs() {
    return FObx(() {
      if (_navController.routeDepth > 0) {
        return FHeaderCrumbs(businessParent: widget.businessParent);
      } else {
        return const FSizedBox();
      }
    });
  }

  FWidget _buildNickNameText() {
    const _maxWidth = 140.0; //限制最大宽度
    return FObx(() {
      final nickName = Store.user.displayName;
      return FContainer(
        constraints: BoxConstraints(maxWidth: _maxWidth),
        child: FText(
          nickName,
          style: TextStyle(
            fontSize: FFontSizes.H6,
            color: Colors.white,
            height: 1,
          ),
          overflow: TextOverflow.ellipsis,
        ),
      );
    });
  }

  FWidget _buildNav() {
    return FContainer(
      width: leftWidth,
      color: _colorScheme.nav,
      padding: EdgeInsets.symmetric(
          vertical: Global.isRemoveLogo ? 0 : FSpacings.XXL),
      child: FColumn(
        children: [
          if (!Global.isRemoveLogo) const _NavLogo(),
          const FSizedBox(height: FSpacings.XL),
          FExpanded(child: FObx(() {
            return FSideNavMenuBar(
              routes: _buildMenuList(_navController.navNames),
              onActiveMenuChanged: (context, index) {
                Get.find<HomeNavigatorController>().changePage(index);
              },
            );
          })),
        ],
      ),
    );
  }

  List<FSideNavMenuItemRoute> _buildMenuList(List<String> navNames) {
    List<FSideNavMenuItemRoute> items = [];
    var otherNavNames = Store.user.associatedFeatures
        .where((element) => element.associatedPosition == MAINMENU)
        .toList()
        .map((e) => e.title)
        .toList();

    /// 遍历 navNames ，使用switch case 生成对应的 FSideNavMenuItemRoute
    for (String navName in navNames) {
      switch (navName) {
        case '/home/home_page':
          items.add(
            FSideNavMenuItemRoute(
              Icons.home_outlined,
              i18nBook.homePage.homePage.t,
            ),
          );
          break;
        case '/remedical':
          items.add(
            FSideNavMenuItemRoute(
              Icons.assignment,
              i18nBook.remedical.patientManagement.t,
            ),
          );
          break;
        case "/remedical/records_view":
          items.add(
            FSideNavMenuItemRoute(
              FIcons.diagnostics,
              i18nBook.homePage.remoteDiagnosis.t,
            ),
          );
          break;
        case '/realTimeRemedical/realTimeConsultation':
          items.add(
            FSideNavMenuItemRoute(
              FIcons.live_consultation,
              i18nBook.realTimeConsultation.realTimeDiagnosis.t,
            ),
          );
          break;
        case "/realTimeRemedical/calendar_page":
          items.add(
            FSideNavMenuItemRoute(
                Icons.calendar_month, i18nBook.calendar.calendarView.t),
          );
          break;
        case "/live/device_list":
          items.add(
            FSideNavMenuItemRoute(
                Icons.cast_connected, i18nBook.live.deviceLive.t),
          );
          break;
        case '/flyinsono_college':
          items.add(
            FSideNavMenuItemRoute(
              Icons.school,
              i18nBook.common.flyinsonoCollege.t,
            ),
          );
          break;
        default:
          // items.add(
          //   FSideNavMenuItemRoute(
          //     Icons.question_mark_rounded,
          //     i18nBook.notification.unknownType.t,
          //   ),
          // );
          break;
      }
    }
    for (var name in navNames) {
      if (otherNavNames.contains(name)) {
        var info = Store.user.associatedFeatures
            .firstWhere((element) => element.title == name);
        if (info.associatedPosition == MAINMENU) {
          items.add(
            FSideNavMenuItemRoute(
              Icons.feedback,
              i18nBook.isCurrentChinese ? info.cTitle ?? '' : info.eTitle ?? '',
              info.icon,
            ),
          );
        }
      }
    }
    return items;
  }

  ///最大化、最小化、关闭按钮
  FWidget _buildWindowOperateButtons() {
    return TitleBarButtons(
      controller.onMinimize,
      controller.onWindowClose,
      controller.onMaximize,
      Colors.white,
      FTheme.ins.colorScheme.header,
    );
  }

  void _onAssociatedFeatureChange(
      Object sender, List<AssociatedFeatureInfoDTO> e) {
    setState(() {});
  }

  void _onNetworkInterruption(Object sender, bool e) {
    setState(() {
      print('网络状态是否中断：_isNetworkAbnormal');
      _isNetworkAbnormal = e;
    });
  }
}

///导航logo
class _NavLogo extends StatelessWidget implements FWidget {
  const _NavLogo();

  /// 区域高度
  // ignore: unused_field
  static const double C_HEIGHT = 60.0;
  @override
  FWidget build(BuildContext context) {
    return FContainer(
      height: C_HEIGHT,
      padding: const EdgeInsets.symmetric(
        horizontal: 5,
      ),
      // 俄语定制主题
      child: FImage.asset(
        i18nBook.isCurrentRussian
            ? "assets/images/logo_ru_white_vertical.png"
            : "assets/images/logo_en_white_vertical.png",
        filterQuality: FilterQuality.medium,
        isAntiAlias: true,
        fit: BoxFit.contain,
      ),
    );
  }
}

///主页导航
class _HomeNavigator extends FisView<HomeNavigatorController>
    implements FWidget {
  @override
  FWidget build(BuildContext context) {
    final navNative = FNavigator(
      key: Get.nestedKey(
        NavIds.HOME,
      ),
      initialRoute: RouteNames.Home.MainPage,
      onGenerateRoute: controller.onGenerateRoute,
    );
    return navNative;
  }
}

///手机端布局
class _MobileLayout extends FStatefulWidget {
  @override
  FState<_MobileLayout> createState() => _MobileLayoutState();
}

class _MobileLayoutState extends FState<_MobileLayout> {
  final _navController = Get.find<HomeMobileNavController>();

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

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

  @override
  FWidget build(BuildContext context) {
    return FScaffold(
      body: FNavigator(
        key: Get.nestedKey(
          NavIds.HOME,
        ),
        initialRoute: RouteNames.Home.MainPage,
        onGenerateRoute: _navController.onGenerateRoute,
      ),
      bottomNavigationBar: _buildBottomBar(),
    );
  }

  FWidget _buildBottomBar() {
    final navBar = FBottomNavigationBar(
        currentIndex: _navController.currentIndex,
        elevation: 0,
        backgroundColor: Colors.white,
        showSelectedLabels: true,
        showUnselectedLabels: true,
        type: BottomNavigationBarType.fixed,
        onTap: (index) {
          _navController.changePage(index);
          setState(() {});
        },
        items: _buildNavigationItemsByNavNames(_navController.navNames));

    return navBar;
  }

  FWidget _buildThirdpartyIcon(String iconUrl) {
    final iconWidth = 24.0;
    final iconHeight = 24.0;
    FWidget thirdpartyIcon = FIcon(Icons.feedback);
    if (Store.user.associatedFeatures.isNotEmpty) {
      if (iconUrl.isNotNullOrEmpty) {
        if (iconUrl.endsWith('.jpg')) {
          thirdpartyIcon = QuickFWidget(
            ColorFiltered(
              colorFilter: ColorFilter.mode(Colors.black54, BlendMode.srcIn),
              child: Image.network(
                iconUrl,
                height: iconHeight,
                width: iconWidth,
              ),
            ),
          );
        } else if (iconUrl.endsWith('.svg')) {
          thirdpartyIcon = QuickFWidget(
            SvgPicture.network(
              iconUrl,
              color: Colors.black54, // 设置颜色
              width: iconWidth,
              height: iconHeight,
            ),
          );
        } else {
          thirdpartyIcon = FImage.network(
            iconUrl,
            height: iconHeight,
          );
        }
      }
    }
    return thirdpartyIcon;
  }

  FWidget _buildThirdpartyActiveIcon(String iconUrl) {
    final iconWidth = 24.0;
    final iconHeight = 24.0;
    FWidget thirdpartyActiveIcon = FIcon(Icons.feedback);
    if (Store.user.associatedFeatures.isNotEmpty) {
      if (iconUrl.isNotNullOrEmpty) {
        if (iconUrl.endsWith('.jpg')) {
          thirdpartyActiveIcon = QuickFWidget(
            ColorFiltered(
              colorFilter: ColorFilter.mode(
                  FTheme.ins.colorScheme.primary, BlendMode.srcIn),
              child: Image.network(
                iconUrl,
                height: iconHeight,
                width: iconWidth,
              ),
            ),
          );
        } else if (iconUrl.endsWith('.svg')) {
          thirdpartyActiveIcon = QuickFWidget(
            SvgPicture.network(
              iconUrl,
              color: FTheme.ins.colorScheme.primary, // 设置颜色
              width: iconWidth,
              height: iconHeight,
            ),
          );
        } else {
          thirdpartyActiveIcon = FImage.network(
            iconUrl,
            height: iconHeight,
          );
        }
      }
    }
    return thirdpartyActiveIcon;
  }

  List<FBottomNavigationBarItem> _buildNavigationItemsByNavNames(
      List<String> navNames) {
    List<FBottomNavigationBarItem> items = [];
    var otherNavNames = Store.user.associatedFeatures
        .where((element) => element.associatedPosition == MAINMENU)
        .toList()
        .map((e) => e.title)
        .toList();

    /// 遍历 navNames ，使用switch case 生成对应的 FBottomNavigationBarItem
    for (String navName in navNames) {
      switch (navName) {
        case '/home/home_page':
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                Icons.home_outlined,
              ),
              label: i18nBook.homePage.homePage.t,
            ),
          );
          break;
        case '/realTimeRemedical/MobileConsultation':
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                FIcons.live_consultation,
              ),
              label: i18nBook.realTimeConsultation.realTimeDiagnosis.t,
            ),
          );
          break;
        case "/remedical":
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                Icons.assignment,
              ),
              label: i18nBook.remedical.patientManagement.t,
            ),
          );
          break;
        case '/user/center':
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                FIcons.my,
              ),
              label: i18nBook.homePage.my.t,
            ),
          );
          break;
        case "/remedical/records_view":
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                FIcons.diagnostics,
              ),
              label: i18nBook.homePage.remoteDiagnosis.t,
            ),
          );
          break;
        case "/flyinsono_college":
          items.add(
            FBottomNavigationBarItem(
              icon: FIcon(
                Icons.school_outlined,
              ),
              label: i18nBook.common.college.t,
            ),
          );
          break;
        default:
          if (otherNavNames.contains(navName)) {
            var info = Store.user.associatedFeatures
                .firstWhere((element) => element.title == navName);

            items.add(
              FBottomNavigationBarItem(
                label: i18nBook.isCurrentChinese
                    ? info.cTitle ?? ''
                    : info.eTitle ?? '',
                activeIcon: _buildThirdpartyActiveIcon(info.icon ?? ''),
                icon: _buildThirdpartyIcon(info.icon ?? ''),
              ),
            );
          }
          break;
      }
    }

    return items;
  }

  void _onAssociatedFeatureChange(
      Object sender, List<AssociatedFeatureInfoDTO> e) {
    setState(() {});
  }
}
