import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/pages/team_page/bloc/team_bloc.dart';
import 'package:zhiying_base_widget/pages/team_page/bloc/team_repository.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_data_model.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_style_model.dart';
import 'package:zhiying_base_widget/widgets/team/appbar/team_app_bar_widget.dart';
import 'package:zhiying_base_widget/widgets/team/data/team_data_widet.dart';
import 'package:zhiying_base_widget/widgets/team/fans_list/team_fans_widget.dart';
import 'package:zhiying_base_widget/widgets/team/filter/team_filter_widget.dart';
import 'package:zhiying_base_widget/widgets/team/input/team_input_widget.dart';
import 'package:zhiying_base_widget/widgets/team/recommend/team_recommend_widget.dart';
import 'package:zhiying_comm/util/custom_sliver_persistent_header_delegate.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'dart:ui';
import 'package:flutter_bloc/flutter_bloc.dart';

import 'team_page_sk.dart';

///
/// 我的团队
///
class TeamPage extends StatelessWidget {
  final Map<String, dynamic> data;

  const TeamPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<TeamBloc>(
      create: (_) => TeamBloc(repository: TeamRepository())..add(TeamInitEvent(data)),
      child: _TeamPageContainer(),
    );
  }
}

class _TeamPageContainer extends StatefulWidget {
  @override
  _TeamPageContainerState createState() => _TeamPageContainerState();
}

class _TeamPageContainerState extends State<_TeamPageContainer> {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<TeamBloc, TeamState>(
      listener: (context, state) {},
      buildWhen: (prov, current) {
        if (current is TeamErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print('TeamPage state === $state, ');
        if (state is TeamLoadedState) {
          _initTabController(state?.styleModel);
          return _getMainWidget(state?.styleModel, state?.dataModel);
        }

        /// 骨架屏幕
        return TeamPageSkeleton();
      },
    );
  }

  var tabTitle = [
    '全部1',
    '达人1',
    '超级达人',
    '运营商1',
  ];
  TabController _controller;

  @override
  void initState() {
    // _controller = TabController(length: tabTitle.length, vsync: ScrollableState());
    super.initState();
  }

  void _initTabController(TeamStyleModel styleModel) {
    if (null == _controller) {
      _controller = TabController(length: styleModel?.userLvTabs?.length ?? 0, vsync: ScrollableState());
    }
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  /// 主体视图
  Widget _getMainWidget(TeamStyleModel styleModel, TeamDataModel dataModel) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: HexColor.fromHex(styleModel?.bgColor ?? '#F9F9F9'),
      body: NestedScrollView(
        headerSliverBuilder: (context, bool) {
          return [
            /// 头部Bar
            TeamAppBarWidget(styleModel),

            /// 我的推荐人
            SliverToBoxAdapter(child: TeamRecommendWidget(styleModel, dataModel)),

            /// 数据
            SliverToBoxAdapter(child: TeamDataWidget(styleModel, dataModel)),

            /// 间距
            SliverToBoxAdapter(child: SizedBox(height: 8)),

            /// 输入框
            SliverPersistentHeader(delegate: CustomSliverPersistentHeaderDelegate(min: 34, max: 34, child: TeamInputWidget(styleModel)), pinned: true),

            /// 悬停TabBar
            SliverPersistentHeader(
              delegate: new _SliverTabBarDelegate(
                tabBar: TabBar(
                  isScrollable: false,
                  labelStyle: TextStyle(fontWeight: FontWeight.bold, fontSize: 13),
                  unselectedLabelStyle: TextStyle(fontSize: 13),
                  indicator: MaterialIndicator(
                    height: 2,
                    topLeftRadius: 8,
                    topRightRadius: 8,
                    bottomLeftRadius: 8,
                    bottomRightRadius: 8,
                    color: HexColor.fromHex(styleModel?.userLvTabsLineColor ?? '#F94B47'),
                    horizontalPadding: 30,
                  ),
                  controller: _controller,
                  // tabs: tabTitle.map((f) => Tab(text: f)).toList(),
                  tabs: styleModel.userLvTabs
                      .map((item) => Tab(
                            text: item.name,
                          ))
                      .toList(),
                  indicatorColor: Colors.red,
                  unselectedLabelColor: HexColor.fromHex(styleModel?.userLvTabsNameColor ?? '#999999'),
                  labelColor: HexColor.fromHex(styleModel?.userLvTabsNameSelectedColor ?? '#000000'),
                ),
              ),
              pinned: true,
            ),

            /// 筛选条件
            SliverPersistentHeader(delegate: CustomSliverPersistentHeaderDelegate(max: 32.5, min: 32.5, child: TeamFilterWidget(styleModel)), pinned: true),
          ];
        },
        body: MediaQuery.removePadding(
          removeTop: true,
          context: context,
          // child: TabBarView(controller: _controller, children: tabTitle.map((s) => TeamFansWidget(styleModel)).toList()),
          child: TabBarView(
            controller: _controller,
            children: styleModel.userLvTabs.map((item) => TeamFansWidget(styleModel, item.type)).toList(),
          ),
        ),
      ),
    );
  }
}

class _SliverTabBarDelegate extends SliverPersistentHeaderDelegate {
  final TabBar tabBar;

  const _SliverTabBarDelegate({this.tabBar}) : assert(tabBar != null);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return Container(
      color: Colors.white,
      child: tabBar,
    );
  }

  @override
  bool shouldRebuild(_SliverTabBarDelegate oldDelegate) {
    return false;
  }

  @override
  double get maxExtent => tabBar.preferredSize.height;

  @override
  double get minExtent => tabBar.preferredSize.height;
}
