import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/team_page/model/team_style_model.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:zhiying_base_widget/pages/team_page/notifier/team_page_notifier.dart';
import 'package:zhiying_base_widget/widgets/team/fans_list/bloc/team_list_fans_repository.dart';
import 'package:zhiying_base_widget/widgets/team/fans_list/model/team_fans_list_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';

import 'bloc/team_list_fans_bloc.dart';
import 'team_fans_item.dart';
import 'team_fans_number_item.dart';

class TeamFansWidget extends StatefulWidget {
  TeamStyleModel styleModel;
  final String type;
  final int tabCurrentIndex;

  TeamFansWidget(this.styleModel, this.type, this.tabCurrentIndex);

  @override
  _TeamFansWidgetState createState() => _TeamFansWidgetState();
}

class _TeamFansWidgetState extends State<TeamFansWidget> with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<TeamListFansBloc>(
      create: (_) => TeamListFansBloc(TeamListFansRepository(type: widget?.type)),
      child: _TeamFansWidgetContainer(widget?.styleModel, widget?.tabCurrentIndex),
    );
  }

  @override
  bool get wantKeepAlive => true;
}

class _TeamFansWidgetContainer extends StatefulWidget {
  TeamStyleModel styleModel;
  final int tabCurrentIndex;

  _TeamFansWidgetContainer(this.styleModel, this.tabCurrentIndex);

  @override
  __TeamFansWidgetContainerState createState() => __TeamFansWidgetContainerState();
}

class __TeamFansWidgetContainerState extends State<_TeamFansWidgetContainer> {
  RefreshController _refreshController;
  int tabSelectIndex = 0;

  /// 上拉更多
  void _onLoading() async {
    // if(widget.tabCurrentIndex == tabSelectIndex ) {
    BlocProvider.of<TeamListFansBloc>(context).add(TeamListFansOnLoadEevnt());
    // }
  }

  /// 下拉刷新
  void _onRefresh() async {
    // if(widget.tabCurrentIndex == tabSelectIndex || _refreshController.initialRefresh) {
    BlocProvider.of<TeamListFansBloc>(context).add(TeamListFansOnRefreshEvent());
    // }
  }

  @override
  void initState() {
    _refreshController = RefreshController(initialRefresh: true);
    super.initState();
  }

  @override
  void didChangeDependencies() {
    TeamPageNotifier notifier = Provider.of<TeamPageNotifier>(context);
    if (null != notifier) {
      tabSelectIndex = notifier?.getTabIndex() ?? 0;
      bool isSearch = notifier?.getSearch() ?? false;
      Logger.log('isSearch ==== $isSearch');

      /// 如果是搜索框
      if(isSearch){
        BlocProvider.of<TeamListFansBloc>(context).add(TeamListFansSearchEvent(notifier?.getKeyword()));
      }else {
        Map<String, String> reqArgs = notifier?.getReqArgs() ?? null;
        if (widget.tabCurrentIndex == tabSelectIndex && !EmptyUtil.isEmpty(reqArgs)) {
          Logger.log('didChangeDependencies, currentTabIndex = ${widget?.tabCurrentIndex}, tabSelectIndex = $tabSelectIndex , reqArgs = ${reqArgs?.toString()}');
          // _refreshController.refreshToIdle();
          BlocProvider.of<TeamListFansBloc>(context).add(TeamListFansFilterEvent(args: reqArgs));
        }
      }
    }
    super.didChangeDependencies();
  }

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

  @override
  Widget build(BuildContext context) {
    Logger.log('__TeamFansWidgetContainerState build ====== ');

    return BlocConsumer<TeamListFansBloc, TeamListFansState>(
      listener: (context, current) {
        if (current is TeamListFansOnLoadErrorState) {
          _refreshController?.loadNoData();
        }
        if (current is TeamListFansOnLoadSuccessState) {
          _refreshController?.loadComplete();
        }
        if (current is TeamListFansOnRefreshErrorState) {
          _refreshController?.refreshCompleted();
        }
        if (current is TeamListFansOnRefreshSuccessState) {
          _refreshController?.refreshCompleted();
          _refreshController?.resetNoData();
        }
      },
      buildWhen: (prov, current) {
        if (current is TeamListFansErrorState) {
          if (prov is TeamListFansLoadedState) {
            // Fluttertoast.showToast(msg: '网络似乎开小差了~');
          }
          return true;
        }
        // 加载更多成功
        if (current is TeamListFansOnLoadSuccessState) {
          return false;
        }

        // 加载更多失败
        if (current is TeamListFansOnLoadErrorState) {
          return false;
        }

        // 刷新失败
        if (current is TeamListFansOnRefreshSuccessState) {
          return false;
        }

        // 刷新成功
        if (current is TeamListFansOnRefreshErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        return SmartRefresher(
          onLoading: _onLoading,
          onRefresh: _onRefresh,
          enablePullDown: true,
          enablePullUp: true,
          // footer: ClassicFooter(),
          // header: MaterialClassicHeader(),
          controller: _refreshController,
          // child: ListView.builder(
          //   itemBuilder: (context, int) => int == 0 ? TeamFansNumberItemWidget(widget?.styleModel) : TeamFansItem(widget?.styleModel),
          //   itemCount: 10,
          // ),
          child: _getMainWidget(context, state),
        );
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(context, state) {
    if (state is TeamListFansLoadedState) {
      int lenght = state?.model?.fans?.length ?? 0;
      if (lenght > 0) {
        return ListView.builder(
          itemBuilder: (context, index) {
            if (index == 0) {
              return TeamFansNumberItemWidget(widget?.styleModel, state?.model);
            } else {
              TeamFansListItemModel itemModel = state.model.fans[index - 1];
              return TeamFansItem(widget?.styleModel?.teamViewItem, itemModel);
            }
          },
          itemCount: lenght + 1,
        );
      }
    }
    return _getEmptyWidget();
  }

  /// 空数据的视图
  Widget _getEmptyWidget() {
    return ListView.builder(
      itemCount: 1,
      itemBuilder: (context, int) {
        return Container(
          padding: const EdgeInsets.only(top: 40),
          child: Column(
            children: <Widget>[
              CachedNetworkImage(width: 115, imageUrl: widget?.styleModel?.teamViewEmptyImg ?? ''),
              const SizedBox(height: 26),
              Text('暂时木有好友呀~', style: TextStyle(color: HexColor.fromHex('#999999'), fontSize: 12)),
            ],
          ),
        );
      },
    );
  }
}
