import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:provider/provider.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_notifier.dart';
import 'package:zhiying_base_widget/widgets/empty/empty_widget.dart';
import 'package:zhiying_base_widget/widgets/home/home_auth/home_auth.dart';
import 'package:zhiying_base_widget/widgets/refresh/refresh_header/refresh_gif_header.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'bloc/custom_item_page_bloc.dart';
import 'bloc/custom_item_page_state.dart';
import 'bloc/custom_item_page_event.dart';
import 'bloc/custom_item_page_repository.dart';


///
/// 通用模块的分类导航下的子模块
///
///
class CustomItemPage extends StatelessWidget {
  final Map<String, dynamic> data;
  final int tabIndex;
  final String modPid;
  final String modId;
  final bool needBuildStatus;

  CustomItemPage(this.data, this.tabIndex, this.modId, this.modPid, this.needBuildStatus);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider.value(value: MainPageNotifier()),
      ],
      child: BlocProvider<CustomItemPageBloc>(
        create: (_) => CustomItemPageBloc(CustomItemPageRepository(this.data, this.tabIndex, this.modId, this.modPid)),
        child: _CustomItemPageContainer(this.data, this.tabIndex, this.modId, this.modPid, this.needBuildStatus),
      ),
    );
  }
}

class _CustomItemPageContainer extends StatefulWidget {
  final Map<String, dynamic> data;
  final int tabIndex;
  final String modPid;
  final String modId;
  final bool needBuildStatus;

  const _CustomItemPageContainer(this.data, this.tabIndex, this.modId, this.modPid, this.needBuildStatus, {Key key}) : super(key: key);

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

class __CustomItemPageContainerState extends State<_CustomItemPageContainer> with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  ScrollController _controller;
  RefreshController _refreshController;
  final EventBus _eventBus = EventBus();


  /// 回到顶点
  void _scrollTop() {
    // _controller.jumpTo(0);
    _controller.animateTo(0, duration: Duration(milliseconds: 200), curve: Curves.linear);
  }

  /// 初始化
  void _initEvent() {
    BlocProvider.of<CustomItemPageBloc>(context).add(CustomItemPageInitEvent());
  }

  /// 刷新
  void _refreshEvent() {
    BlocProvider.of<CustomItemPageBloc>(context).add(CustomItemPageRefreshEvent());
  }

  /// 下拉更多
  void _loadEvent() {
    // BlocProvider.of<CustomItemPageBloc>(context).add(CustomItemPageLoadEvent());
    Provider.of<MainPageNotifier>(context, listen: false).loadMore();
    Future.delayed(Duration(milliseconds: 500), () => _refreshController?.loadComplete());
  }

  @override
  void initState() {
    _controller = ScrollController();
    _refreshController = RefreshController(initialRefresh: false);
    _initEvent();
    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CustomItemPageBloc, CustomItemPageState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (current is CustomItemPageRefreshSuccessState) {
          _refreshController?.refreshCompleted(resetFooterState: true);
          return false;
        }
        if (current is CustomItemPageRefreshErrorState) {
          _refreshController?.refreshFailed();
          return false;
        }
        if (current is CustomItemPageLoadSuccessState) {
          _refreshController?.loadComplete();
          return false;
        }
        if (current is CustomItemPageLoadErrorState) {
          _refreshController?.loadNoData();
          return false;
        }
        if (current is CustomItemPageErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is CustomItemPageLoadedState) {
          if (EmptyUtil.isEmpty(state.model))
            return _buildEmptyWidget();
          else
            return _buildMainWidget(state.model);
        }
        if (state is CustomItemPageInitErrorState) {
          return _buildEmptyWidget();
        }
        return _buildSkeletonWidget();
      },
    );
  }

  /// 有数据
  Widget _buildMainWidget(final List<Map<String, dynamic>> model) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: false,
      child: Stack(
        children: <Widget>[
          SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: true,
            onRefresh: _refreshEvent,
            onLoading: _loadEvent,
            header: RefreshGifHeader(),
            // footer: RefreshFooter(),
            child: CustomScrollView(
              controller: _controller,
              slivers: _buildContentWidgets(model),
            ),
          ),
          Align(
            alignment: Alignment.bottomCenter,
            child: Container( margin: const EdgeInsets.only(bottom: 8), child: _buildAuthWidget(model),), //_buildAuthWidget(model),
          )
        ],
      ),
    );
  }

  /// 根据widget的modName生成视图
  List<Widget> _buildContentWidgets(final List<Map<String, dynamic>> datas) {
    List<Widget> result = [];
    for (int i = 0; i < datas.length; i++) {
      WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(datas[i]));
      if(item.modName == 'audit_tip'){
        Logger.debug('授权组件，跳过');
        continue;
      }
      if(item.modName == 'product'){
        datas[i]['eventBus'] = _eventBus;
      }
      result.addAll(WidgetFactory.create(
        item.modName,
        isSliver: true,
        model: datas[i],
      ));
    }

    // if (widget.needBuildStatus) {
    //   double top = MediaQueryData.fromWindow(window).padding.top;
    //   result.insert(
    //       0,
    //       SliverPersistentHeader(
    //         pinned: false,
    //         floating: false,
    //         delegate: CustomSliverPersistentHeaderDelegate(max: top, min: top, child: Container(
    //           // color: Colors.yellow,
    //           color: HexColor.fromHex('#FFFF4242'),
    //         )),
    //       ));
    //
    // }

    return result;
  }

  /// 空数据
  Widget _buildEmptyWidget() {
    return SmartRefresher(
      controller: _refreshController,
      onRefresh: _refreshEvent,
      enablePullDown: true,
      child: Container(
        child: EmptyWidget(),
      ),
    );
  }

  /// 骨架图
  Widget _buildSkeletonWidget() {
    return Container();
  }

  /// 特殊的授权组件
  Widget _buildAuthWidget(final List<Map<String, dynamic>> datas){
    int length = datas?.length ?? 0;
    if(length == 0) return Container();
    Widget rlt;
    for (int i = 0; i < datas.length; i++) {
      WidgetModel item = WidgetModel.fromJson(Map<String, dynamic>.from(datas[i]));
      if(item.modName == 'audit_tip'){
        rlt = HomeAuth(datas[i]);
        break;
      }
    }

    return rlt ?? Container();

  }

}
