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_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: (_) =>
      CustomQuickEntryBloc(repository: CustomQuickEntryRepository())
        ..add(CustomQuickEntryInitEvent(model: model)),
      child: _CustomQuickEntryContainer(model),
    );
  }
}

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

  _CustomQuickEntryContainer(this.model);

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

class __CustomQuickEntryContainerState extends State<_CustomQuickEntryContainer> {
  /// 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) {
        return true;
      },
      builder: (context, state) {
        if (state is CustomQuickEntryCachedState) {
          return _getMainWidget(state.model);
        }
        if (state is CustomQuickEntryLoadedState) {
          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');

    // 图标的高度
    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);
    }

    // 分类导航高度
    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;
    // }

    return Container(
      margin: EdgeInsets.only(top: double.tryParse(model?.topMargin),
          left: ParseUtil.stringParseDouble(model?.leftRightMargin),
          right: ParseUtil.stringParseDouble(model?.leftRightMargin)),
      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 ? 15 : 0),
        height: totalHeight,
        // 总体高度
        width: double.infinity,
        // color: HexColor.fromHex(widget?.model['bg_color']),
        child: Column(
          children: <Widget>[

            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),

            /// 一级标题
            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(),
        ),
      );
    });
  }
}

///
/// 图片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),
//       ),
//     ),
//   );
// }

}
