import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:event_bus/event_bus.dart';
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/main_page/notifier/main_page_notifier.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_bg_notifier.dart';
import 'package:zhiying_base_widget/widgets/goods_details/appbar/goods_details_appbar_widget.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/goods_details_footer_widget.dart';
import 'package:zhiying_base_widget/widgets/goods_details/footer/model/goods_details_footer_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'notifier/goods_details_appbar_color_notifier.dart';

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

  GoodsDetailsPage(this.data, {this.isFree = false, 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: MainPageBgNotifier()),
        ChangeNotifierProvider.value(value: MainPageNotifier()),
        ChangeNotifierProvider.value(value: GoodsDetailsAppBarColorNotifier()),
      ],
      child: BlocProvider<GoodsDetailsPageBloc>(
        create: (_) => GoodsDetailsPageBloc(repository: GoodsDetailsPageRepository())..add(GoodsDetailsPageInitEvent(model: widget?.data)),
        child: GoodsDetailsContainer(
          widget?.data,
          isFree: widget?.isFree,
        ),
      ),
    );
  }
}

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

  const GoodsDetailsContainer(this.data, {this.isFree = false});

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

class _GoodsDetailsContainerState extends State<GoodsDetailsContainer> {
  bool _isEnded = false;
  ScrollController _controller;
  RefreshController _refreshController;
  final int BANNER_HEIGHT = 375 - 40;
  EventBus _eventBus;

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

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

    Navigator.maybePop(context);
  }

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

      if (_controller.offset >= 0 && _controller.offset <= BANNER_HEIGHT) {
        double percent = _controller.offset == 0 ? 0.0 : _controller.offset / BANNER_HEIGHT;
        Provider.of<GoodsDetailsAppBarColorNotifier>(context, listen: false).setPercent(percent);
      } else if (_controller.offset > BANNER_HEIGHT && _controller.offset <= BANNER_HEIGHT + 300) {
        Provider.of<GoodsDetailsAppBarColorNotifier>(context, listen: false).setPercent(1);
      }
    });
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return 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('GoodsDetailsPage currente state = $state');
        if (state is GoodsDetailsPageLoadedState) {
          int length = state?.model?.length ?? 0;
          if (length == 0) {
            return GoodsDetailsPageSkeleton();
          }
          return _getMainWidget(state?.model);
        }
        return GoodsDetailsPageSkeleton();
      },
    );
  }

  /// 主视图
  Widget _getMainWidget(List<Map<String, dynamic>> datas) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: Stack(
        children: <Widget>[
          Container(
              color: Color(0xfff1f1f1),
              child: Stack(
                children: <Widget>[
                  CustomScrollView(
                    controller: _controller,
                    slivers: _createContent(context, datas ?? []),
                  ),
                  Align(alignment: Alignment.topCenter, child: GoodsDetailsAppBarWidget(datas[0])),
                ],
              )),
          Align(
            alignment: Alignment.bottomCenter,
            child: _FloatView(
              !EmptyUtil.isEmpty(datas) ? datas[datas.length - 1] : null,
            ),
          )
        ],
      ),

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

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

    /// datas.length - 1 为最后一个在底部
    for (int i = 1; i < datas.length - 1; i++) {
      WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(datas[i]));

      print('商品详情页面item.modName ${item.modName}');

      if (item.modName == 'product') {
        datas[i]['eventBus'] = _eventBus;
      }

      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,
      color: HexColor.fromHex('#FF4242'),
      height: MediaQueryData.fromWindow(window).padding.top + 44,
      padding: EdgeInsets.only(top: MediaQueryData.fromWindow(window).padding.top),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: <Widget>[
          Padding(
              padding: const EdgeInsets.only(left: 12.5),
              child: SizedBox(
                width: 40,
                height: 40,
                child: IconButton(
                  icon: Icon(
                    Icons.arrow_back_ios,
                    size: 22,
                    color: HexColor.fromHex('#FFFFFF'),
                  ),
                  onPressed: () => _openPop(),
                ),
              )),
          Text(
            '商品详情',
            style: TextStyle(color: HexColor.fromHex('#FFFFFF'), fontSize: 15, fontWeight: FontWeight.bold),
          ),
          Padding(
              padding: const EdgeInsets.only(right: 12.5),
              child: SizedBox(
                width: 40,
                height: 40,
                child: Container(
                  height: double.infinity,
                  width: double.infinity,
                  color: Colors.transparent,
                ),
              )),
        ],
      ),
      // child: AppBar(
      //   backgroundColor: Colors.transparent,
      //   elevation: 0,
      //   leading:
      //   IconButton(
      //     icon: Icon(
      //       Icons.arrow_back_ios,
      //       size: 22,
      //       color: HexColor.fromHex('#FFFFFF'),
      //     ),
      //     onPressed: () => _openPop(),
      //   ),
      // ),
    );
  }

  ///构建浮动页
  _FloatView(Map<String, dynamic> model) {
    if (model != null) {
      return FloatView(
        model: model,
      );
    }
  }
}

class FloatView extends StatefulWidget {
  final Map<String, dynamic> model;

  const FloatView({Key key, this.model}) : super(key: key);

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

class _FloatViewState extends State<FloatView> with TickerProviderStateMixin {
  double floatMarginBottom = 0.0;
  Timer floatTimer;

  AnimationController animationController;


  Animation<double> tween;

  GoodsDetailsFooterModel footerModel;

  @override
  void initState() {
    footerModel = GoodsDetailsFooterModel.fromJson(json.decode(widget?.model['data']));
    animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 3000));
    CurvedAnimation curvedAnimation = CurvedAnimation(parent: animationController, curve: Curves.easeInOutBack);
    tween = Tween<double>(begin: 5, end: 20).animate(curvedAnimation);
    curvedAnimation.addListener(() {
      setState(() {});
    });

    animationController.repeat(reverse: true);

    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
   // return Container();
    return Row(
      mainAxisAlignment: MainAxisAlignment.end,
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(bottom: tween?.value ?? 0, right: 25),
          color: Colors.red,
          child: Text(""),
        ),
      ],
    );
  }
}
