import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/dialog/loading/loading.dart';
import 'package:zhiying_base_widget/dialog/loading/loading_dialog.dart';
import 'package:zhiying_base_widget/pages/hot_ranking_page/hot_ranking_page_bloc.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/home_goods_item_single.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_list_style_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_style_model.dart';
import 'package:zhiying_base_widget/widgets/hot_ranking/hot_ranking_goods/hot_ranking_goods.dart';
import 'package:zhiying_base_widget/widgets/hot_ranking/hot_ranking_list/model/hot_ranking_list_data_model.dart';
import 'package:zhiying_base_widget/widgets/hot_ranking/hot_ranking_list/model/hot_ranking_list_model.dart';
import 'package:zhiying_base_widget/widgets/refresh/refresh_footer/refresh_footer.dart';
import 'package:zhiying_base_widget/widgets/refresh/refresh_header/refresh_header.dart';
import 'package:zhiying_comm/util/base_bloc.dart';

import 'hot_ranking_bloc.dart';
import 'hot_ranking_list_sk.dart';

class HotRankingList extends StatefulWidget {
  final Map<String, dynamic> data;

  const HotRankingList(this.data, {Key key}) : super(key: key);

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

class _HotRankingState extends State<HotRankingList> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  HotRankingListBloc _bloc;
  TabController _tabController;
  RefreshController _refreshController;
  List<HomeGoodsModel> goods;

  HotRankingPageBloc _pageBloc;

  ScrollController _scrollcontroller;

  bool isFirstTime = true;

  @override
  void initState() {
    _bloc = HotRankingListBloc();
    _refreshController = RefreshController();
    _pageBloc = BlocProvider.of<HotRankingPageBloc>(context);
    _scrollcontroller = ScrollController();

    if (_pageBloc != null) {
      _pageBloc.event.listen((event) {
        if (event.containsKey('type') && event['type'] == "loadData") {
          if (!isFirstTime) {
            Loading.show(context);
          }
          isFirstTime = false;
          _bloc.currentPage = 1;
          _bloc.loadData(event['type_id'], _bloc.currentPage, () {});
          _scrollcontroller.animateTo(0, duration: Duration(milliseconds: 500), curve: Curves.bounceInOut);
        }
      });
    }

    super.initState();
  }

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

  ///构建
  void createTabController() {
    _tabController = TabController(length: 4, vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<HotRankingListDataModel>(
        stream: _bloc.outData,
        builder: (context, snapshot) {
          if (snapshot.data == null) {
            return HotRankingSkeleton();
          } else {
            goods = snapshot.data.good;

            return SmartRefresher(
              controller: _refreshController,
              enablePullDown: true,
              enablePullUp: true,
              onLoading: _onLoading,
              onRefresh: _onRefresh,
              header: RefreshHeader(),
              footer: RefreshFooter(),
              child: CustomScrollView(
                controller: _scrollcontroller,
                slivers: <Widget>[SliverList(delegate: SliverChildBuilderDelegate(_buildListItem, childCount: goods.length))],
              ),
            );
          }
        });
  }

  Future _onLoading() async {
    _bloc.loadMoreData(_bloc.currentTypeId, () {
      _refreshController.loadComplete();
    });
    return null;
  }

  Future _onRefresh() async {
    _bloc.currentPage = 1;
    _bloc.loadData(_bloc.currentTypeId, _bloc.currentPage, () {
      _refreshController.refreshCompleted();
    });
  }

  Widget _buildListItem(BuildContext context, int index) {
    HomeGoodsStyleModel homeGoodsStyleModel = HomeGoodsStyleModel();
    homeGoodsStyleModel.listStyle = HomeGoodsListStyleModel.fromJson(json.decode(widget.data['data']));
    var indexImage;
    if (homeGoodsStyleModel.listStyle.hotRankIconList != null &&
        homeGoodsStyleModel.listStyle.hotRankIconList.length > 0 &&
        homeGoodsStyleModel.listStyle.hotRankIconList.length - 1 >= index) {
        indexImage = homeGoodsStyleModel.listStyle.hotRankIconList[index];
    }
    return HomeGoodsItemSingle(
      goods[index],
      homeGoodsStyleModel,
      indexImage: indexImage,
    );
    // return HotRankingGoods(
    //   styleModel:
    //       HotRankingListModel.fromJson(json.decode(widget.data['data'])),
    //   good: goods[index],
    //   index: index,
    // );
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}
