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: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_comm/zhiying_comm.dart';
import 'package:cached_network_image/cached_network_image.dart';

import 'home_quick_entry_sk.dart';
import 'model/home_quick_entry_model.dart';

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

  const HomeQuickEntry(this.model);

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

class HomeQuickEntryContianer extends StatefulWidget {
  @override
  _HomeQuickEntryContianerState createState() => _HomeQuickEntryContianerState();
}

class _HomeQuickEntryContianerState extends State<HomeQuickEntryContianer> {

  /// Icon点击事件
  void _itemIconClick(TypeNormal model){
    print("item type = ${model.skip_identifier}");
    // RouterUtil.route(model, model.toJson(), context);
  }

  @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 totalDataSize = model?.type_normal?.length ?? 0;

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

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

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

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

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

    //如果有二级标题
    if (!EmptyUtil.isEmpty(model?.title_2_open) && model.title_2_open == '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_open) && model.pagination_open == '0') {
        totalHeight = totalRowSize * (itemHeight + barMargin);
    }

    return Container(
      color: Colors.white,
      child: Container(
        margin: const EdgeInsets.only(top: 15, bottom: 15 ),
        height: totalHeight, // 总体高度
        width: double.infinity,
        color: Colors.white,
        child: Swiper(
          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: _getSwiperPaginationContorl(model, totalPage),
        ),
      ),
    );
  }

  /// 页的数据
  Widget _getPageWidget({double titleHeight, double iconHeight, int totalPage, int currentPage, int columSize, int totalRowSize, int totalDataSize, HomeQuickEntryModel 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, HomeQuickEntryModel 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, HomeQuickEntryModel 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,);
    }

    TypeNormal item = model?.type_normal[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?.title_1_open) && model.title_1_open == '1',
              child: Padding(
                padding: const EdgeInsets.only(top: 5),
                child: Text(item?.title_1 ?? '', style: TextStyle( fontSize: 10, color: HexColor.fromHex(model?.title_1_text_color)),),
              ),
            ),

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

          ],
        ),
      ),
    );
  }


  /// 进度条
  SwiperPagination _getSwiperPaginationContorl(HomeQuickEntryModel model, int pageCount){
    if(EmptyUtil.isEmpty(model?.pagination_open) || model.pagination_open == '0'){
      return null;
    }

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

  }

  // 进度条 圆形
  SwiperPagination _swiperPaginationDot(HomeQuickEntryModel model){
    return SwiperPagination(margin: const EdgeInsets.only(), builder: DotSwiperPaginationBuilder( color: HexColor.fromHex(model?.pagination_unselect_color), activeColor: HexColor.fromHex(model?.pagination_select_color), 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,
      ),
    );
  }
}
