import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:zhiying_base_widget/widgets/home/home_notice/bloc/home_notice_repository.dart';
import 'package:zhiying_base_widget/widgets/home/home_notice/home_notice_sk.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'package:zhiying_base_widget/widgets/home/home_notice/model/home_notice_model.dart';
import 'bloc/bloc.dart';

///
/// 公告滚动widget
///
class HomeNoticeWidget extends StatelessWidget {
  final Map<String, dynamic> model;

  const HomeNoticeWidget(this.model);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<HomeNoticeBloc>(
      create: (_) => HomeNoticeBloc(repository: HomeNoticeRepository())..add(HomeNoticeInitEvent(model: model)),
      child: HomeNoticeWidgetContianer(),
    );
  }
}

class HomeNoticeWidgetContianer extends StatefulWidget {
  @override
  _HomeNoticeWidgetContianerState createState() => _HomeNoticeWidgetContianerState();
}

class _HomeNoticeWidgetContianerState extends State<HomeNoticeWidgetContianer> {

  /// 子item点击事件
  void _itemOnClick(HomeNoticeModel model) {
    if(pageIndex == model.notices.length){
      pageIndex = 0;
    }
    print('===== $pageIndex');
    HomeNoticeNoticesModel item = model.notices[pageIndex];
    _itemJump(item);
  }

  /// 子item跳转
  void _itemJump(HomeNoticeNoticesModel model){
    print('${model?.skip_identifier}');
    RouterUtil.route(model.toJson(), context);
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<HomeNoticeBloc, HomeNoticeState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        return true;
      },
      builder: (context, state) {
        if (state is HomeNoticeLoadedState) {
          return _getMainWidget(state?.model);
        }
        return HomeNoticeSkeleton();
      },
    );
  }

  /// 主体页面
  Widget _getMainWidget(HomeNoticeModel model) {
    return Container(
      width: double.infinity,
      decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.only(bottomLeft: Radius.circular(7.5), bottomRight: Radius.circular(7.5))),
      padding: const EdgeInsets.only(bottom: 7.5),
      child: Container(
        decoration: BoxDecoration(borderRadius: BorderRadius.circular(7.5), color: HexColor.fromHex(model?.bg_color)),
        // color: Colors.cyan),
        margin: const EdgeInsets.only(left: 12.5, right: 12.5),
        padding: const EdgeInsets.only(top: 8, bottom: 8, left: 12, right: 8),
        // height: 30,
        width: double.infinity,
        child: _getChildWidget(model),
      ),
    );
  }

  var pageIndex = 0;

  Widget _getChildWidget(HomeNoticeModel model) {
    return GestureDetector(
      onTap: () => _itemOnClick(model),
      behavior: HitTestBehavior.opaque,
      child: Row(
        children: <Widget>[
          /// 图片
          // Container(width: 52, height: 13, color: Colors.red),
          CachedNetworkImage(
            imageUrl: model?.logo_img ?? '',
            width: 52,
          ),
          const SizedBox(width: 14),

          /// 文字
          Expanded(
            child: Container(
              width: double.infinity,
              height: 15,
              alignment: Alignment.centerLeft,
              // color: Colors.yellowAccent,
              child: MarqueeWidget(
                model?.notices?.length ?? 0,
                (BuildContext context, int index) {
                  HomeNoticeNoticesModel item = model.notices[index];
                  return Align(alignment: Alignment.centerLeft, child: Text('${item?.notice_text}' , style: TextStyle(color: HexColor.fromHex(model?.text_color), fontSize: 12)));
                },
                onPageChanged: (index) => pageIndex = index,
              ),
            ),
          ),
          const SizedBox(width: 14),

          /// 图片
          CachedNetworkImage(imageUrl: model?.jump_img ?? '', height: 18),
          // Container(
          //   width: 18,
          //   height: 18,
          //   color: Colors.red,
          // ),
        ],
      ),
    );
  }
}

// 上下滚动的消息轮播
class MarqueeWidget extends StatefulWidget {
  int count; // 子视图数量
  IndexedWidgetBuilder itemBuilder; // 子视图构造器
  final ValueChanged<int> onPageChanged;

  MarqueeWidget(this.count, this.itemBuilder, {this.onPageChanged});

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

class _MarqueeWidgetState extends State<MarqueeWidget> {
  PageController _controller;
  Timer _timer;

  @override
  void initState() {
    super.initState();

    if (widget.count > 1) {
      _controller = PageController();
      _timer = Timer.periodic(Duration(seconds: 5), (timer) {
        // 如果当前位于最后一页，则直接跳转到第一页，两者内容相同，跳转时视觉上无感知
        if (_controller.page.round() >= widget.count) {
          _controller.jumpToPage(0);
        }
        _controller.nextPage(duration: Duration(seconds: 1), curve: Curves.linear);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    //   return PageView.builder(
    //     scrollDirection: Axis.vertical,
    //     controller: _controller,
    //     itemBuilder: (buildContext, index) {
    //       if (index < widget.count) {
    //         return widget.itemBuilder(buildContext, index);
    //       } else {
    //         return widget.itemBuilder(buildContext, 0);
    //       }
    //     },
    //     itemCount: widget.count + 1, // 在原数据末尾添加一笔数据(即第一笔数据)，用于实现无限循环滚动效果
    //   );
    // }

    return PageView.custom(
      physics: NeverScrollableScrollPhysics(),
      childrenDelegate: SliverChildBuilderDelegate((context, index) {
        if (index < widget.count) {
          return widget.itemBuilder(context, index);
        } else {
          return widget.itemBuilder(context, 0);
        }
      }, childCount: widget.count + 1),
      scrollDirection: Axis.vertical,
      controller: _controller,
      onPageChanged: widget?.onPageChanged,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
    _timer?.cancel();
  }
}
