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/goods_details_page/goods_details_page.dart';
import 'package:zhiying_base_widget/pages/main_page/notifier/main_page_bg_notifier.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

import 'bloc/bloc.dart';
import 'bloc/home_slide_banner_repository.dart';
import 'home_slide_banner_sk.dart';
import 'model/home_slide_banner_model.dart';

///
/// banner轮播图
///
class HomeSlideBanner extends StatefulWidget {
  final Map<String, dynamic> model;

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

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

class _HomeSlideBannerState extends State<HomeSlideBanner> {
  @override
  Widget build(BuildContext context) {
    return BlocProvider<HomeSlideBannerBloc>(
      create: (_) => HomeSlideBannerBloc(repository: HomeSlideBannerRepository())..add(HomeBannerInitEvent(model: widget?.model)),
      child: HomeSlideBannerContainer(),
    );
  }
}

class HomeSlideBannerContainer extends StatefulWidget {
  @override
  _HomeSlideBannerContainerState createState() => _HomeSlideBannerContainerState();
}

class _HomeSlideBannerContainerState extends State<HomeSlideBannerContainer> {

  /// 子元素点击事件
  void _itemOnClick(IndexCarousel model) {
    print('点击了 $model');
    // RouterUtil.route(model.toJson(), context);
    Navigator.push(context, MaterialPageRoute(
      builder: (_) => PageFactory.create('goods_details', null)
    ));
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<HomeSlideBannerBloc, HomeSlideBannerState>(
      listener: (BuildContext context, HomeSlideBannerState 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 HomeSlideBannerCachedState) {
          return _getMainWidget(state.datas);
        }
        // 骨架屏
        return HomeSlideBannerSkeleton();
      },
    );
  }

  Widget _getMainWidget(HomeSlideBannerModel datas) {
    return Container(
      width: double.infinity,
      height: 140,
      child: Swiper(
        itemBuilder: (BuildContext context, int index) {
          IndexCarousel items = datas.index_carousel_list[index];
          return Container(
            width: double.infinity,
            child: CachedNetworkImage(
              imageUrl: items?.img ?? '',
              fit: BoxFit.cover,
            ),
          );
        },
        itemCount: datas?.index_carousel_list?.length ?? 0,
        loop: true,
        autoplay: true,
        onTap: (index) => _itemOnClick(datas.index_carousel_list[index]),
        pagination: _getSwiperStyleByType(datas, datas?.index_carousel_list?.length ?? 0),
        onIndexChanged: (index) {
          print('切换下一页');
          Provider.of<MainPageBgNotifier>(context, listen: false).switchBg(Container(
            width: double.infinity,
            height: 200,
            color: Colors.primaries[(index + 2) % Colors.primaries.length],
          ));
        },
      ),
    );
  }

  /// 获取进度样式
  SwiperPlugin _getSwiperStyleByType(HomeSlideBannerModel model, int pageCount) {

    if('1' != model.pagination_open){
      return null;
    }

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

  /// 数字样式
  SwiperPlugin _getNumswiperPlugin(int pageCount, String selectColor, String unselectColor) {
    return SwiperCustomPagination(builder: (BuildContext context, SwiperPluginConfig config) {
      return Align(
        alignment: Alignment(0.0, 0.9),
        child: Container(
            padding: const EdgeInsets.symmetric(vertical: 5, horizontal: 18),
            decoration: BoxDecoration(borderRadius: BorderRadius.circular(13), color: HexColor.fromHex('#4D000000')),
            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));
  }
}
