import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/search_result_page/item/bloc/search_result_item_bloc.dart';
import 'package:zhiying_base_widget/pages/search_result_page/item/bloc/search_result_item_repository.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/skeleton/home_goods_sk.dart';
import 'package:zhiying_base_widget/widgets/search_result/goods_list/bloc/search_result_goods_list_bloc.dart';
import 'package:zhiying_base_widget/widgets/search_result/goods_list/bloc/search_result_goods_list_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';

import 'notifier/search_result_item_page_notifier.dart';

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

  const SearchResultItemPage(this.data);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: SearchResultItemPageNotifier()),
      ],
      // child: BlocProvider<SearchResultItemBloc>(
      //   create: (_) => SearchResultItemBloc(repository: SearchResultItemRepository())..add(SearchResultItemInitEvent(model: data)),
      //   child: SearchResultItemPageContianer(),
      // ),
      child: MultiBlocProvider(
        providers: [
          /// 视图BLOC
          BlocProvider<SearchResultItemBloc>(
            create: (_) => SearchResultItemBloc(repository: SearchResultItemRepository())..add(SearchResultItemInitEvent(model: data)),
          ),

          /// 商品列表Bloc
          BlocProvider<SearchResultGoodsListBloc>(
            create: (_) => SearchResultGoodsListBloc(repository: SearchResultGoodsListRepository(reqData: data)),
          ),
        ],
        child: SearchResultItemPageContianer(),
      ),
    );
  }
}

class SearchResultItemPageContianer extends StatefulWidget {
  @override
  _SearchResultItemPageContianerState createState() => _SearchResultItemPageContianerState();
}

class _SearchResultItemPageContianerState extends State<SearchResultItemPageContianer> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  RefreshController _refreshController;
  ScrollController _controller;
  bool _isEnded = false;

  @override
  void initState() {
    _refreshController = RefreshController();
    _controller = ScrollController();

    _controller.addListener(() {
      // print('${_controller.offset}   ${_controller.position.maxScrollExtent}');
      if (_controller.offset >= _controller.position.maxScrollExtent && !_isEnded) {
        // 滑动到底部
        _isEnded = true;
        Provider.of<SearchResultItemPageNotifier>(context, listen: false).loadMore();
      } else if (_controller.offset < _controller.position.maxScrollExtent && _isEnded) {
        _isEnded = false;
        Provider.of<SearchResultItemPageNotifier>(context, listen: false).reset();
      }
    });

    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<SearchResultItemBloc, SearchResultItemState>(
      listener: (BuildContext context, SearchResultItemState state) {
        if (state is SearchResultItemErrorState) {
          print('数据加载出错');
        }
      },
      buildWhen: (previous, current) {
        /// 数据加载出错不进行build
        if (current is SearchResultItemErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print('currente state = $state');
        if (state is SearchResultItemLoadedState) {
          return _getMainWidget(state?.model ?? null);
        }

        /// 骨架屏幕
        return _getMainWidget(null);
      },
    );
  }

  /// 上拉更多
  void _onLoading() async {
    BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListOnLoadEvent());
    _refreshController.loadComplete();
  }

  /// 下拉刷新
  void _onRefresh() async {
    BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListOnRefreshEvent());
    _refreshController.refreshCompleted(resetFooterState: true);
  }

  /// 获取主视图
  Widget _getMainWidget(List<Map<String, dynamic>> datas) {
    return Scaffold(
      backgroundColor: HexColor.fromHex('#F9F9F9'),
      body: Stack(
        children: <Widget>[
          Positioned(
            top: 20,
            left: 0,
            right: 0,
            bottom: 0,
            child: SmartRefresher(
              onLoading: _onLoading,
              onRefresh: _onRefresh,
              enablePullDown: true,
              enablePullUp: true,
              // footer: ClassicFooter(),
              // header: WaterDropHeader(),
              controller: _refreshController,
              child: CustomScrollView(
                controller: _controller,
                slivers: _createContentWidget(datas),
              ),
            ),
          ),

          /// 筛选栏
          _getSearchResultSortWidget(datas),
        ],
      ),
    );
  }

  /// 筛选栏
  Widget _getSearchResultSortWidget(List<Map<String, dynamic>> datas) {
    int length = datas?.length ?? 0;
    if (length == 0) {
      return Container();
    } else {
      WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(datas[0]));
      List<Widget> itemWidgets = WidgetFactory.create(item.modName, isSliver: false, model: datas[0]);
      int length = itemWidgets?.length ?? 0;
      return Align(alignment: Alignment.topCenter, child: length > 0 ? itemWidgets[0] : Container());
    }
  }

  /// 创建Widget
  List<Widget> _createContentWidget(List<Map<String, dynamic>> datas) {
    List<Widget> list = [];
    int length = datas?.length ?? 0;
    if (length > 0) {
      /// 去除筛选栏， 从1开始
      for (int i = 1; i < datas.length; i++) {
        WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(datas[i]));
        print('item.modName ${item.modName}');
        list.addAll(WidgetFactory.create(
          item.modName,
          isSliver: true,
          model: datas[i],
        ));
      }
    } else {
      list.add(SliverToBoxAdapter(
        /// TODO 改成骨架图
        child: HomeGoodsSkeleton(),
      ));
    }
    return list;
  }
}
