import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
import 'package:zhiying_base_widget/pages/favorites_page/model/favorites_style_model.dart';
import 'package:zhiying_base_widget/pages/favorites_page/notifier/favorites_page_notifier.dart';
import 'package:zhiying_base_widget/widgets/favorites/dialog/favorites_dialog_widget.dart';
import 'package:zhiying_base_widget/widgets/favorites/goods_list/bloc/favorites_goods_list_bloc.dart';
import 'package:zhiying_base_widget/widgets/favorites/goods_list/bloc/favorites_goods_list_repository.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/home_goods_item_single.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_style_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/skeleton/home_goods_sk.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'model/favorites_goods_list_model.dart';

class FavoritesGoodsListWidget extends StatelessWidget {
  FavoritesStyleModel model;
  String type;
  int currentIndex;

  FavoritesGoodsListWidget({@required this.model, @required this.type, this.currentIndex = 0});

  @override
  Widget build(BuildContext context) {
    return BlocProvider<FavoritesGoodsListBloc>(
      create: (_) => FavoritesGoodsListBloc(FavoritesGoodsListRepository(type: type)),
      child: _FavoritesGoodsListWidgetContainer(model, currentIndex),
    );
  }
}

class _FavoritesGoodsListWidgetContainer extends StatefulWidget {
  FavoritesStyleModel styleModel;
  int currentIndex;

  _FavoritesGoodsListWidgetContainer(this.styleModel, this.currentIndex);

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

class __FavoritesGoodsListWidgetContainerState extends State<_FavoritesGoodsListWidgetContainer> with AutomaticKeepAliveClientMixin {
  RefreshController _refreshController;
  SlidableController _slidableController;

  // 是否编辑中
  bool isEditing = false;
  int lastChangeVal = -1;

  /// 下拉刷新
  void _onRefresh() async {
    BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListOnRefreshEvent());
  }

  /// 上拉更多
  void _onLoad() async {
    BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListOnLoadEvent());
  }

  /// 右边划删除
  void _onSlideDelete(ConfirmDialog styleModel,int index) async{
    var result = await showDialog(context: context, child: FavoritesDialogWidget(styleModel: styleModel,));
    if(result == 1){
      BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListSlideDeleteEvent(index));
      // Slidable.of(context)?.renderingMode == SlidableRenderingMode.none ? Slidable.of(context)?.open() : Slidable.of(context)?.close();
      // Slidable.of(context)?.close();
    }
  }

  /// 分享商品
  void _onSlideShare() async{
    // TODO 分享商品还没弄
  }

  /// 商品点击选中
  void _onClickGoods(int index){
    BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListSignGoodsSelectEvent(index));
  }

  /// 全选
  void _onClickAllSelecct(FavoritesGoodsListDataModel dataModel) {

    if(!dataModel.isAllSelect) {
      BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListGoodsSelectAllEvent());
    }else{
      BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListGoodsCancelAllEvent());
    }
  }

  /// 点击删除
  void _onClickDelete(ConfirmDialog styleModel) async {

    //
    var result = await showDialog(context: context, child: FavoritesDialogWidget(styleModel: styleModel,));
    if(result == 1){
      BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListDeleteEvent());
    }
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    _refreshController = RefreshController();
    _slidableController = SlidableController();
    BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListInitEvent());
    super.initState();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    FavoritesPageNotifier favoritesPageNotifier = Provider.of<FavoritesPageNotifier>(context);

    if (null != favoritesPageNotifier) {
      isEditing = favoritesPageNotifier.isEditing;
      if(favoritesPageNotifier.editingTypeTag) {

        // BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListGoodsCancelAllEvent());
      }else{
        // if(favoritesPageNotifier.selectIndex == widget.currentIndex) {
          BlocProvider.of<FavoritesGoodsListBloc>(context).add(FavoritesGoodsListSearchEvent(favoritesPageNotifier?.keyword));
        // }
      }
    }
  }

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

  @override
  Widget build(BuildContext context) {
    return Listener(
      onPointerDown: (down)=> RouterUtil.hideKeyboard(context),
      child: Container(
        color: HexColor.fromHex('#F9F9F9'),
        child: BlocConsumer<FavoritesGoodsListBloc, FavoritesGoodsListState>(
          listener: (context, state) {},
          buildWhen: (prev, current) {
            if (current is FavoritesGoodsListRefreshSuccessState) {
              _refreshController?.refreshCompleted(resetFooterState: true);
              return false;
            }
            if (current is FavoritesGoodsListRefreshErrorState) {
              _refreshController?.refreshFailed();
              return false;
            }
            if (current is FavoritesGoodsListLoadSuccessState) {
              _refreshController?.loadComplete();
              return false;
            }
            if (current is FavoritesGoodsListLoadErrorState) {
              _refreshController?.loadNoData();
              return false;
            }
            if (current is FavoritesGoodsListErrorState) {
              return false;
            }
            if(current is FavoritesGoodsListNotSelectState){
              Fluttertoast.showToast(msg: '请选择需要删除的商品～');
              return false;
            }
            return true;
          },
          builder: (context, state) {
            /// 初始化失败，空数据
            if (state is FavoritesGoodsListInitErrorState) {
              return _buildEmptyWidget(widget?.styleModel);
            }

            /// 数据加载成功
            if (state is FavoritesGoodsListLoadedState) {
              // Logger.log('__FavoritesGoodsListWidgetContainerState ==== 刷新 size = ${state?.dataModel?.lists?.length}');
              return _buildGoodsListWidget(widget?.styleModel, state?.dataModel);
            }

            /// 骨架图
            return _buildSkeletonWidget(widget?.styleModel);
          },
        ),
      ),
    );
  }

  /// 有数据返回
  Widget _buildGoodsListWidget(FavoritesStyleModel styleModel, FavoritesGoodsListDataModel dataModel) {


    /// 如果数据删除了，则返回空视图
    int length = dataModel?.lists?.length ?? 0;
    if(length == 0) return _buildEmptyWidget(styleModel);

    return Stack(
      children: <Widget>[
        /// 数据
        SmartRefresher(
          controller: _refreshController,
          onRefresh: _onRefresh,
          onLoading: _onLoad,
          enablePullUp: true,
          enablePullDown: true,
          child: ListView.builder(
              padding: EdgeInsets.only(top: 7.5, left: 12.5, right: isEditing  ? 0 : 12.5),
              itemCount: dataModel.lists.length,
              itemBuilder: (context, index) {
                FavoritesGoodsListItemModel item = dataModel.lists[index];
                return Row(
                  children: <Widget>[
                    Visibility(
                      visible: isEditing ,
                      child: GestureDetector(
                        onTap: ()=> _onClickGoods(index),
                        behavior: HitTestBehavior.opaque,
                        child: Container(
                          height: 20,
                          width: 20,
                          margin: const EdgeInsets.only(right: 8),
                          child: CachedNetworkImage(
                            imageUrl: item.isSelect ? styleModel?.editLeftConfirmIcon : styleModel?.editLeftNoConfirmIcon,
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: Slidable(
                        key: Key(index.toString()),
                        controller: _slidableController,
                        enabled: !isEditing,
                        actionPane: SlidableDrawerActionPane(),
                        actionExtentRatio: 0.25,
                        closeOnScroll: false,
                        secondaryActions: <Widget>[
                          /// 分享
                          Padding(
                            padding: const EdgeInsets.only(bottom: 8),
                            child: IconSlideAction(
                              caption: '分享',
                              color: Colors.deepOrange,
                              icon: Icons.share,
                              onTap: () => _onSlideShare(),
                              closeOnTap: true,
                            ),
                          ),

                          /// 删除
                          Padding(
                            padding: const EdgeInsets.only(bottom: 8),
                            child: IconSlideAction(
                              caption: '删除',
                              color: Colors.red,
                              closeOnTap: true,
                              icon: Icons.delete,
                              onTap: () => _onSlideDelete(styleModel?.confirmDialog ,index),
                            ),
                          ),
                        ],
                        child: HomeGoodsItemSingle(
                          item,
                          HomeGoodsStyleModel()..listStyle = styleModel?.listStyle,
                          marginBottom: 8,
                          marginLeft: 0,
                          marginRight: 0,
                          marginTop: 0
                        ),
                      ),
                    )
                  ],
                );
              }),
        ),

        /// 编辑
        _buildEditrWidget(widget?.styleModel, dataModel),
      ],
    );
  }

  /// 编辑的底部Widget
  Widget _buildEditrWidget(FavoritesStyleModel styleModel, FavoritesGoodsListDataModel dataModel) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Visibility(
        visible: isEditing ,
        child: Container(
          padding: const EdgeInsets.only(left: 12.5, right: 12.5, top: 15.5, bottom: 15.5),
          width: double.infinity,
          decoration: BoxDecoration(
              color: HexColor.fromHex(styleModel?.bottom?.bgColor ?? '#FFFFFF'), borderRadius: BorderRadius.only(topRight: Radius.circular(10), topLeft: Radius.circular(10))),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              GestureDetector(
                onTap: () => _onClickAllSelecct(dataModel),
                behavior: HitTestBehavior.opaque,
                child: Row(
                  children: <Widget>[
                    Visibility(
                      visible: dataModel?.isAllSelect ?? false,
                      replacement: Container(
                        width: 20,
                        height: 20,
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(20), border: Border.all(color: HexColor.fromHex('#DCDCDC'), width: 0.5)),
                      ),
                      child: Container(
                        height: 20,
                        width: 20,
                        child: CachedNetworkImage(imageUrl: styleModel?.editLeftConfirmIcon ?? '',),
                      ),
                    ),
                    const SizedBox(width: 8),
                    Text(
                      styleModel?.bottom?.leftText ?? '全选',
                      style: TextStyle(
                        fontSize: 15,
                        color: HexColor.fromHex(styleModel?.bottom?.leftColor ?? '#333333'),
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
              GestureDetector(
                onTap: () => _onClickDelete(styleModel?.confirmDialog),
                behavior: HitTestBehavior.opaque,
                child: Text(
                  styleModel?.bottom?.rightText ?? '删除',
                  style: TextStyle(
                    fontSize: 15,
                    color: HexColor.fromHex(styleModel?.bottom?.rightColor ?? '#FF4242'),
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 空数据
  Widget _buildEmptyWidget(FavoritesStyleModel styleModel) {
    return SmartRefresher(
      controller: _refreshController,
      onRefresh: _onRefresh,
      enablePullDown: true,
      enablePullUp: false,
      child: Column(
        children: <Widget>[
          const SizedBox(height: 80),
          CachedNetworkImage(imageUrl: styleModel?.tabItemNotFoundImg ?? '', width: 188),
          const SizedBox(height: 22),
          Text(
            '暂时没有商品噢\n快去浏览收藏吧',
            style: TextStyle(fontSize: 15, color: HexColor.fromHex('#999999')),
          )
        ],
      ),
    );
  }

  /// 骨架图
  Widget _buildSkeletonWidget(FavoritesStyleModel styleModel) {
    return HomeGoodsSkeleton();
  }
}
