import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/orders_page/bloc/order_page_bloc.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_filter_model.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_page_item_style_model.dart';
import 'package:zhiying_base_widget/pages/orders_page/models/order_page_style_model.dart';
import 'package:zhiying_base_widget/pages/orders_page/order_content_page.dart';
import 'package:zhiying_base_widget/pages/orders_page/order_search_page.dart';
import 'package:zhiying_base_widget/pages/orders_page/views/order_filter.dart';
import 'package:zhiying_base_widget/pages/orders_page/views/order_serch_widget.dart';
import 'package:zhiying_base_widget/pages/orders_page/views/order_tabbar_widget.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

// 订单页面
class OrdersPage extends StatefulWidget {
  final Map<String, dynamic> data;

  const OrdersPage(
    this.data, {
    Key key,
  }) : super(key: key);

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

class _OrdersPageState extends State<OrdersPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xfff9f9f9),
      appBar: _createNav(),
      body: SafeArea(
          child: BlocProvider<OrderPageBloc>(
        bloc: OrderPageBloc(),
        child: _OrdersContainer(widget.data),
      )),
    );
  }

  // 导航栏
  Widget _createNav() {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: Colors.white,
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        '我的订单',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xff333333),
        ),
      ),
    );
  }
}

class _OrdersContainer extends StatefulWidget {
  final Map<String, dynamic> data;

  const _OrdersContainer(this.data, {Key key}) : super(key: key);

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

class _OrdersContainerState extends State<_OrdersContainer>
    with TickerProviderStateMixin {
  TabController _tabController;
  GlobalKey _tabKey = GlobalKey();
  OrderPageBloc _bloc;

  final OrderFilterModel _filter = OrderFilterModel();

  bool _isFilterShow = false;
  List<String> _titles = [];
  List<Widget> _contents = [];

  EventBus _eventBus = EventBus();

  @override
  void initState() {
    _bloc = BlocProvider.of<OrderPageBloc>(context);
    if (widget.data.containsKey('skip_identifier')) {
      _bloc.loadData(widget.data['skip_identifier']);
    }

    super.initState();
  }

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

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<OrderPageStyleModel>(
        stream: _bloc.outData,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          OrderPageStyleModel model = snapshot.data;
          if (model == null) {
            return Container();
          }
          List<OrderTypeModel> type = model.filter.orderState;

          _tabController?.dispose();
          _tabController =
              TabController(length: type?.length ?? 0, vsync: this);
          _tabController.addListener(() {
            Logger.debug('????? ${_tabController.index.toString()}');
          });
          _titles = List.generate(type?.length, (index) => type[index].name);
          _contents = List.generate(
            type?.length ?? 0,
            (index) => OrderContentPage(
              type[index].type,
              style: model,
              filter: _filter,
              index: index,
              eventBus: _eventBus,
            ),
          );

          return Column(
            children: <Widget>[
              GestureDetector(
                child: OrderSearchWidget(model),
                onTap: () {
                  Navigator.of(context)
                      .push(CupertinoPageRoute(builder: (BuildContext context) {
                    return OrderSearchPage(model);
                  }));
                },
              ),
              OrderTabbarWidget(
                model,
                _tabController,
                _titles,
                key: _tabKey,
                onMoreClick: () {
                  setState(() {
                    _isFilterShow = !_isFilterShow;
                  });
                },
              ),
              Expanded(
                child: Stack(
                  children: <Widget>[
                    TabBarView(
                      children: _contents,
                      controller: _tabController,
                    ),
                    Visibility(
                      visible: _isFilterShow,
                      child: OrderFilterWidget(
                        model,
                        _filter,
                        onDismiss: () {
                          setState(() {
                            _isFilterShow = false;
                          });
                        },
                        onConfirm: (_) {
                          _eventBus.fire(_tabController.index);
                          setState(() {
                            _isFilterShow = false;
                          });
                        },
                        onReset: (_) {
                          _eventBus.fire(_tabController.index);
                          setState(() {
                            _isFilterShow = false;
                          });
                        },
                      ),
                    )
                  ],
                ),
              )
            ],
          );
        });
  }
}
