
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:twong/api/index.dart';
import 'package:twong/providers/order_num.dart';
import 'package:twong/router/base.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/models/index.dart';
import 'package:twong/widgets/app_bar.dart';
import 'package:twong/widgets/cart_item.dart';
import 'package:twong/widgets/order_utils.dart';

class OrderList extends StatefulWidget {
  final int index;
  OrderList({Key key, this.index = 0}): super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _OrderListState(this.index);
  }
}

class _OrderListState extends State<OrderList> with SingleTickerProviderStateMixin {
  int index;
  List<OrderData> _orders;
  List<String> tabs = ["待付款", "待发货", "待收货", "待评价", "已完成"];

  _OrderListState(this.index);

  @override
  void initState() {
    doSelect(index);
    super.initState();
  }

  void doSelect(int idx) {
    setState(() {
      index = idx;
      _orders = null;
    });

    Network.inst.getOrderList(type: idx).then((orders) {
      setState(() {
        _orders = orders;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: DAppBar("订单管理"),
      body: SafeArea(
        child: Container(
          color: DColors.back,
          child: Stack(
              children: [
                Consumer<OrderNumModel>(
                  builder: (context, model, child) => _buildHeaders(model.data),
                ),
                _buildTabs(),
                Container(
                  child: _buildList(),
                  margin: EdgeInsets.only(top: 104.px),
                  constraints: BoxConstraints.expand(),
                )
              ]),
        ),
      ),
    );
  }

  Widget _buildHeaders(dynamic data) {
    Log.d(data);
    return Container(
      height: 88.px,
      color: DColors.Main,
      padding: EdgeInsets.only(left: 12.px, right: 12.px),
      constraints: BoxConstraints.expand().widthConstraints(),
      child: Row(
          children: [
            Expanded(child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    height: 23.px,
                    margin: EdgeInsets.only(top: 12.px),
                    child: Text("订单信息", style:
                    TextStyle(color: Colors.white,
                        fontSize: 14.px,
                        fontWeight: FontWeight.w600)),
                  ),
                  Row(
                      children: [
                        Text("累计订单: ${data["order_count"]}单",
                            style: TextStyle(color: Colors.white,
                                fontSize: 12.px)),
                        Container(width: 30.px),
                        Text("总消费: ${Utils.formatRMB(data["sum_price"],
                            show: true)}", style: TextStyle(color: Colors.white,
                                fontSize: 12.px)),
                      ])
                ])
            ),
            Container(
              width: 80.px,
              margin: EdgeInsets.only(top: 6.px),
              alignment: Alignment.topCenter,
              // child: Icon(Icons.shopping_bag_outlined,
              //     color: Colors.white, size: 48.px),
            )
          ]),
    );
  }

  Widget _buildTabs() {
    final _style = TextStyle(fontSize: 12.px);
    List<Widget> widgets = List<Widget>();
    for (var idx = 0; idx < tabs.length; idx ++) {
      widgets.add(Expanded(child: Container(
        width: 4.px,
        child: FlatButton(
          minWidth: 1.px,
          highlightColor: Colors.transparent,
          onPressed: () => doSelect(idx),
          child: Container(
            padding: EdgeInsets.only(bottom: 4.px),
            decoration: BoxDecoration(
              border: index == idx ? Border(
                  bottom: BorderSide(color: DColors.Main)
              ) : null,
            ),
            child: Text(tabs[idx], textAlign: TextAlign.center, style: _style),
          ),
        ),
      )));
    }

    return Container(
        constraints: BoxConstraints.expand().widthConstraints(),
        height: 46.px,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.px)
        ),
        margin: EdgeInsets.only(left: 12.px, right: 12.px, top: 58.px),
        child: Row(children: widgets));
  }

  Widget _buildList() {
    if (_orders == null) {
      return Container(
          alignment: Alignment.topCenter,
          margin: EdgeInsets.only(top: 86.px),
          child: Utils.loadingWidget);
    }
    if (_orders.length < 1) {
      return Container(
          alignment: Alignment.topCenter,
          margin: EdgeInsets.only(top: 86.px),
          child: Text("暂无订单信息"));
    }
    List<Widget> widgets = List<Widget>();
    for (var data in _orders) {
      List<Widget> cartList = List<Widget>();
      for (var order in data.cartInfo) {
        cartList.add(CartItem(order));
      }

      widgets.add(Container(
        margin: EdgeInsets.only(top: 8.px),
        padding: EdgeInsets.all(6.px),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.px)
        ),
        child: Column(
            children: [
              Row(children: [
                Expanded(child: Text(Utils.formatData(data.add_time))),
                Text(data.orderStatus.title)
              ]),
              Divider(),
              InkWell(
                onTap: () {
                  Navigator.pushNamed(context,
                      RouteNames.orderDetails, arguments: data.order_id);
                },
                child: Column(children: cartList),
              ),
              Divider(),
              Row(mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    RichText(text: TextSpan(
                        style: TextStyle(color: Colors.black, fontSize: 12.px),
                        text: "共 ${data.cartInfo.length} 件商品 总金额: ",
                        children: [
                          TextSpan(text:
                          Utils.formatRMB(data.total_price, show: true),
                              style: TextStyle(
                                  color: Colors.red, fontSize: 13.px)
                          )
                        ]
                    ))
                  ]),
              OrderUtils.buildButtons(data: data),
            ]),
      ));
    }
    return Container(
        margin: EdgeInsets.only(left: 12.px, right: 12.px),
        child: ListView(
            children: widgets,
            physics: ClampingScrollPhysics()
        )
    );
  }
}