import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/goods_details_page.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/home_goods_item.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_model.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_base_widget/widgets/search_result/goods_list/bloc/search_result_goods_list_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

class SearchResultGoodsListWidget extends StatefulWidget {
  final Map<String, dynamic> data;
  HomeGoodsStyleModel style;

  SearchResultGoodsListWidget(this.data) {
    try {
      style = HomeGoodsStyleModel.fromJson(jsonDecode(data['data']));
    } catch (e) {}
  }

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

class _SearchResultGoodsListWidgetState extends State<SearchResultGoodsListWidget> {
  @override
  Widget build(BuildContext context) {
    // return BlocProvider<SearchResultGoodsListBloc>(
    //   create: (_) => SearchResultGoodsListBloc(repository: SearchResultGoodsListRepository())..add(SearchResultGoodsListInitEvent(model: widget?.data)),
    //     child: SearchResultGoodsListWidgetContainer(),
    // );
    return SearchResultGoodsListWidgetContainer(widget?.data, widget?.style);
  }
}

class SearchResultGoodsListWidgetContainer extends StatefulWidget {
  final Map<String, dynamic> data;
  final HomeGoodsStyleModel style;

  const SearchResultGoodsListWidgetContainer(this.data, this.style);

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

/// 商品列表
class _SearchResultGoodsListWidgetContainerState extends State<SearchResultGoodsListWidgetContainer> {
  /// 显示样式
  bool _isShowOneColumn = true;

  /// 下拉刷新
  void _onRefersh() async {
    BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListOnRefreshEvent());
  }

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

  /// 跳转商品详情
  void _openGoodsDetailsPage() {
    Navigator.push(context, MaterialPageRoute(builder: (_) => GoodsDetailsPage(null)));
  }

  @override
  void initState() {
    /// 初始化
    BlocProvider.of<SearchResultGoodsListBloc>(context).add(SearchResultGoodsListInitEvent());
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<SearchResultGoodsListBloc, SearchResultGoodsListState>(
      listener: (BuildContext context, SearchResultGoodsListState state) {
        if (state is SearchResultGoodsListErrorState) {
          print('数据加载出错');
        }
      },
      buildWhen: (previous, current) {
        /// 数据加载出错不进行build
        if (current is SearchResultGoodsListErrorState) {
          return false;
        }

        return true;
      },
      builder: (context, state) {
        if (state is SearchResultGoodsListLoadedState) {
          return _getMainWidget(state?.model, widget?.style);
        }
        if (state is SearchResultGoodsListChangeStyleState) {
          _isShowOneColumn = state.isShowOneColumn;
          return _getMainWidget(state?.model, widget?.style);
        }

        /// 骨架屏幕
        return HomeGoodsSkeleton();
      },
    );
  }

  /// 获取主视图
  Widget _getMainWidget(List<HomeGoodsModel> goods, HomeGoodsStyleModel styleModel) {
    int column = _isShowOneColumn ? 1 : 2;

    return ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemCount: goods?.length ?? 0,
        itemBuilder: (context, index) {
          if (column == 1) {
            return HomeGoodsItemSingle(
              goods[index],
              styleModel,
              data: widget.data,
            );
          } else {
            // return Container(color: Colors.red, height: 126,margin: EdgeInsets.all(10),);
            return Padding(
              padding: const EdgeInsets.only(left: 5, right: 5),
              child: Row(
                children: List.generate(column, (c) {
                  int i = index * column + c;
                  return Expanded(
                    child: i < goods.length
                        ? HomeGoodsItem(
                            goods[i],
                            styleModel,
                            data: widget.data,
                          )
                        : Container(),
                  );
                }).toList(),
              ),
            );
          }
        });
  }

  /// 单列
// Widget _getSignleWidget(List<HomeGoodsModel> goods, HomeGoodsStyleModel styleModel) {
//   return ListView.builder(
//       shrinkWrap: true,
//       physics: NeverScrollableScrollPhysics(),
//       itemCount: goods.length,
//       itemBuilder: (context, index) {
//         if (column == 1) {
//           return HomeGoodsItemSingle(
//             goods[index],
//             styleModel,
//             data: widget.data,
//           );
//         } else {
//           // return Container(color: Colors.red, height: 126,margin: EdgeInsets.all(10),);
//           return Padding(
//             padding: const EdgeInsets.only(left: 5, right: 5),
//             child: Row(
//               children: List.generate(column, (c) {
//                 int i = index * column + c;
//                 return Expanded(
//                   child: i < goods.length
//                       ? HomeGoodsItem(
//                           goods[i],
//                           _style,
//                           data: widget.data,
//                         )
//                       : Container(),
//                 );
//               }).toList(),
//             ),
//           );
//         }
//       });
//
//   return HomeGoodsItemSingle(model, styleModel);
// }
//
// /// 双列
// Widget _getTowWidget(List<HomeGoodsModel> goods, HomeGoodsStyleModel styleModel) {
//   int column = 2;
//   int count = (goods.length / column).ceil();
//
//   return Container(
//     child: Text('22222222'),
//   );
// }
}
