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

import '../../common/api/index.dart';
import '../../common/models/index.dart';
import '../../common/style/index.dart';
import '../../common/utils/log_util.dart';
import '../../common/widgets/index.dart';
import '../common/portal/index.dart';
import 'apps/index.dart';
import 'contact/index.dart';
import 'default_index/index.dart';
import 'im/index.dart';
import 'index.dart';
import 'settings/index.dart';

class HomePage extends GetView<HomeController> {
  const HomePage({Key? key}) : super(key: key);

  /// 底部 tabBar
  Widget _buildBottomNavigationBar() {
    return Obx(() => BottomNavigationBar(
          items: controller.state.homeTabList.map((element) {
            switch (element) {
              case AppIndexModule.im:
                return BottomNavigationBarItem(
                    icon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    activeIcon: O2UI.badgeView(controller.state.unReadNumber,
                        const Icon(O2IconFont.message)),
                    label: element.name());
              case AppIndexModule.contact:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.addressList),
                    activeIcon: const Icon(O2IconFont.addressList),
                    label: element.name());
              case AppIndexModule.home:
                return _indexBarItem();
              case AppIndexModule.app:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.apps),
                    activeIcon: const Icon(O2IconFont.apps),
                    label: element.name());
              case AppIndexModule.settings:
                return BottomNavigationBarItem(
                    icon: const Icon(O2IconFont.settings),
                    activeIcon: const Icon(O2IconFont.settings),
                    label: element.name());
            }
          }).toList(),
          currentIndex: controller.state.currentIndex,
          type: BottomNavigationBarType.fixed,
          onTap: (value) => controller.handleNavBarClick(value),
        ));
  }

  // 主视图
  Widget _buildView() {
    return Obx(() => controller.state.showBottomBar
        // ? controller.getViewByIndex(controller.state.currentIndex)
        ? _mainPageView()
        : const CircularProgressIndicator());
  }

  @override
  Widget build(BuildContext context) {
    OLogger.d("HomePage build");
    return GetBuilder<HomeController>(
      builder: (_) {
        return WillPopScope(
            onWillPop: controller.onWillPop,
            child: Obx(() => Scaffold(
                  backgroundColor: Theme.of(context).primaryColor,
                  body: SafeArea(
                    child: _buildView(),
                  ),
                  bottomNavigationBar: controller.state.showBottomBar
                      ? _buildBottomNavigationBar()
                      : Container(
                          color: Colors.white,
                          width: double.infinity),
                )));
      },
    );
  }

  /// 首页 底部  tab  按钮
  BottomNavigationBarItem _indexBarItem() {
    return BottomNavigationBarItem(
        icon: ProgramCenterService.to.homeBlurImageView(),
        activeIcon: ProgramCenterService.to.homeFocusImageView(),
        label: '');
  }

  /// PageView 主页
  Widget _mainPageView() {
    return Obx(() => PageView.builder(
        controller: controller.pageController,
        itemCount: controller.state.homeTabList.length,
        physics: const NeverScrollableScrollPhysics(),
        itemBuilder: (context, index) {
          final app = controller.state.homeTabList[index];
          switch (app) {
            case AppIndexModule.im:
              return KeepAliveWrapper(child: _imPageView());
            case AppIndexModule.contact:
              return KeepAliveWrapper(child: _contactPageView());
            case AppIndexModule.home:
              return KeepAliveWrapper(child: _defaultIndexPageView());
            case AppIndexModule.app:
              return KeepAliveWrapper(child: _appsPageView());
            case AppIndexModule.settings:
              return KeepAliveWrapper(child: _settingsPageView());
          }
        }));
  }

  /// 应用页面
  Widget _appsPageView() {
    final portal = ProgramCenterService.to.getExtendParamHomeTabPortal('appTabPortal');
    if (portal!= null && portal.portalId?.isNotEmpty == true ) { 
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_apps'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": hiddenAppBar,
                "title": appBarTitle,
                "pageId": pageId,
                "portalParameters": portalParameters
              }),
          tag: 'app_tag_$portalId');
      controller.portalCache[AppIndexModule.app] = portalId;
      return PortalPage(tag: 'app_tag_$portalId');
    } else {
      AppsBinding().dependencies();
      return const AppsPage();
    }
  }

  /// 通讯录页面
  Widget _contactPageView() {
    final portal = ProgramCenterService.to.getExtendParamHomeTabPortal('contactTabPortal');
    if (portal!= null && portal.portalId?.isNotEmpty == true ) { 
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_contact'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": hiddenAppBar,
                "title": appBarTitle,
                "pageId": pageId,
                "portalParameters": portalParameters
              }),
          tag: 'contact_tag_$portalId');
      controller.portalCache[AppIndexModule.contact] = portalId;
      return PortalPage(tag: 'contact_tag_$portalId');
    } else {
      ContactBinding().dependencies();
      return const ContactPage();
    }
  }

  /// 首页
  Widget _defaultIndexPageView() {
    final portal = ProgramCenterService.to.getExtendParamHomeTabPortal('indexTabPortal');
    if (portal!= null && portal.portalId?.isNotEmpty == true ) { 
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_index'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": hiddenAppBar,
                "title": appBarTitle,
                "pageId": pageId,
                "portalParameters": portalParameters
              }),
          tag: 'index_tag_$portalId');
      return PortalPage(tag: 'index_tag_$portalId');
    } else {
      var portalId = ProgramCenterService.to.homeIndexPage();
      if (portalId != null && portalId.isNotEmpty) {
        final extendParam = ProgramCenterService.to.extendParam();
        final indexPortalHiddenAppBar =
            extendParam['indexPortalHiddenAppBar'] ?? true;
        final indexPortalAppBarTitle =
            extendParam['indexPortalAppBarTitle'] ?? 'home_tab_index'.tr;
        Get.lazyPut<PortalController>(
            () => PortalController(initMap: {
                  "portalId": portalId,
                  "hiddenAppBar": indexPortalHiddenAppBar,
                  "title": indexPortalAppBarTitle
                }),
            tag: 'index_tag_$portalId');
        controller.portalCache[AppIndexModule.home] = portalId;
        return PortalPage(tag: 'index_tag_$portalId');
      } else {
        DefaultIndexBinding().dependencies();
        return const DefaultIndexPage();
      }
    }
  }

  /// 消息页面
  Widget _imPageView() {
    final portal = ProgramCenterService.to.getExtendParamHomeTabPortal('imTabPortal');
    if (portal!= null && portal.portalId?.isNotEmpty == true ) { 
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_im'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": hiddenAppBar,
                "title": appBarTitle,
                "pageId": pageId,
                "portalParameters": portalParameters
              }),
          tag: 'im_tag_$portalId');
      controller.portalCache[AppIndexModule.im] = portalId;
      return PortalPage(tag: 'im_tag_$portalId');
    } else {
      ImBinding().dependencies();
      return const ImPage();
    }
  }

  /// 设置页面
  Widget _settingsPageView() {
    final portal = ProgramCenterService.to.getExtendParamHomeTabPortal('settingsTabPortal');
    if (portal!= null && portal.portalId?.isNotEmpty == true ) { 
      final portalId = portal.portalId!;
      final hiddenAppBar = portal.hiddenAppBar ?? false;
      final appBarTitle = portal.appBarTitle ?? 'home_tab_settings'.tr;
      final pageId = portal.pageId;
      final portalParameters = portal.portalParameters;
      Get.lazyPut<PortalController>(
          () => PortalController(initMap: {
                "portalId": portalId,
                "hiddenAppBar": hiddenAppBar,
                "title": appBarTitle,
                "pageId": pageId,
                "portalParameters": portalParameters
              }),
          tag: 'settings_tag_$portalId');
      controller.portalCache[AppIndexModule.settings] = portalId;
      return PortalPage(tag: 'settings_tag_$portalId');
    } else {
      SettingsBinding().dependencies();
      return const SettingsPage();
    }
  }
}
