/// 布局模板
library;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/tab_bar_controller.dart';
import 'package:loopin/models/tab_type.dart';
import 'package:loopin/pages/video/module/attention.dart';
import 'package:loopin/pages/video/module/friend.dart';
import 'package:loopin/pages/video/module/recommend.dart';
import 'package:loopin/update/upgrade_service.dart';
import 'package:loopin/utils/common.dart';

import '../components/keepalive_wrapper.dart';
import '../controller/video_module_controller.dart';
import '../pages/chat/index.dart';
// 引入pages页面
import '../pages/index/index.dart';
import '../pages/my/index.dart';
import '../pages/upload_video_page/upload_video_page.dart';
import '../pages/video/index.dart';
import '../styles/index.dart';

class Layout extends StatefulWidget {
  const Layout({super.key});

  @override
  State<Layout> createState() => _LayoutState();
}

class _LayoutState extends State<Layout> {
  final GlobalKey<MyPageState> myPageKey = GlobalKey<MyPageState>();

  VideoModuleController videoModuleController = Get.put(VideoModuleController());

  // page页面
  // List pageList = [
  //   VideoPage(),
  //   IndexPage(),
  //   UploadVideoPage(
  //     visible: false,
  //   ),
  //   ChatPage(),
  //   MyPage(key: myPageKey)
  // ];
  // tabs选项
  List navItems = [
    BottomNavigationBarItem(icon: Icon(Icons.play_circle_outline), label: '视频'),
    BottomNavigationBarItem(icon: Icon(Icons.local_mall), label: '易选'),
    BottomNavigationBarItem(
        icon: Icon(
          Icons.camera_alt_rounded,
          color: Colors.transparent,
        ),
        label: ''),
    BottomNavigationBarItem(
      icon: Obx(() {
        final unread = Get.find<TabBarController>().getBadge(TabType.chat);
        return Stack(
          alignment: Alignment(4, -2),
          children: [
            Icon(Icons.message),
            if (unread > 0) FStyle.badge(unread), // 显示角标
          ],
        );
      }),
      label: '消息',
    ),
    // BottomNavigationBarItem(icon: Icon(Icons.face), label: '我')
    BottomNavigationBarItem(
      icon: Obx(() {
        final unread = Get.find<TabBarController>().getBadge(TabType.my);
        return Stack(
          alignment: Alignment(4, -2),
          children: [
            const Icon(Icons.face),
            if (unread > 0) FStyle.badge(unread),
          ],
        );
      }),
      label: '我',
    ),
  ];

  @override
  void initState() {
    super.initState();
    // 页面初始化后检查版本更新
    WidgetsBinding.instance.addPostFrameCallback((_) {
      UpgradeService.checkUpgrade(this);
    });
  }

  // 底部导航栏背景色
  Color bottomNavigationBgcolor() {
    int index = videoModuleController.layoutPageCurrent.value;
    int pageVideoTabIndex = videoModuleController.videoTabIndex.value;
    Color color = Colors.white;
    if (index == 0) {
      if ([0, 1, 2].contains(pageVideoTabIndex)) {
        color = Colors.black;
      } else {
        color = Colors.white;
      }
    }
    return color;
  }

  // 底部导航栏颜色
  Color bottomNavigationItemcolor({centerDocked = false}) {
    int index = videoModuleController.layoutPageCurrent.value;
    int pageVideoTabIndex = videoModuleController.videoTabIndex.value;
    Color color = Colors.black54;
    if (index == 0) {
      if ([0, 1, 2].contains(pageVideoTabIndex)) {
        color = Colors.white60;
      } else {
        color = Colors.black54;
      }
    } else if (index == 2 && centerDocked) {
      color = FStyle.primaryColor;
    }
    return color;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.grey[50],
      // body: pageList[pageCurrent],
      // body: Stack(
      //   children: [
      //     Obx(
      //       () => Offstage(
      //         offstage: videoModuleController.layoutPageCurrent.value != 0,
      //         child: const KeepAliveWrapper(child: VideoPage()),
      //       ),
      //     ),
      //     Obx(
      //       () => Offstage(
      //         offstage: videoModuleController.layoutPageCurrent.value != 1,
      //         child: IndexPage(), // 商品保活
      //       ),
      //     ),
      //     Obx(
      //       () => Offstage(
      //         offstage: videoModuleController.layoutPageCurrent.value != 2,
      //         child: UploadVideoPage(
      //           visible: videoModuleController.layoutPageCurrent.value == 2,
      //         ), // 不需要保活
      //       ),
      //     ),
      //     Obx(
      //       () => Offstage(
      //         offstage: videoModuleController.layoutPageCurrent.value != 3,
      //         child: ChatPage(), // 不需要保活
      //       ),
      //     ),
      //     Obx(
      //       () => Offstage(
      //         offstage: videoModuleController.layoutPageCurrent.value != 4,
      //         child: MyPage(key: myPageKey), // 不需要保活
      //       ),
      //     ),
      //   ],
      // ),
      body: Obx(
        () {
          return IndexedStack(
            index: videoModuleController.layoutPageCurrent.value,
            children: [
              const KeepAliveWrapper(child: VideoPage()),
              const KeepAliveWrapper(child: IndexPage()),
              UploadVideoPage(
                visible: videoModuleController.layoutPageCurrent.value == 2,
              ),
              const KeepAliveWrapper(child: ChatPage()),
              KeepAliveWrapper(
                  child: MyPage(
                key: myPageKey,
              )),
            ],
          );
        },
      ),

      // 底部导航栏
      bottomNavigationBar: Theme(
        // Flutter去掉BottomNavigationBar底部导航栏的水波纹
        data: ThemeData(
          splashColor: Colors.transparent,
          highlightColor: Colors.transparent,
          hoverColor: Colors.transparent,
        ),
        child: Obx(() {
          return Stack(
            children: [
              Container(
                decoration: BoxDecoration(
                  border: Border(top: BorderSide(color: Colors.black45, width: .1)),
                ),
                child: BottomNavigationBar(
                  backgroundColor: bottomNavigationBgcolor(),
                  fixedColor: FStyle.primaryColor,
                  unselectedItemColor: bottomNavigationItemcolor(),
                  type: BottomNavigationBarType.fixed,
                  elevation: 1.0,
                  unselectedFontSize: 12.0,
                  selectedFontSize: 12.0,
                  currentIndex: videoModuleController.layoutPageCurrent.value,
                  items: [...navItems],
                  onTap: (index) {
                    onTabTap(index);
                  },
                ),
              ),
              // 自定义底部导航栏中间按钮
              Positioned(
                left: MediaQuery.of(context).size.width / 2 - 18,
                top: 0,
                // bottom: 0,
                bottom: MediaQuery.of(context).padding.bottom, // 动态适配 SafeArea

                child: InkWell(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(
                        'assets/images/ico_carema.png',
                        width: 36.0,
                        isAntiAlias: true,
                        fit: BoxFit.contain,
                      ),
                    ],
                  ),
                  onTap: () {
                    onTabTap(2);
                  },
                ),
              ),
            ],
          );
        }),
      ),
    );
  }

  // 点击底部导航
  void onTabTap(int index) {
    // logger.i(index);
    if (index == 0) {
      if (videoModuleController.videoTabIndex.value == 2) {
        RecommendModule.playVideo();
      }
      if (videoModuleController.videoTabIndex.value == 1) {
        FriendModule.playVideo();
      }
      if (videoModuleController.videoTabIndex.value == 0) {
        AttentionModule.playVideo();
      }
    } else {
      RecommendModule.pauseVideo();
      FriendModule.pauseVideo();
      AttentionModule.pauseVideo();
    }
    if ([2, 3, 4].contains(index) && !Common.isLogin()) {
      Get.toNamed('/login');
      return;
    }
    if (index == 3) {
      // 更新会话列表
      // final ctl = Get.find<ChatController>();
      // logger.e(ctl.chatList.toJson());
      // if (ctl.chatList.isEmpty) {
      //   Get.find<ChatController>().getConversationList();
      // }
    }
    if (index == 4) {
      myPageKey.currentState?.refreshData();
    }
    videoModuleController.updateLayoutPage(index);
    // setState(() {});
  }
}
