import 'dart:async';
import 'dart:math';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:tab_indicator_styler/tab_indicator_styler.dart';
import 'package:zhiying_base_widget/widgets/primary_page_view/primary_page_view.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'custom_quick_entry_sk.dart';
import 'model/custom_quick_entry_model.dart';
import 'bloc/bloc.dart';

class CustomQuickEntry extends StatelessWidget {
  final Map<String, dynamic> model;

  const CustomQuickEntry(this.model);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<CustomQuickEntryBloc>(
      create: (_) {
        return CustomQuickEntryBloc(repository: CustomQuickEntryRepository())..add(CustomQuickEntryInitEvent(model: model));
      },
      child: _CustomQuickEntryContainer(model),
    );
  }
}

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

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

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

class __CustomQuickEntryContainerState extends State<_CustomQuickEntryContainer> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  /// Icon点击事件
  void _itemIconClick(ListStyle model) {
    print("item type = ${model.skipIdentifier}");
    // Navigator.push(context, CupertinoPageRoute(builder: (_) => CommonPage(null)));
    RouterUtil.route(model, model.toJson(), context);
  }

  SwiperController _controller;

  @override
  void initState() {
    _controller = SwiperController();

    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();

    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CustomQuickEntryBloc, CustomQuickEntryState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (prev is CustomQuickEntryLoadedState) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print("构建");
        if (state is CustomQuickEntryCachedState) {
          return _getMainWidget(state.model);
        }
        if (state is CustomQuickEntryLoadedState) {
          if (state.model.isShowCategory == "1") {
            return CustomQuickCateEntry(
              model: state.model,
            );
          } else {
            return _getMainWidget(state.model);
          }
        }
        if (state is CustomQuickEntryErrorState) {
          return Container();
        }
        return CustomQuickEntrySkeleton();
      },
    );
  }

  Widget _getMainWidget(CustomQuickEntryModel model) {
    // 数据总数
    int totalDataSize = model?.listStyle?.length ?? 0;

    // 展示的总行数
    int totalRowSize = int.parse(model?.rowSize ?? '1');

    // 展示的列数
    int columSize = int.parse(model?.columSize ?? '5');

    //计算实际显示行数
    if (totalRowSize * columSize > totalDataSize) {
      for (int index = 1; index <= totalRowSize; index++) {
        if (index * columSize >= totalDataSize) {
          totalRowSize = index;
          break;
        }
      }
    }
    print("行数" + totalRowSize.toString());

    // 图标的高度
    double iconHeight = 40.0;
    // 标题的高度
    double titleHeight = 20.0;

    // 子元素的高度
    double itemHeight = iconHeight;

    // 如果有一级标题
    if (!EmptyUtil.isEmpty(model?.isShowTitle) && model.isShowTitle == '1') {
      itemHeight = iconHeight + titleHeight;
    }

    //如果有二级标题
    if (!EmptyUtil.isEmpty(model?.isShowSubTitle) && model.isShowSubTitle == '1') {
      itemHeight = iconHeight + titleHeight * 2;
    }

    // 进度条的边距
    double barMargin = 15.0;
    // 总页数
    int totalPage = totalDataSize % (totalRowSize * columSize) == 0 ? totalDataSize ~/ (totalRowSize * columSize) : (totalDataSize ~/ (totalRowSize * columSize)) + 1;

    Logger.log('totalPage = ' + totalPage?.toString());
    // 总体高度 = 行数 * (子元素高度 + 边距高度) + 进度条的高度
    double totalHeight = totalRowSize * (itemHeight + barMargin);
    if (totalPage > 1 && !EmptyUtil.isEmpty(model?.pagination) && model.pagination != 'type_null' /*model.pagination_open == '0'*/) {
      totalHeight = totalRowSize * (itemHeight + barMargin) + 8;
    }

    // 分类导航高度
    double categoryHeight = 24;
    // 分类导航到多眼导航的边距
    double categoryBottomMargin = 15.0;
    bool hasCategory = false;
    // if(!EmptyUtil.isEmpty(model?.typeList) && model.typeList.length >= 2){
    //   totalHeight = totalHeight + categoryHeight + categoryBottomMargin;
    //   hasCategory = true;
    // }

    // 如果有左上角标题
    double moduleTitleHeight = 22 + 10.0;
    if (!EmptyUtil.isEmpty(model?.moduleTitleName)) {
      totalHeight = totalHeight + moduleTitleHeight;
    }

    double marginLeftRight = model?.isLeftRightMargin == "1" ? double.tryParse(model?.leftRightMargin ?? "0") : 0;
    double marginTop = model?.isTopMargin == "1" ? double.tryParse(model?.topMargin ?? "0") : 0;
    return Container(
      margin: EdgeInsets.only(top: marginTop, left: marginLeftRight, right: marginLeftRight),
      decoration: BoxDecoration(
          color: HexColor.fromHex(model?.bgColor ?? ''),
          //color: Colors.green,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(ParseUtil.stringParseDouble(model?.topRightRadius)),
            topLeft: Radius.circular(ParseUtil.stringParseDouble(model?.topLeftRadius)),
            bottomLeft: Radius.circular(ParseUtil.stringParseDouble(model?.bottomLeftRadius)),
            bottomRight: Radius.circular(ParseUtil.stringParseDouble(model?.bottomRightRadius)),
          )),
      child: Container(
        margin: EdgeInsets.only(top: !hasCategory ? 15 : 0, bottom: totalPage > 1 ? 8 : 0),
        height: totalHeight,
        // 总体高度
        width: double.infinity,
        // color: HexColor.fromHex(widget?.model['bg_color']),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            // 左上角标题
            Visibility(
              visible: !EmptyUtil.isEmpty(model?.moduleTitleName),
              child: Padding(
                  padding: const EdgeInsets.only(left: 12.5, bottom: 10),
                  child: Text(model?.moduleTitleName ?? '', style: TextStyle(color: HexColor.fromHex(model?.moduleTitleColor), fontWeight: FontWeight.bold, fontSize: 15))),
            ),

            // icon
            Expanded(
              child: Container(
                width: double.infinity,
                height: hasCategory ? totalHeight - categoryHeight - categoryBottomMargin : totalHeight,
                child: Swiper(
                  controller: _controller,
                  itemCount: totalPage,
                  loop: false,
                  itemBuilder: (context, index) {
                    return Container(
                      height: double.infinity,
                      width: double.infinity,
                      padding: const EdgeInsets.symmetric(horizontal: 4),
                      child: _getPageWidget(
                        iconHeight: iconHeight,
                        titleHeight: titleHeight,
                        totalDataSize: totalDataSize,
                        totalPage: totalPage,
                        currentPage: index,
                        totalRowSize: totalRowSize,
                        columSize: columSize,
                        model: model,
                        itemHeight: itemHeight,
                      ),
                    );
                  },
                  pagination: totalPage <= 1 ? null : _getSwiperPaginationContorl(model, totalPage),
                ),
              ),
            )

            // Container(
            //   margin: EdgeInsets.only(bottom: categoryBottomMargin),
            //   padding: const EdgeInsets.only(left: 12.5, right: 12.5),
            //   height: categoryHeight,
            //   width: double.infinity,
            //   child: TabBar(
            //     controller: tabController,
            //     labelColor: HexColor.fromHex('#FFFF4242'),
            //     unselectedLabelColor: HexColor.fromHex('#FF3C3C3C'),
            //     // indicatorColor: HexColor.fromHex('#FFFF4242'),
            //     indicator: MaterialIndicator(
            //       color: HexColor.fromHex('#FFFF4242'),
            //       height: 22,
            //       bottomRightRadius: 10,
            //       bottomLeftRadius: 10,
            //       topRightRadius: 10,
            //       topLeftRadius: 10,
            //       tabPosition: TabPosition.top,
            //       horizontalPadding: 8,
            //       // paintingStyle: PaintingStyle.stroke
            //     ),
            //     tabs: List.generate(5, (index) => Container(width: 50, child: Center(child: Text('热门', style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold))))),
            //   ),
            // ),

            // Expanded(
            //   child: TabBarView(
            //     controller: tabController,
            //     children: List.generate(5, (index) => Container(
            //       width: double.infinity,
            //       height: hasCategory ? totalHeight - categoryHeight - categoryBottomMargin : totalHeight ,
            //       child: Swiper(
            //         controller: _controller,
            //         itemCount: totalPage,
            //         loop: false,
            //         itemBuilder: (context, index) {
            //           return Container(
            //             height: double.infinity,
            //             width: double.infinity,
            //             padding: const EdgeInsets.symmetric(horizontal: 4),
            //             child: _getPageWidget(
            //               iconHeight: iconHeight,
            //               titleHeight: titleHeight,
            //               totalDataSize: totalDataSize,
            //               totalPage: totalPage,
            //               currentPage: index,
            //               totalRowSize: totalRowSize,
            //               columSize: columSize,
            //               model: model,
            //               itemHeight: itemHeight,
            //             ),
            //           );
            //         },
            //         pagination: totalPage <= 1 ? null : _getSwiperPaginationContorl(model, totalPage),
            //       ),
            //     )),
            //   ),
            // )
          ],
        ),
      ),
    );
  }

  /// 页的数据
  Widget _getPageWidget(
      {double titleHeight, double iconHeight, int totalPage, int currentPage, int columSize, int totalRowSize, int totalDataSize, CustomQuickEntryModel model, double itemHeight}) {
    List rowList = [];
    for (int i = 0; i < totalRowSize; i++) {
      rowList.add(i);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: rowList.map((currentRow) {
        return Container(
          padding: EdgeInsets.only(bottom: 15),
          width: double.infinity,
          child: _getRowWidget(
              titleHeight: titleHeight,
              iconHeight: iconHeight,
              totalPage: totalPage,
              currentPage: currentPage,
              columSize: columSize,
              totalRowSize: totalRowSize,
              totalDataSize: totalDataSize,
              model: model,
              currentRow: currentRow,
              itemHeight: itemHeight),
        );
      }).toList(),
    );
  }

  /// 行的数据
  Widget _getRowWidget(
      {double titleHeight,
      double iconHeight,
      int totalPage,
      int currentPage,
      int columSize,
      int totalRowSize,
      int totalDataSize,
      CustomQuickEntryModel model,
      int currentRow,
      double itemHeight}) {
    List itemList = [];
    for (int i = 0; i < columSize; i++) {
      itemList.add(i);
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: itemList.map((currentIndex) {
        return _getColumWidget(
          titleHeight: titleHeight,
          iconHeight: iconHeight,
          totalPage: totalPage,
          currentPage: currentPage,
          totalDataSize: totalDataSize,
          columSize: columSize,
          totalRowSize: totalRowSize,
          model: model,
          currentRow: currentRow,
          currentColum: currentIndex,
          itemHeight: itemHeight,
        );
      }).toList(),
    );
  }

  /// item 的数据
  Widget _getColumWidget(
      {double titleHeight,
      double iconHeight,
      int totalPage,
      int currentPage,
      int columSize,
      int totalRowSize,
      int totalDataSize,
      CustomQuickEntryModel model,
      int currentRow,
      int currentColum,
      double itemHeight}) {
    // 当前index = 当前的页数+1 * 当前的行数 + 当前的列数
    // int currentIndex = (currentPage + 1) * currentRow  + currentColum  + currentRow*columSize;
    // int currentIndex = currentPage != 0 ? currentPage * (columSize * totalRowSize) + columSize + currentRow * columSize :
    //     currentColum + currentRow * columSize;

    // 当前元素的下表 =  当前的列数 +  当前的行数 * 列数 + 当前的页数 * 当前的行数 + 当前的列数
    int currentIndex = currentColum + currentRow * columSize + currentPage * totalRowSize * columSize;

    // print('current Index  sss =  $currentIndex');

    if (currentIndex >= totalDataSize) {
      return Container(
        height: itemHeight,
        width: 60,
      );
    }

    ListStyle item = model?.listStyle[currentIndex];

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        _itemIconClick(item);
        },
      child: Container(
        height: itemHeight,
        width: 60,
        // color: Colors.red,
        child: Column(
          children: <Widget>[
            /// 图标
            MyNetWorkImage(
              item.img,
              width: 40,
            ),

            /// 一级标题
            Visibility(
              visible: !EmptyUtil.isEmpty(model?.isShowTitle) && model.isShowTitle == '1',
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  item?.title ?? '',
                  style: TextStyle(fontSize: 10, color: HexColor.fromHex(model?.titleColor)),
                ),
              ),
            ),

            /// 二级标题
            Visibility(
              visible: !EmptyUtil.isEmpty(model?.isShowSubTitle) && model.isShowSubTitle == '1',
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  item?.subTitle ?? '',
                  style: TextStyle(fontSize: 10, color: HexColor.fromHex(model?.subTitleColor)),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// 进度条
  SwiperPlugin _getSwiperPaginationContorl(CustomQuickEntryModel model, int pageCount) {
    if (EmptyUtil.isEmpty(model?.pagination) || model.pagination == 'type_null' /*model.pagination_open == '0'*/) {
      return null;
    }

    if (model.pagination == 'type_point') {
      // 点点点进度条
      return _swiperPaginationDot(model);
    } else {
      // 自定义进度条
      return _swiperCustomPagination(pageCount);
    }
  }

  // 进度条 圆形
  SwiperPagination _swiperPaginationDot(CustomQuickEntryModel model) {
    return SwiperPagination(
        margin: const EdgeInsets.only(),
        builder: DotSwiperPaginationBuilder(
            color: HexColor.fromHex(model?.paginationUnselectColor), activeColor: HexColor.fromHex(model?.paginationSelectColor), size: 8, activeSize: 8));
  }

  // 自定义进度条 条形
  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(),
        ),
      );
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

///
/// 图片build 优化
///
class MyNetWorkImage extends StatelessWidget {
  final String imgUrl;
  final double width;

  const MyNetWorkImage(this.imgUrl, {this.width = 40});

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

// Widget _getMainWidget(CustomQuickEntryModel model) {
//   // 数据总数
//   int totalDataSize = model?.listStyle?.length ?? 0;
//
//   // 展示的总行数
//   int totalRowSize = 1;int.parse(model?.rowSize ?? '1');
//
//   // 展示的列数
//   int columSize = 5;int.parse(model?.columnSize ?? '5');
//
//   // 图标的高度
//   double iconHeight = 40.0;
//   // 标题的高度
//   double titleHeight = 20.0;
//
//   // 子元素的高度
//   double itemHeight = iconHeight;
//
//   // 如果有一级标题
//   if (!EmptyUtil.isEmpty(model?.isShowTitle) && model.isShowTitle == '1') {
//     itemHeight = iconHeight + titleHeight;
//   }
//
//   //如果有二级标题
//   if (!EmptyUtil.isEmpty(model?.isShowSubTitle) && model.isShowSubTitle == '1') {
//     itemHeight = iconHeight + titleHeight * 2;
//   }
//
//   // 进度条的边距
//   double barMargin = 15.0;
//   // 总页数
//   int totalPage = totalDataSize % (totalRowSize * columSize) == 0 ? totalDataSize ~/ (totalRowSize * columSize) : (totalDataSize ~/ (totalRowSize * columSize)) + 1;
//
//   // 总体高度 = 行数 * (子元素高度 + 边距高度) + 进度条的高度
//   double totalHeight = totalRowSize * (itemHeight + barMargin) + 4;
//   if (!EmptyUtil.isEmpty(model?.pagination) && model.pagination != 'type_null' /*model.pagination_open == '0'*/) {
//     totalHeight = totalRowSize * (itemHeight + barMargin);
//   }
//
//   return Container(
//     color: HexColor.fromHex(widget?.model['bg_color']),
//     // color: Colors.yellow,
//     child: Container(
//       margin: EdgeInsets.only(top: 15, bottom: totalPage > 1 ? 15 : 0),
//       height: totalHeight,
//       // 总体高度
//       width: double.infinity,
//       color: HexColor.fromHex(widget?.model['bg_color']),
//       child: Swiper(
//         controller: _controller,
//         itemCount: totalPage,
//         loop: false,
//         itemBuilder: (context, index) {
//           return Container(
//             height: double.infinity,
//             width: double.infinity,
//             padding: const EdgeInsets.symmetric(horizontal: 12.5),
//             child: _getPageWidget(
//               iconHeight: iconHeight,
//               titleHeight: titleHeight,
//               totalDataSize: totalDataSize,
//               totalPage: totalPage,
//               currentPage: index,
//               totalRowSize: totalRowSize,
//               columSize: columSize,
//               model: model,
//               itemHeight: itemHeight,
//             ),
//           );
//         },
//         pagination: totalPage <= 1 ? null : _getSwiperPaginationContorl(model, totalPage),
//       ),
//     ),
//   );
// }

}

class CustomQuickCateEntry extends StatefulWidget {
  final CustomQuickEntryModel model;

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

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

class _CustomQuickCateEntryState extends State<CustomQuickCateEntry> with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  TabController tabController;



  bool isOnTap = false;

  Timer onTapTimer;

  SwiperController _controller;

  List<PageItem> pageList = List();

  @override
  void initState() {

    if (widget?.model != null) {
      tabController = TabController(length: widget?.model?.typeList?.length ?? 0, vsync: this);
      tabController.addListener(() {});
    }
    _controller = SwiperController();


    super.initState();
  }

  @override
  void dispose() {
    tabController?.dispose();

    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    print("构建数据");
    return _getMainHasCategoryWidget(widget?.model);
  }

  Widget _getMainHasCategoryWidget(CustomQuickEntryModel model) {
    bool hasCategory = false;
    if (!EmptyUtil.isEmpty(model?.typeList) && model.typeList.length >= 2) {
      hasCategory = true;
    }

    int maxTotal = 0;

    ///分类
    if (model.typeList != null) {
      for (var item in model?.typeList) {
        item.listStyle = List();

        for (var listItem in model?.listStyle) {
          if (listItem?.typeListKey == item.key) {
            item.listStyle.add(listItem);
          }
        }
        if (item.listStyle.length > maxTotal) {
          maxTotal = item.listStyle.length;
        }
      }
    }
    pageList.clear();

    // 数据总数
    int totalDataSize = maxTotal;

    // 展示的列数
    int columSize = int.parse(model?.columSize ?? '5');

    // 展示的总行数
    int totalRowSize = int.parse(model?.rowSize ?? '2');

    //计算实际显示行数
    if (totalRowSize * columSize > totalDataSize) {
      for (int index = 1; index <= totalRowSize; index++) {
        if (index * columSize >= totalDataSize) {
          totalRowSize = index;
          break;
        }
      }
    }


    //计算实际显示行数
    print("行数" + totalRowSize.toString());

    // 图标的高度
    double iconHeight = 40;
    // 标题的高度
    double titleHeight = 20.0;

    // 子元素的高度
    double itemHeight = iconHeight;

    // 如果有一级标题
    if (!EmptyUtil.isEmpty(model?.isShowTitle) && model.isShowTitle == '1') {
      itemHeight = iconHeight + titleHeight;
    }

    //如果有二级标题
    if (!EmptyUtil.isEmpty(model?.isShowSubTitle) && model.isShowSubTitle == '1') {
      itemHeight = iconHeight + titleHeight * 2;
    }

    // 进度条的边距
    double barMargin = 10.0;
    // 总页数
    int totalPage = totalDataSize % (totalRowSize * columSize) == 0 ? totalDataSize ~/ (totalRowSize * columSize) : (totalDataSize ~/ (totalRowSize * columSize)) + 1;

    Logger.log('totalPage = ' + totalPage?.toString());
    // 总体高度 = 行数 * (子元素高度 + 边距高度) + 进度条的高度
    double totalHeight = totalRowSize * (itemHeight + barMargin);
    if (totalPage > 1 && !EmptyUtil.isEmpty(model?.pagination) && model.pagination != 'type_null' /*model.pagination_open == '0'*/) {
      totalHeight = totalRowSize * (itemHeight + barMargin) + 6;
    }

    // 分类导航高度
    double categoryHeight = 24;
    // 分类导航到多眼导航的边距
    double categoryBottomMargin = 20.0;

    if (!EmptyUtil.isEmpty(model?.typeList) && model.typeList.length >= 2) {
      totalHeight = totalHeight + categoryHeight + categoryBottomMargin;
      hasCategory = true;
    }

    // 如果有左上角标题
    double moduleTitleHeight = 22 + 10.0;
    if (!EmptyUtil.isEmpty(model?.moduleTitleName)) {
      totalHeight = totalHeight + moduleTitleHeight;
    }

    double marginLeftRight = model?.isLeftRightMargin == "1" ? double.tryParse(model?.leftRightMargin ?? "0") : 0;
    double marginTop = model?.isTopMargin == "1" ? double.tryParse(model?.topMargin ?? "0") : 0;

    int currentTypeIndex = 0;

    for (var item in model.typeList) {
      if ((item?.listStyle?.length ?? 0) == 0) {
        pageList.add(PageItem(index: currentTypeIndex, listStyle: List()));
        currentTypeIndex++;
        continue;
      }

      if (item.listStyle.length > totalRowSize) {
        for (int index = 0; index < (item.listStyle.length / (columSize * totalRowSize)).ceil(); index++) {
          var list = List<ListStyle>();
          var startIndex = index * columSize * totalRowSize;
          for (var i = 0; i < columSize * totalRowSize; i++) {
            if (item.listStyle.length > startIndex + i) {
              list.add(item.listStyle[startIndex + i]);
            } else {
              break;
            }
          }
          pageList.add(PageItem(index: currentTypeIndex, listStyle: list));
        }
      } else {
        pageList.add(PageItem(index: currentTypeIndex, listStyle: item?.listStyle));
      }
      currentTypeIndex++;
    }

    return Container(
      margin: EdgeInsets.only(top: marginTop, left: marginLeftRight, right: marginLeftRight),
      decoration: BoxDecoration(
          color: HexColor.fromHex(model?.bgColor ?? ''),
          //color: Colors.green,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(ParseUtil.stringParseDouble(model?.topRightRadius)),
            topLeft: Radius.circular(ParseUtil.stringParseDouble(model?.topLeftRadius)),
            bottomLeft: Radius.circular(ParseUtil.stringParseDouble(model?.bottomLeftRadius)),
            bottomRight: Radius.circular(ParseUtil.stringParseDouble(model?.bottomRightRadius)),
          )),
      child: Container(
        height: totalHeight + (totalRowSize * 5) + 5+5,
        margin: EdgeInsets.only(bottom: model?.pagination == "type_null" ? 0 : 8),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            hasCategory
                ? Container(
                    height: categoryHeight,
                    margin: EdgeInsets.only(top: 10, bottom: 15),
                    child: TabBar(
                      isScrollable: true,
                      onTap: (value) {
                        onTapTimer?.cancel();
                        isOnTap = true;
                        onTapTimer = Timer(Duration(milliseconds: 300), () {
                          isOnTap = false;
                        });
                        int current = 0;
                        for (var pageItem in pageList) {
                          if (pageItem.index == value) {
                            _controller.move(current);
                            print("跳转到" + current.toString());
                            break;
                          }
                          current++;
                        }
                      },
                      labelColor: HexColor.fromHex("#FFFFFF"),
                      unselectedLabelColor: HexColor.fromHex("#FF333333"),
                      labelStyle: TextStyle(fontSize: 14),
                      tabs: _buildTab(model,columSize,marginLeftRight),
                      labelPadding: EdgeInsets.only(left: 16,right: 16),
                      controller: tabController,
                      indicatorSize: TabBarIndicatorSize.label,
                      indicatorColor: Colors.transparent,
                      indicator: BubbleTabIndicator(indicatorColor: HexColor.fromHex("#FF4242")),
                    ),
                  )
                : Container(),
            Expanded(
                child: Swiper(
              controller: _controller,
              itemCount: pageList.length ?? 0,
              physics: BouncingScrollPhysics(),
              loop: false,
              onIndexChanged: (currentIndex) {
                if (isOnTap) {
                  return;
                }
                tabController.animateTo(pageList[currentIndex].index);
              },
              itemBuilder: (context, index) {
                var totalDataSize = pageList[index].listStyle.length ?? 0;
                return Container(
                  height: double.infinity,
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 0),
                  child: _getCategoryPageWidget(
                    iconHeight: iconHeight,
                    titleHeight: titleHeight,
                    totalDataSize: totalDataSize,
                    totalPage: pageList?.length ?? 0,
                    currentPage: index,
                    totalRowSize: totalRowSize,
                    columSize: columSize,
                    model: model,
                    itemHeight: itemHeight,
                  ),
                );
              },
              pagination: _getSwiperPaginationContorl(model, model?.typeList?.length ?? 0),
            )),
          ],
        ),
      ),
    );
  }

  _buildTab(CustomQuickEntryModel model,int columSize,double marginLeft) {
    List<Widget> listWidget = List();
    var maxWidth = ((MediaQuery.of(context).size.width-marginLeft*2)-(32*columSize)) / columSize;
    print("测试"+columSize.toString());
    for (var item in model?.typeList) {
      listWidget.add(Tab(
        child: Container(
          width: maxWidth,
          child: Center(child: Text(item.name??"")),
        ),
      ));
    }
    return listWidget;
  }

  /// 获取有分类页
  _getCategoryPageWidget(
      {double titleHeight, double iconHeight, int totalPage, int currentPage, int columSize, int totalRowSize, int totalDataSize, CustomQuickEntryModel model, double itemHeight}) {
    List rowList = [];
    for (int i = 0; i < totalRowSize; i++) {
      rowList.add(i);
    }

    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: rowList.map((currentRow) {
        return Container(
          padding: EdgeInsets.only(bottom: 15, top: 0),
          width: double.infinity,
          child: _buildHasCategoryRowWidget(
              titleHeight: titleHeight,
              iconHeight: iconHeight,
              totalPage: totalPage,
              currentPage: currentPage,
              columSize: columSize,
              totalRowSize: totalRowSize,
              totalDataSize: totalDataSize,
              model: model,
              currentRow: currentRow,
              itemHeight: itemHeight),
        );
      }).toList(),
    );
  }

  ///有分类行构建
  Widget _buildHasCategoryRowWidget(
      {double titleHeight,
      double iconHeight,
      int totalPage,
      int currentPage,
      int columSize,
      int totalRowSize,
      int totalDataSize,
      CustomQuickEntryModel model,
      int currentRow,
      double itemHeight}) {
    List itemList = [];
    for (int i = 0; i < columSize; i++) {
      itemList.add(i);
    }

    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceAround,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: itemList.map((currentIndex) {
        return _getHasCategoryColumWidget(
          titleHeight: titleHeight,
          iconHeight: iconHeight,
          totalPage: totalPage,
          currentPage: currentPage,
          totalDataSize: totalDataSize,
          columSize: columSize,
          totalRowSize: totalRowSize,
          model: model,
          currentRow: currentRow,
          currentColum: currentIndex,
          itemHeight: itemHeight,
        );
      }).toList(),
    );
  }

  /// item 的数据
  Widget _getHasCategoryColumWidget({
    double titleHeight,
    double iconHeight,
    int totalPage,
    int currentPage,
    int columSize,
    int totalRowSize,
    int totalDataSize,
    CustomQuickEntryModel model,
    int currentRow,
    int currentColum,
    double itemHeight,
  }) {
    // 当前index = 当前的页数+1 * 当前的行数 + 当前的列数
    // int currentIndex = (currentPage + 1) * currentRow  + currentColum  + currentRow*columSize;
    // int currentIndex = currentPage != 0 ? currentPage * (columSize * totalRowSize) + columSize + currentRow * columSize :
    //     currentColum + currentRow * columSize;

    // 当前元素的下表 =  当前的列数 +  当前的行数 * 列数 + 当前的页数 * 当前的行数 + 当前的列数
    int currentIndex = currentColum + currentRow * columSize;
    //print("当前页" + currentPage.toString() + "当前点" + currentIndex.toString());

    // print('current Index  sss =  $currentIndex');


    if (currentIndex >= totalDataSize) {
      return Container(
        height: itemHeight,
        width: 60,
      );
    }

    ListStyle item = pageList[currentPage].listStyle[currentIndex];

    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () => _itemIconClick(item),
      child: Container(
        height: itemHeight,
        width:60,
        // color: Colors.red,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            /// 图标
            MyNetWorkImage(item.img,width: 40,),

            /// 一级标题
            Visibility(
              visible: !EmptyUtil.isEmpty(model?.isShowTitle) && model.isShowTitle == '1',
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  item?.title ?? '',
                  style: TextStyle(fontSize: 10, color: HexColor.fromHex(model?.titleColor)),
                ),
              ),
            ),

            /// 二级标题
            Visibility(
              visible: !EmptyUtil.isEmpty(model?.isShowSubTitle) && model.isShowSubTitle == '1',
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(
                  item?.subTitle ?? '',
                  style: TextStyle(fontSize: 10, color: HexColor.fromHex(model?.subTitleColor)),
                ),
              ),
            )
          ],
        ),
      ),
    );
  }

  /// Icon点击事件
  void _itemIconClick(ListStyle model) {
    print("item type = ${model.skipIdentifier}");
    // Navigator.push(context, CupertinoPageRoute(builder: (_) => CommonPage(null)));
    RouterUtil.route(model, model.toJson(), context);
  }

  /// 进度条
  SwiperPlugin _getSwiperPaginationContorl(CustomQuickEntryModel model, int pageCount) {
    if (EmptyUtil.isEmpty(model?.pagination) || model.pagination == 'type_null' /*model.pagination_open == '0'*/) {
      return null;
    }

    if (model.pagination == 'type_point') {
      // 点点点进度条
      return _swiperPaginationDot(model);
    } else {
      // 自定义进度条
      return _swiperCustomPagination(pageCount);
    }
  }

  // 进度条 圆形
  SwiperPagination _swiperPaginationDot(CustomQuickEntryModel model) {
    return SwiperPagination(
        margin: const EdgeInsets.only(),
        builder: DotSwiperPaginationBuilder(
          space: 2,
            color: HexColor.fromHex(model?.paginationUnselectColor), activeColor: HexColor.fromHex(model?.paginationSelectColor), size: 6, activeSize: 7));
  }

  // 自定义进度条 条形
  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(),
        ),
      );
    });
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
}

class PageItem {
  int index;

  PageItem({this.index, this.listStyle});

  List<ListStyle> listStyle;
}
