import 'package:flutter/material.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/bloc/bloc.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/bloc/home_quick_entry_repository.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/home_quick_entry_sk.dart';
import 'package:zhiying_base_widget/widgets/home/home_quick_entry/model/home_quick_entry_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

///
/// 首页的快速入口widget
///
class HomeQuickEntryWidget extends StatelessWidget {
  final Map<String, dynamic> model;

  HomeQuickEntryWidget(this.model);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<HomeQuickEntryBloc>(
      create: (_) => HomeQuickEntryBloc(repository: HomeQuickEntryRepository())..add(HomeQuickEntryInitEvent(model: model)),
      child: HomeQuickEntryWidgetContianer(),
    );
  }
}

class HomeQuickEntryWidgetContianer extends StatefulWidget {
  @override
  _HomeQuickEntryWidgetContianerState createState() => _HomeQuickEntryWidgetContianerState();
}

class _HomeQuickEntryWidgetContianerState extends State<HomeQuickEntryWidgetContianer> {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<HomeQuickEntryBloc, HomeQuickEntryState>(
      listener: (context, state) {
        Logger.log('数据加载出错');
      },
      buildWhen: (prev, current) {
        if (current is HomeQuickEntryErrorState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        if (state is HomeQuickEntryCachedState) {
          return _getMainWidget(state.model);
        }
        if (state is HomeQuickEntryLoadedState) {
          return _getMainWidget(state.model);
        }
        return HomeQuickEntrySkeleton();
      },
    );
  }


  Widget _getMainWidget(HomeQuickEntryModel model) {
    int dataSize = 15;//model?.type_normal?.length ?? 0; // 总数
    int columSize = 5;//int.parse(model?.colum_size ?? '5'); // 列数
    int rowSize =  2;//int.parse(model?.row_size ?? '2'); // 行数
    rowSize = columSize * rowSize <= dataSize ? rowSize : dataSize % columSize == 0 ? dataSize ~/ columSize : (dataSize ~/ columSize) +1;

    // 页数 总数 % （columSize * rowSize）
    int pageCount = dataSize % (rowSize * columSize) == 0 ? dataSize ~/ (rowSize * columSize) : (dataSize ~/ (rowSize * columSize)) + 1;

    // 进度条底部距离
    const double bottomSize = 15.0;
    // 子元素之间的下边距
    const double itemPadding = 15.0;
    // 图片的高度
    const double iconHeight = 40.0;
    // 一个标题➕边距的高度
    const double titleHeight = 20;

    // 总体的高度 == 行数 * （图片高度 + 标题高度 + 元素之间的边距) + 上下内边距
    double containerHeight = rowSize * (iconHeight + titleHeight + itemPadding*2) + (bottomSize*2);


    return Container(
      // padding: const EdgeInsets.only(bottom: bottomSize, top: bottomSize),
      // padding: const EdgeInsets.only(top: bottomSize),
      color: Colors.green,
      height: containerHeight,
      width: double.infinity,
      child: Column(
        children: <Widget>[
          Expanded(
            child: Container(
              // color: Colors.yellowAccent,
              child: Swiper(
                itemHeight: double.infinity,
                itemWidth: double.infinity,
                duration: 100,
                scrollDirection: Axis.horizontal,
                loop: false,
                containerWidth: double.infinity,
                containerHeight: 250,
                index: 0,
                itemCount: pageCount,
                // 页数
                itemBuilder: (BuildContext context, int index) {
                  return HomeQuickEntrySwiperItem(
                    data: model?.type_normal,
                    dataSize: dataSize,
                    showDataSize: columSize * rowSize,
                    page: index,
                    columSize: columSize,
                    rowSize: rowSize,
                    itemPadding: itemPadding,
                  );
                },
                pagination: _SwiperCustomPagination(pageCount),
              ),
            ),
          )
        ],
      ),
    );
  }

  // 自定义进度条
  SwiperPlugin _SwiperCustomPagination(int pageCount) {
    List list = [];
    for (int i = 0; i < pageCount; i++) {
      list.add(i);
    }

    return SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
      return Align(
        alignment: Alignment(0.0, 1),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: list.map((index) {
            var borderRadius;
            if (index == 0) {
              borderRadius = BorderRadius.only(topLeft: Radius.circular(2), bottomLeft: Radius.circular(2));
            }
            if (index == list.length - 1) {
              borderRadius = BorderRadius.only(topRight: Radius.circular(2), bottomRight: Radius.circular(2));
            }

            if (index == config.activeIndex) {
              borderRadius = BorderRadius.all(Radius.circular(2));
            }

            return Container(
              height: 4,
              width: 25,
              decoration: BoxDecoration(borderRadius: borderRadius, color: index == config.activeIndex ? HexColor.fromHex('#FF4242') : HexColor.fromHex('#FFFFFF')),
            );
          }).toList(),
        ),
      );
    });
  }
}

///
/// 快速入口一页的显示
///
class HomeQuickEntrySwiperItem extends StatelessWidget {
  final List data;
  final int page; // 当前的页数
  final int showDataSize; // 显示的数据
  final int columSize; // 列数
  final int rowSize; // 行数
  final int dataSize;
  final double itemPadding;

  const HomeQuickEntrySwiperItem({this.page, this.data, this.showDataSize, this.columSize, this.rowSize, this.itemPadding, this.dataSize});

  @override
  Widget build(BuildContext context) {
    // 当前显示的个数
    // int itemCount = (data.length - page * showDataSize) >= showDataSize ? showDataSize : (data.length - page * showDataSize);
    int itemCount = (dataSize - page * showDataSize) >= showDataSize ? showDataSize : (dataSize - page * showDataSize);
    print('${itemCount}');
    return Container(
      // color: Colors.cyan,
      height: double.infinity,
      width: double.infinity,
      // margin: const EdgeInsets.only(bottom: 15),
      child: GridView.builder(
          cacheExtent: double.infinity,
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          primary: false,
          padding: const EdgeInsets.only(top: 15),
          reverse: false,
          addAutomaticKeepAlives: false,
          addRepaintBoundaries: false,
          physics: NeverScrollableScrollPhysics(),
          itemCount: itemCount,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: columSize,
            childAspectRatio: 1,
            crossAxisSpacing: 0,
            mainAxisSpacing: 0,
          ),
          itemBuilder: (context, i) {
            // return HomeQuickEntryItem(data: data[itemCount == showDataSize ? page * showDataSize + i : page == 0 ? page + i : page * showDataSize + i], itemPaddding: itemPadding,);
            // 最后一行
            bool isLast =  i >= (rowSize -1)  * columSize;
            return HomeQuickEntryItem(data: null, itemPaddding: itemPadding, isLastRow: isLast,);
          }),
    );
  }
}

///
/// 快速入口的样式
///
class HomeQuickEntryItem extends StatelessWidget {
  final TypeNormal data;
  final double itemPaddding;
  final bool isLastRow;

  HomeQuickEntryItem({this.data, this.itemPaddding, this.isLastRow});

  /// 子图标的点击
  _itemOnClick(context) {
    Navigator.push(context, MaterialPageRoute(builder: (context) {
      return PageFactory.create('login', null);
    }));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _itemOnClick(context),
      child: Container(
        margin: EdgeInsets.only(bottom: isLastRow ? 0 :0),
        color: Colors.red,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
            // 图片
            MyNetWorkImage(data?.img?? 'https://profile.csdnimg.cn/3/3/0/3_canhuashu'),

            Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  data?.title_1 ?? '京东',
                  style: TextStyle(color: HexColor.fromHex('#666666'), fontSize: 20.sp),
                )),

            Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  data?.title_1 ?? '京东',
                  style: TextStyle(color: HexColor.fromHex('#666666'), fontSize: 20.sp),
                )),
//          SizedBox(height: 25.h,)
          ],
        ),
      ),
    );
  }
}

///
/// 图片build 优化
///
class MyNetWorkImage extends StatelessWidget {

  final String imgUrl;
  const MyNetWorkImage(this.imgUrl);

  @override
  Widget build(BuildContext context) {
    return RepaintBoundary(
      child: CachedNetworkImage(
        width: 40,
        imageUrl: imgUrl,
      ),
    );
  }
}
