import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/bloc/goods_details_page_bloc.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/bloc/goods_details_page_repository.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/goods_details_page_sk.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/notifier/goods_details_page_notifier.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/goods_details_footer_widget.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

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

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

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

class _GoodsDetailsPageState extends State<GoodsDetailsPage> {
  @override
  void initState() {
    print("parent data = ${widget.data}");
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        /// 滑动通知
        ChangeNotifierProvider.value(value: GoodsDetailsPageNotifier()),
      ],
      child: BlocProvider<GoodsDetailsPageBloc>(
        create: (_) =>
            GoodsDetailsPageBloc(repository: GoodsDetailsPageRepository())
              ..add(GoodsDetailsPageInitEvent(model: widget?.data)),
        child: GoodsDetailsContainer(widget?.data),
      ),
    );
  }
}

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

  const GoodsDetailsContainer(this.data);

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

class _GoodsDetailsContainerState extends State<GoodsDetailsContainer> {
  bool _isEnded = false;
  ScrollController _controller = ScrollController();
  RefreshController _refreshController = RefreshController(initialRefresh: false);

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

  /// 返回上一页
  void _openPop() {
    print('返回上一页');

    Navigator.maybePop(context);
  }

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

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

  @override
  Widget build(BuildContext context) {
    return MediaQuery.removePadding(
      removeTop: true,
      context: context,
      child: Container(
        width: double.infinity,
        child: BlocConsumer<GoodsDetailsPageBloc, GoodsDetailsPageState>(
          listener: (BuildContext context, GoodsDetailsPageState state) {
            if (state is GoodsDetailsPageErrorState) {
              print('数据加载出错');
            }
          },
          buildWhen: (previous, current) {
            /// 数据加载出错不进行build
            if (current is GoodsDetailsPageErrorState) {
              return false;
            }
            return true;
          },
          builder: (context, state) {
            print('currente state = $state');
            if (state is GoodsDetailsPageLoadedState) {
              return _getMainWidget(state?.model);
            }
            return GoodsDetailsPageSkeleton();
          },
        ),
      ),
    );
  }

  /// 主视图
  Widget _getMainWidget(List<Map<String, dynamic>> datas) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Container(
        color: Color(0xfff1f1f1),
        child: CustomScrollView(
          controller: _controller,
          slivers: _createContent(context, datas ?? []),
        ),
      ),

      /// appBar
      // Align(alignment: Alignment.topCenter, child: _getAppBarWidget()),

      /// 底部
      bottomNavigationBar: GoodsDetailsFooterWidget(
          !EmptyUtil.isEmpty(datas) ? datas[datas.length - 1] : null),
    );
  }

  List<Widget> _createContent(
      BuildContext context, List<Map<String, dynamic>> datas) {
    List<Widget> list = List();

    /// datas.length - 1 为最后一个在底部
    for (int i = 0; i < datas.length - 1; 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],
      ));
    }
    if (list.length <= 0) {
      list.add(SliverToBoxAdapter(
        child: Container(
          height: 200,
          child: Center(
            child: Text('暂时无数据哦~'),
          ),
        ),
      ));
    }
    return list;
  }

  /// appBar
  Widget _getAppBarWidget() {
    return Container(
      width: double.infinity,
      height: 40,
      margin:
          EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
      child: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          icon: Icon(
            Icons.arrow_back_ios,
            size: 22,
            color: HexColor.fromHex('#FFFFFF'),
          ),
          onPressed: () => _openPop(),
        ),
      ),
    );
  }
}
