import 'package:flutter/material.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/pages/team_details_page/bloc/team_details_bloc.dart';
import 'package:zhiying_base_widget/pages/team_details_page/bloc/team_details_repository.dart';
import 'package:zhiying_base_widget/pages/team_details_page/model/team_details_data_model.dart';
import 'package:zhiying_base_widget/pages/team_details_page/model/team_details_style_model.dart';
import 'package:zhiying_base_widget/widgets/team_details/month_data/team_details_month_data_widget.dart';
import 'package:zhiying_base_widget/widgets/team_details/referrer/team_details_referrer_widget.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_base_widget/widgets/team/fans_list/team_fans_item.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

///
/// 我的团队 - 用户详情
///

class TeamDetailsPage extends StatelessWidget {
  final Map<String, dynamic> data;

  TeamDetailsPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<TeamDetailsBloc>(
      create: (_) => TeamDetailsBloc(repository: TeamDetailsRepository())..add(TeamDetailsInitEvent(data)),
      child: _TeamDetailsPage(),
    );
  }
}

class _TeamDetailsPage extends StatefulWidget {
  @override
  _TeamDetailsPageState createState() => _TeamDetailsPageState();
}

class _TeamDetailsPageState extends State<_TeamDetailsPage> {
  int _selectIndex = 0;
  TabController _controller;

  @override
  void initState() {
    super.initState();
  }

  void _initTabController(TeamDetailsStyleModel styleModel) {
    int length = styleModel?.dashbord?.length ?? 0;
    if (null == _controller && length > 0) {
      _controller = TabController(length: length, vsync: ScrollableState());
      _controller.addListener(_tabListener);
    }
  }

  void _tabListener() {
    if (!_controller.indexIsChanging) {
      setState(() {
        _selectIndex = _controller.index;
      });
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<TeamDetailsBloc, TeamDetailsState>(
      listener: (context, state) {},
      buildWhen: (prov, current) {
        if (current is TeamDetailsErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is TeamDetailsLoadedState) {
          _initTabController(state?.styleModel);
          return _getMainWidget(state?.styleModel, state?.dataModel);
        }
        return _getMainWidget(null, null);
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(TeamDetailsStyleModel styleModel, TeamDetailsDataModel dataModel) {
    return Scaffold(
      backgroundColor: HexColor.fromHex(styleModel?.bg_color ?? '#F9F9F9'),
      body: CustomScrollView(
        slivers: <Widget>[
          /// 头部Bar
          SliverAppBar(
              // expandedHeight: 200.0,
              brightness: Brightness.light,
              leading: IconButton(
                  icon: Icon(
                    Icons.arrow_back_ios,
                    size: 22,
                    color: HexColor.fromHex('#333333'),
                  ),
                  onPressed: () => Navigator.maybePop(context)),
              backgroundColor: HexColor.fromHex(styleModel?.app_bar_bg_color ?? '#FFFFFF'),
              floating: true,
              pinned: true,
              title: Text(styleModel?.app_bar_name ?? '用户详情',
                  style: TextStyle(color: HexColor.fromHex(styleModel?.app_bar_name_color ?? '#333333'), fontWeight: FontWeight.bold, fontSize: 18)),
              centerTitle: true,
              elevation: 0),

          /// TA的推荐人
          SliverToBoxAdapter(child: TeamDetailsReferrerWidget(styleModel?.header_referrer, dataModel?.referrer)),

          /// 推荐人的信息
          SliverToBoxAdapter(child: TeamFansItem(styleModel?.self_info, dataModel?.info)),

          /// 本月数据 & 上个月数据
          SliverToBoxAdapter(
            child: Visibility(
              visible: null != _controller,
              child: Container(
                height: 30,
                width: double.infinity,
                margin: const EdgeInsets.only(left: 50, right: 50, top: 10),
                child: TabBar(
                  labelStyle: TextStyle(fontSize: 15, fontWeight: FontWeight.bold),
                  indicatorColor: HexColor.fromHex(styleModel?.dashbord_line_color ?? '#F94B47'),
                  indicator: MaterialIndicator(
                    height: 2,
                    bottomRightRadius: 2,
                    bottomLeftRadius: 2,
                    topRightRadius: 2,
                    topLeftRadius: 2,
                    color: HexColor.fromHex(styleModel?.dashbord_line_color ?? '#F94B47'),
                    horizontalPadding: 17,
                  ),
                  unselectedLabelStyle: TextStyle(fontSize: 15),
                  indicatorSize: TabBarIndicatorSize.label,
                  labelColor: HexColor.fromHex(styleModel?.name_selected_color ?? '#000000'),
                  unselectedLabelColor: HexColor.fromHex(styleModel?.name_color ?? '#999999'),
                  controller: _controller,
                  tabs: _buildTabs(styleModel),
                ),
              ),
            ),
          ),

          /// 邀请贡献
          SliverToBoxAdapter(child: _buildDataCar(styleModel, dataModel)),
          //
          // SliverToBoxAdapter(
          //   child: TeamDetailsMonthDataWidget(),
          // ),

          SliverPadding(padding: const EdgeInsets.only(bottom: 28))
        ],
      ),
    );
  }

  /// 本月数据 & 上个月数据
  List<Widget> _buildTabs(TeamDetailsStyleModel styleModel) {
    int length = styleModel?.dashbord?.length ?? 0;
    List<Widget> widgets = [];
    if (length > 0) {
      styleModel.dashbord.forEach((element) {
        widgets.add(Text(element.name));
      });
    } else {
      widgets.add(Text('本月数据'));
      widgets.add(Text('上月数据'));
    }
    return widgets;
  }

  /// 贡献值自购等
  Widget _buildDataCar(TeamDetailsStyleModel styleModel, TeamDetailsDataModel dataModel) {
    List<Widget> widgets = [];
    int styleLength = styleModel?.dashbord_items?.length ?? 0;
    int dataLength = dataModel?.dash_board?.length ?? 0;
    int dataItemLength = dataLength > 0 ? dataModel.dash_board[0]?.list?.length ?? 0 : 0;
    if (styleLength > 0) {
      // styleModel.dashbord_items.forEach((element) {
      //   widgets.add(TeamDetailsMonthDataWidget(element, dataLength > 0 ? dataModel?.dash_board[_selectIndex] : null));
      // });
      for (int i = 0; i < styleLength; i++) {
        TeamDetailsStyleModelDashbordItem element = styleModel.dashbord_items[i];
        TeamDetailsDashBoardItem dataElement = (dataLength > 0 && dataItemLength > 0 && dataItemLength == styleLength) ? dataModel.dash_board[_selectIndex].list[i] : null;
        widgets.add(TeamDetailsMonthDataWidget(element, dataElement));
      }

      return Column(children: widgets);
    } else {
      return Container();
    }
  }
}
