import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.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_base_widget/widgets/hot_ranking/hot_ranking_list/model/hot_ranking_list_model.dart';
import 'package:zhiying_base_widget/widgets/refresh/refresh_header/refresh_header.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_appbar/wallet_appbar_sk.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_data/wallet_data_sk.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_detail/wallet_detail_sk.dart';
import 'package:zhiying_base_widget/widgets/wallet/wallet_income/wallet_income_sk.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'dart:ui';
import 'package:provider/provider.dart';

import 'wallet_page_bloc.dart';

///钱包页面
class WalletPage extends StatefulWidget {
  final Map<String, dynamic> data;

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

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

class _WalletPageState extends State<WalletPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff9f9f9),
      body: MultiProvider(
        providers: [
          ChangeNotifierProvider.value(value: BaseChangeNotifier()),
        ],
        child: BlocProvider<WalletPageBloc>(
          bloc: WalletPageBloc(),
          child: _WalletPageContainer(
            data: widget.data,
          ),
        ),
      ),
    );
  }
}

class _WalletPageContainer extends StatefulWidget {
  _WalletPageContainer({Key key, this.data}) : super(key: key);

  final Map<String, dynamic> data;

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

class _WalletPageContainerState extends State<_WalletPageContainer>
    with AutomaticKeepAliveClientMixin {
  ScrollController _controller;
  RefreshController _refreshController;

  WalletPageBloc _pageBloc;

  @override
  void initState() {
    _controller = ScrollController();
    _refreshController = RefreshController(initialRefresh: false);
    _pageBloc = BlocProvider.of<WalletPageBloc>(context);
    if (widget.data.containsKey(Constants.SkipIdentifierName)) {
      _pageBloc.loadData(widget.data[Constants.SkipIdentifierName]);
    }
    super.initState();
  }

  @override
  void didChangeDependencies() {
    var userInfo = Provider.of<UserInfoNotifier>(context);
    if (userInfo != null) {
      if (widget.data.containsKey(Constants.SkipIdentifierName)) {
        _pageBloc.loadData(widget.data[Constants.SkipIdentifierName]);
        Provider.of<BaseChangeNotifier>(context,listen: false).refresh();
      }
    }
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    _refreshController?.dispose();
     Provider.of<BaseChangeNotifier>(context,listen: false).close();
    super.dispose();
  }

  void _onLoading() async {
    // await Future.delayed(Duration(milliseconds: 1000));
    // if (mounted) setState(() {});
    // _refreshController.loadComplete();
  }

  void _onRefresh() async {
    if (widget.data.containsKey(Constants.SkipIdentifierName)) {
      _pageBloc.loadData(widget.data[Constants.SkipIdentifierName]);
      Provider.of<BaseChangeNotifier>(context,listen: false).refresh();
    }
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334);
    double top = MediaQueryData.fromWindow(window).padding.top;
    return Container(
      width: double.infinity,
      child: Stack(
        fit: StackFit.passthrough,
        children: <Widget>[
          StreamBuilder(
            stream: _pageBloc.outData,
            builder: (context, asyncSnapshot) {
              var model = asyncSnapshot.data;
              _refreshController.refreshCompleted();
              return Stack(
                children: <Widget>[
                  Container(height: 181, color: _pageBloc.backgroundColor),
                  SmartRefresher(
                    controller: _refreshController,
                    enablePullDown: true,
                    enablePullUp: false,
                    header: RefreshHeader(
                      offsetY: top,
                    ),
                    onLoading: _onLoading,
                    onRefresh: _onRefresh,
                    child: CustomScrollView(
                      controller: _controller,
                      slivers: _createContent(context, model),
                    ),
                  )
                ],
              );
            },
          )
        ],
      ),
    );
  }

  List<Widget> _createContent(
      BuildContext context, List<Map<String, dynamic>> model) {
    List<Widget> list = List();
    if (model == null) {
      ///骨架图
      list.add(SliverToBoxAdapter(
        child: WalletAppbarSkeleton(),
      ));
      list.add(SliverToBoxAdapter(
        child: WalletDataSkeleton(),
      ));
      list.add(SliverToBoxAdapter(
        child: WalletIncomeSkeleton(),
      ));
      list.add(SliverToBoxAdapter(
        child: WalletDetailSkeleton(),
      ));
    } else {
      for (var item in model) {
        WidgetModel widgetModel =
            WidgetModel.fromJson(Map<String, dynamic>.from(item));
        list.addAll(WidgetFactory.create(widgetModel.modName,
            isSliver: true, model: item));
      }
    }
    return list;
  }

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

// 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;
//   }
// }