/// 视频页面模板
library;

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/utils/common.dart';

import '../../IM/im_core.dart';
import '../../behavior/custom_scroll_behavior.dart';
import '../../components/keepalive_wrapper.dart';
import '../../controller/video_module_controller.dart';
import './module/attention.dart';
import './module/friend.dart';
import './module/recommend.dart';
// 引入tab内容模块

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

  @override
  State<VideoPage> createState() => _VideoPageState();
}

class _VideoPageState extends State<VideoPage> with SingleTickerProviderStateMixin {
  GlobalKey<ScaffoldState> scaffoldKey = GlobalKey();

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

  late TabController tabController = TabController(initialIndex: videoModuleController.videoTabIndex.value, length: tabList.length, vsync: this);
  late PageController pageController = PageController(initialPage: videoModuleController.videoTabIndex.value, viewportFraction: 1.0);

  List<String> tabList = ['关注', '朋友', '本地'];
  final tabModules = [
    KeepAliveWrapper(child: AttentionModule()),
    KeepAliveWrapper(child: FriendModule()),
    KeepAliveWrapper(child: RecommendModule()),
  ];
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  // tab文字颜色
  Color tabColor() {
    int tabindex = videoModuleController.videoTabIndex.value;
    Color color = Colors.white;
    if (![0, 1, 2].contains(tabindex)) {
      color = Colors.black;
    }
    return color;
  }

  // tab未选中文字颜色
  Color unselectedTabColor() {
    int tabindex = videoModuleController.videoTabIndex.value;
    Color color = Colors.white70;
    if (![0, 1, 2].contains(tabindex)) {
      color = Colors.black54;
    }
    return color;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      key: scaffoldKey,
      extendBodyBehindAppBar: true,
      appBar: AppBar(
        centerTitle: true,
        forceMaterialTransparency: true,
        backgroundColor: ![0, 1, 2].contains(videoModuleController.videoTabIndex.value) ? null : Colors.transparent,
        foregroundColor: ![0, 1, 2].contains(videoModuleController.videoTabIndex.value) ? Colors.black : Colors.white,
        titleSpacing: 1.0,
        // leading: Obx(() => IconButton(
        //       icon: Badge.count(
        //         backgroundColor: Colors.red,
        //         count: 6,
        //         child: Icon(
        //           Icons.sort_rounded,
        //           color: tabColor(),
        //         ),
        //       ),
        //       onPressed: () {
        //         // 自定义打开右侧drawer
        //         scaffoldKey.currentState?.openDrawer();
        //       },
        //     )),
        title: Obx(() {
          return ScrollConfiguration(
            behavior: CustomScrollBehavior().copyWith(scrollbars: false),
            child: TabBar(
              controller: tabController,
              tabs: tabList.map((v) => Tab(text: v)).toList(),
              isScrollable: true,
              tabAlignment: TabAlignment.center,
              overlayColor: WidgetStateProperty.all(Colors.transparent),
              unselectedLabelColor: unselectedTabColor(),
              labelColor: tabColor(),
              indicatorColor: tabColor(),
              indicatorSize: TabBarIndicatorSize.tab,
              unselectedLabelStyle: const TextStyle(fontSize: 16.0, fontFamily: 'Microsoft YaHei'),
              labelStyle: const TextStyle(fontSize: 16.0, fontFamily: 'Microsoft YaHei', fontWeight: FontWeight.w600),
              dividerHeight: 0,
              labelPadding: const EdgeInsets.symmetric(horizontal: 10.0),
              indicatorPadding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 4.0),
              onTap: (index) {
                // 除了第二个推荐tab，其他tab都校验登录状态
                if (!Common.isLogin() && index != 2) {
                  Get.toNamed('/login');
                  return;
                }
                // 同步索引
                videoModuleController.updateVideoTabIndex(index);
                pageController.jumpToPage(index);
              },
            ),
          );
        }),
        actions: [
          Obx(
            () => IconButton(
              icon: Icon(
                Icons.search_rounded,
                color: tabColor(),
              ),
              onPressed: () {
                print('当前tab索引:${videoModuleController.videoTabIndex.value}');
                if (videoModuleController.videoTabIndex.value == 0) {
                  AttentionModule.playVideo();
                  FriendModule.pauseVideo();
                  RecommendModule.pauseVideo();
                } else if (videoModuleController.videoTabIndex.value == 1) {
                  AttentionModule.pauseVideo();
                  FriendModule.playVideo();
                  RecommendModule.pauseVideo();
                } else if (videoModuleController.videoTabIndex.value == 2) {
                  AttentionModule.pauseVideo();
                  FriendModule.pauseVideo();
                  RecommendModule.playVideo();
                }
                Get.toNamed('/search');
              },
            ),
          ),
        ],
      ),
      body: ScrollConfiguration(
        behavior: CustomScrollBehavior().copyWith(scrollbars: false),
        child: PageView(
          controller: pageController,
          onPageChanged: (index) {
            logger.i('$index');
            // 根据当前 tab 控制对应播放器播放，其它暂停
            if (index == 0) {
              AttentionModule.playVideo();
              FriendModule.pauseVideo();
              RecommendModule.pauseVideo();
            } else if (index == 1) {
              AttentionModule.pauseVideo();
              FriendModule.playVideo();
              RecommendModule.pauseVideo();
            } else if (index == 2) {
              AttentionModule.pauseVideo();
              FriendModule.pauseVideo();
              RecommendModule.playVideo();
            }
            videoModuleController.updateVideoTabIndex(index);
            setState(() {
              tabController.animateTo(index, duration: Duration(milliseconds: 200), curve: Curves.easeInOut);
            });
          },
          children: [...tabModules],
        ),
      ),
      // 侧边栏
      // drawer: Drawer(
      //   shape: RoundedRectangleBorder(borderRadius: BorderRadius.horizontal(right: Radius.circular(15.0))),
      //   clipBehavior: Clip.antiAlias,
      //   width: 300,
      //   child: Container(
      //     color: Colors.grey[50],
      //     child: Column(
      //       children: [
      //         SizedBox(
      //           height: 80.0,
      //         ),
      //         Icon(
      //           Icons.tips_and_updates_outlined,
      //           color: Colors.grey,
      //           size: 50.0,
      //         ),
      //         Text(
      //           '自定义侧边栏~',
      //           style: TextStyle(color: Colors.grey, fontSize: 12.0),
      //         )
      //       ],
      //     ),
      //   ),
      // ),
    );
  }
}
