import 'package:cached_network_image/cached_network_image.dart';
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:provider/provider.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_bg_notifier.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'bloc/bloc.dart';
import 'bloc/custom_slide_banner_repository.dart';
import 'custom_slide_banner_sk.dart';
import 'model/custom_slide_banner_model.dart';

///
/// 可滑动 banner 轮播图
///
class CustomSlideBanner extends StatefulWidget {
  final Map<String, dynamic> model;

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

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

class _CustomSlideBannerState extends State<CustomSlideBanner> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<CustomSlideBannerBloc>(
      create: (_) => CustomSlideBannerBloc(repository: CustomSlideBannerRepository())..add(CustomBannerInitEvent(model: widget?.model)),
      child: CustomSlideBannerContainer(),
    );
  }
}

class CustomSlideBannerContainer extends StatefulWidget {
  @override
  _CustomSlideBannerContainerState createState() => _CustomSlideBannerContainerState();
}

class _CustomSlideBannerContainerState extends State<CustomSlideBannerContainer> {
  /// 子元素点击事件
  void _itemOnClick(IndexCarouselList model) {
    print('点击了 $model');
    RouterUtil.route(model, model.toJson(), context);
    // Navigator.push(context, CupertinoPageRoute(builder: (_) => VipCenterPage(null)));
  }

  SwiperController _swiperController;

  @override
  void initState() {
    _swiperController = SwiperController();
    super.initState();
  }

  @override
  void dispose() {
    _swiperController.stopAutoplay();
    _swiperController?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<CustomSlideBannerBloc, CustomSlideBannerState>(
      listener: (BuildContext context, CustomSlideBannerState state) {
        if (state is HomeSlideBannerLoadError) {
          print('数据加载出错');
        }
      },
      buildWhen: (previous, current) {
        /// 数据加载出错不进行build
        if (current is HomeSlideBannerLoadError) {
          return false;
        }
        return true;
      },
      builder: (context, state) {
        print('currente state = $state');
        if (state is HomeSlideBannerLoadedState) {
          return _getMainWidget(state.datas);
        }
        if (state is CustomSlideBannerCachedState) {
          return _getMainWidget(state.datas);
        }
        // 骨架屏
        return CustomSlideBannerSkeleton();
      },
    );
  }

  Widget _getMainWidget(CustomSlideBannerModel datas) {
    Future.delayed(Duration.zero, () {
      Provider.of<MainPageBgNotifier>(context, listen: false).switchBg(Container(
        width: double.infinity,
        height: 200,
        color: Colors.redAccent,
      ));
    });

    int size = datas?.indexCarouselList?.length ?? 0;
    if (size == 0) return Container();

    // 根据宽高比获取到图片的高度
    // 左右边距
    double horizontalPadding = ParseUtil.stringParseDouble(datas?.leftRightMargin, defVal: 12.5);
    // 上下的边距
    double verticalPadding = ParseUtil.stringParseDouble(datas?.topMargin, defVal: 10);
    // 图片高度
    double imgHeight = (MediaQuery.of(context).size.width - horizontalPadding * 2) * ParseUtil.stringParseDouble(datas?.barWidthHeightRatio, defVal: 0.38);
    // Logger.log('horizontalPadding = $horizontalPadding, verticalPadding = $verticalPadding, imgHeight = $imgHeight');

    return Container(
      width: double.infinity,
      height: imgHeight + verticalPadding * 2,
      // color: Colors.green,
      child: Stack(
        children: <Widget>[
          Column(
            children: <Widget>[
              Flexible(
                child: Container(
                  decoration: BoxDecoration(
                      color: size > 1 ? HexColor.fromHex(datas?.bgColor??"#00000000") : Colors.transparent,
                      borderRadius: BorderRadius.only(
                          topLeft: Radius.circular(double.tryParse(datas?.topLeftRadius)??0),
                          topRight: Radius.circular(double.tryParse(datas?.topRightRadius)??0),
                          bottomRight: Radius.circular(double.tryParse(datas?.bottomRightRadius)??0),
                          bottomLeft: Radius.circular(double.tryParse(datas?.bottomLeftRadius)??0)
                      )
                  ),
                  width: double.infinity,
                  height: double.infinity,

                  // color: Colors.yellow,
                ),
              ),
            ],
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: horizontalPadding, vertical: verticalPadding),
            child: Swiper(
              controller: _swiperController,
              itemBuilder: (BuildContext context, int index) {
                IndexCarouselList items = datas.indexCarouselList[index];
                return Container(
                  width: double.infinity,
                  decoration: BoxDecoration(borderRadius: BorderRadius.circular(7.5)),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(7.5),
                    child: CachedNetworkImage(
                      imageUrl: items?.img ?? '',
                      fit: BoxFit.cover,
                    ),
                  ),
                );
              },
              itemCount: size,
              loop: size > 1,
              autoplay: true,
              onTap: (index) => _itemOnClick(datas.indexCarouselList[index]),
              pagination: _getSwiperStyleByType(datas, size),
              onIndexChanged: (index) {
                // print('color = ${datas?.indexCarouselList[index]?.bgColor}');
                Provider.of<MainPageBgNotifier>(context, listen: false).switchBg(Container(
                  width: double.infinity,
                  height: 200,
                  color: HexColor.fromHex(datas?.indexCarouselList[index]?.bgColor),
                ));
              },
            ),
          ),
        ],
      ),
    );
  }

  /// 获取进度样式
  SwiperPlugin _getSwiperStyleByType(CustomSlideBannerModel model, int pageCount) {
    // 一张图片就不滑动
    if (pageCount <= 1) {
      return null;
    }

    if ('type_null' == model.pagination) {
      return null;
    }

    if ('type_number' == model.pagination) {
      return _getNumswiperPlugin(pageCount, model.paginationSelectColor, model.paginationUnselectColor);
    }
    if ('type_point' == model.pagination) {
      return _swiperCustomPaginationDito(pageCount, model.paginationSelectColor, model.paginationUnselectColor);
    }
    if ('type_bar' == model.pagination) {
      return _swiperCustomPagination(pageCount, model.paginationSelectColor, model.paginationUnselectColor);
    }
    return null;
  }

  /// 数字样式
  SwiperPlugin _getNumswiperPlugin(int pageCount, String selectColor, String unselectColor) {
    return SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
      return Align(
        alignment: Alignment(0.9, 0.9),
        child: Container(
            padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 18),
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(3), color: HexColor.fromHex('#80333333')),
            child: RichText(
              text: TextSpan(text: '${config.activeIndex + 1}', style: TextStyle(fontSize: 12, color: HexColor.fromHex(selectColor)), children: [
                TextSpan(text: '/', style: TextStyle(fontSize: 12, color: HexColor.fromHex(unselectColor))),
                TextSpan(text: '$pageCount', style: TextStyle(fontSize: 12, color: HexColor.fromHex(unselectColor))),
              ]),
            )),
      );
    });
  }

  /// 自定义进度条
  SwiperPlugin _swiperCustomPagination(int pageCount, String selectColor, String unselectColor) {
    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, 0.9),
        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(selectColor) : HexColor.fromHex(unselectColor)),
            );
          }).toList(),
        ),
      );
    });
  }

  /// 圆形进度条
  SwiperPlugin _swiperCustomPaginationDito(int pageCount, String selectColor, String unselectColor) {
    return SwiperPagination(
        margin: const EdgeInsets.only(), builder: DotSwiperPaginationBuilder(color: HexColor.fromHex(unselectColor), activeColor: HexColor.fromHex(selectColor), size: 8, activeSize: 8));
  }
}
