import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/hot_ranking_page/hot_ranking_page_sk.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_bg_notifier.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_notifier.dart';
import 'package:zhiying_base_widget/utils/contants.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:provider/provider.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'hot_ranking_page_bloc.dart';

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

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

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

class _HotRankingPageState extends State<HotRankingPage> {
  @override
  Widget build(BuildContext context) {
    print('hot_ranking_page build');

    //
    // List<Widget> contentWidgets = tabs.map((item) {
    //   BaseTabModel model = BaseTabModel.fromJson(item);
    //   return PageFactory.create(model.skipIdentifier, item);
    // }).toList();
    // if (_currentIndex >= contentWidgets.length) {
    //   _currentIndex = 0;
    // }
    return Scaffold(
      backgroundColor: Color(0xfff9f9f9),
      body: MultiProvider(
        providers: [
          ChangeNotifierProvider.value(value: MainPageBgNotifier()),
        ],
        child: BlocProvider<HotRankingPageBloc>(
          bloc: HotRankingPageBloc(),
          child: _HotRankingPageContainer(data: widget.data),
        ),
      ),
    );
  }
}

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

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

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

class __HotRankingPageContainerState extends State<_HotRankingPageContainer> {
  HotRankingPageBloc _bloc;
  RefreshController _refreshController;
  String backgroundImage;

  @override
  void initState() {
    _refreshController = RefreshController();
    _bloc = BlocProvider.of<HotRankingPageBloc>(context);
    if (widget.data.containsKey(Constants.SkipIdentifierName)) {
      _bloc.loadData(widget.data[Constants.SkipIdentifierName]);
    }

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _bloc.outData,
      builder: (context, asyncSnapshot) {
        var model = asyncSnapshot.data;
        if (model == null) {
          return HotRankingPageSkeleton();
        }
        for (var item in model) {
          WidgetModel widgetModel =
          WidgetModel.fromJson(Map<String, dynamic>.from(item));
          if (item.containsKey("mod_name") &&
              item['mod_name'] == "hot_rank_bg_img") {
            _bloc.backgroundImage = json.decode(item['data'])['bg_img'];
            break;
          }
        }
        return Stack(
          children: <Widget>[
            Container(
              height: 293.h,
              decoration: BoxDecoration(
                  image: DecorationImage(
                      image: CachedNetworkImageProvider(
                          _bloc.backgroundImage ?? ""),
                      fit: BoxFit.fill)),
            ),
            Column(
              children: _createContent(context, model),
            )
          ],
        );
      },
    );
  }

  //刷新
  void _onLoading() async {}

  ///构建子模块
  _createContent(BuildContext context, List<Map<String, dynamic>> model) {
    List<Widget> list = List();
    if (model == null) {
      ///骨架图
    } else {
      for (var item in model) {
        WidgetModel widgetModel =
        WidgetModel.fromJson(Map<String, dynamic>.from(item));
        if (item.containsKey("mod_name") &&
            item['mod_name'] == "hot_rank_tab_view") {
          list.add(Expanded(
              child: WidgetFactory.create(widgetModel.modName,
                  isSliver: false, model: item)[0]));
          continue;
        }
        list.addAll(WidgetFactory.create(widgetModel.modName,
            isSliver: false, model: item));
      }
    }
    return list;
  }
}

class _SilverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SilverAppBarDelegate(BuildContext context, this.child) {
    this.context = context;
  }

  BuildContext context;
  final Widget child;

  @override
  double get minExtent =>
      MediaQuery
          .of(context)
          .padding
          .top + 44;

  @override
  double get maxExtent =>
      MediaQuery
          .of(context)
          .padding
          .top + 44;

  @override
  Widget build(BuildContext context, double shrinkOffset,
      bool overlapsContent) {
    return child;
  }

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