
import 'dart:async';
import 'dart:ui';

import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:flutter_wisetronic/generated/l10n.dart';
import 'package:flutter_wisetronic/models/cart_line_item.dart';
import 'package:flutter_wisetronic/models/extra_fee.dart';
import 'package:flutter_wisetronic/models/fulfillment.dart';
import 'package:flutter_wisetronic/models/order.dart';
import 'package:flutter_wisetronic/store/actions.dart';
import 'package:flutter_wisetronic/store/store.dart';
import 'package:flutter_wisetronic/utils/http_util.dart';
import 'package:flutter_wisetronic/utils/utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

import '../../constants.dart';
import '../../routes.dart';
import '../../utils/util_web.dart' if (dart.library.io) '../../utils/util_io.dart';

class MobileOrderDetail extends StatefulWidget {
  final Key? key;
  final int orderId;
  final bool fromOrders;
  const MobileOrderDetail(this.orderId, {this.key, this.fromOrders});

  @override
  State<StatefulWidget> createState() {
    return MobileOrderDetailState();
  }

}

class MobileOrderDetailState extends State<MobileOrderDetail> {
  Order order;

  LatLng _lastMapPosition;
  LatLng customerLatLng;
  LatLng deliveryLatLng;
  LatLng storeLatLng;
  final Set<Marker> _markers = {};
  final Set<Polyline> _polyLine = {};

  BitmapDescriptor homeIcon;
  BitmapDescriptor deliveryIcon;
  BitmapDescriptor shopIcon;

  Completer<GoogleMapController> _controller = Completer();

  void _onMapCreated(GoogleMapController controller) {
    _controller.complete(controller);
  }

  void _onCameraMove(CameraPosition position) {
    _lastMapPosition = position.target;
  }

  @override
  Widget build(BuildContext context) {
    store.dispatch(UpdateContext(context));

    if (order == null ) {
      return new Scaffold(
        body: Center(
          child: SpinKitWave(
            color: Colors.lightBlueAccent,
            size: 40.0,
          ),
        ),
      );
    }

    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios),
          onPressed: (){
            if (widget.fromOrders != null && widget.fromOrders) {
              Navigator.of(context).pop();
            } else {
              Routes.router.navigateTo(
                  context, '/orders', replace: true, clearStack: true);
            }
          },
        ),
        title: Text(S.of(context).order_detail),
        backgroundColor: Theme.of(context).primaryColor,
      ),
      body: WillPopScope(
        onWillPop: () async {
          if (widget.fromOrders != null && widget.fromOrders) {
            return true;
          } else {
            Routes.router.navigateTo(
                context, '/orders', replace: true, clearStack: true);
          }
          return false;
        },
        child: ListView.builder(
          itemCount: 4,
          itemBuilder: (BuildContext context, int position) {

            switch (position) {
              case 0:
                Column col = Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[],
                );
                col.children.add(
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                          child: GestureDetector(
                            child: Container(
                              width: double.infinity,
                              padding: EdgeInsets.only(top: 0.0, bottom: 16.0),
                              child: Text(
                                order.cartInfo.businessInfo.name,
                                maxLines: 1,
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                  fontSize: 17.0,
                                  fontWeight: FontWeight.bold,
                                ),
                              ),
                              decoration: BoxDecoration(
                                color: Colors.transparent,
                                border: Border(
                                    bottom: BorderSide(
                                      width: 0.5,
                                      color: Colors.black26,
                                    )
                                ),
                              ),
                            ),
                            onTap: () {
                              Routes.router.navigateTo(context, '/shop/${order.businessId}/na/na/na');
                            },
                          ),
                        ),
                        Container(
                          padding: EdgeInsets.only(left: 5.0),
                          margin: EdgeInsets.only(left: 5.0),
                          child: GestureDetector(
                            child: Icon(
                              Icons.phone,
                            ),
                            onTap: () {
                              Utils.launchURL('tel:${order.businessInfo.phone}');
                            },
                          ),
                        ),
                      ],
                    )
                );

                if (!kIsWeb) {
                  if (order.shippingMethod == 'store-delivery' && order.status != Constants.STATUS_COMPLETE && order.status != Constants.STATUS_CANCELLED) {
                    col.children.add(Container(
                      height: 200.0,
                      child: GoogleMap(
                        onMapCreated: _onMapCreated,
                        initialCameraPosition: CameraPosition(
                          target: LatLng(
                            double.parse(order.shippingAddress.lat),
                            double.parse(order.shippingAddress.lng)),
                          zoom: 11.0,
                        ),
                        onCameraMove: _onCameraMove,
                        markers: _markers,
                        polylines: _polyLine,
                        gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
                          new Factory<OneSequenceGestureRecognizer>(() => new EagerGestureRecognizer(),)
                        ].toSet(),
                      ),
                    ));
                    if (order.deliveryDistance != null && order.deliveryDistance.distance != null) {
                      col.children.add(Container(
                        padding: EdgeInsets.only(top: 6.0, bottom: 6.0),
                        margin: EdgeInsets.only(bottom: 6.0),
                        child: Text(
                          S.of(context).delivery_distance_token(
                              order.deliveryDistance.distance.text,
                              order.deliveryDistance.duration.text
                          ),
                        ),
                        decoration: BoxDecoration(
                          border: Border(
                            bottom: BorderSide(
                              width: 0.5,
                              color: Colors.black12,
                            ),
                          ),
                        ),
                      ));
                    }
                  }
                }

                for (CartLineItem lineItem in order.cartInfo.productList) {

                  col.children.add(Container(
                    padding: EdgeInsets.only(top: 16.0, bottom: 0.0),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Util.showImage('${lineItem.product.imagePath}',
                          width: 40.0,
                          height: 40.0,
                          fit: BoxFit.fill,
                          errorWidget: (context, url, error) => Icon(Icons.broken_image, size: 40.0, color: Colors.transparent,),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(left: 5.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.start,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  '${lineItem.name}',
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontSize: 15.0,
                                  ),
                                ),
                                Text(
                                  '${lineItem.description}',
                                  maxLines: 2,
                                  overflow: TextOverflow.ellipsis,
                                  style: TextStyle(
                                    fontSize: 10.0,
                                    color: Colors.black26,
                                  ),
                                )
                              ],
                            ),
                          ),
                        ),
                        Container(
                          width: 30.0,
                          alignment: Alignment.centerRight,
                          child: Text(
                            'x${lineItem.quantity.round()}',
                            style: TextStyle(
                              fontSize: 14.0,
                            ),
                          ),
                        ),
                        Container(
                          width: 60.0,
                          alignment: Alignment.centerRight,
                          child: Text(
                            '${lineItem.getTotalPrice().toStringAsFixed(2)}',
                            style: TextStyle(
                              fontSize: 14.0,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ));
                }
                col.children.add(Container(
                  decoration: BoxDecoration(
                    border: Border(
                      top: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));
                col.children.add(
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 12.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            S.of(context).subtotal,
                            style: TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 12.0),
                        width: 100.0,
                        alignment: Alignment.centerRight,
                        child: Text(
                          '${order.getSubtotal().toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 15.0,
                          ),
                        ),
                      ),
                    ],
                  ),
                );
                for (var i = 0; i < order.cartInfo.extraFeeList.length; i++) {
                  ExtraFee extraFee = order.cartInfo.extraFeeList[i];
                  col.children.add(
                    Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(top: 12.0),
                            alignment: Alignment.centerRight,
                            child: Text(
                              '${extraFee.name}(${extraFee.rate}%)',
                              style: TextStyle(
                                fontSize: 15.0,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                        Container(
                          margin: EdgeInsets.only(top: 12.0),
                          width: 100.0,
                          alignment: Alignment.centerRight,
                          child: Text(
                            '${extraFee.price.toStringAsFixed(2)}',
                            style: TextStyle(
                              fontSize: 15.0,
                            ),
                          ),
                        ),
                      ],
                    ),
                  );
                }
                col.children.add(
                  Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 12.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            S.of(context).total,
                            style: TextStyle(
                              fontSize: 15.0,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                        ),
                      ),
                      Container(
                        margin: EdgeInsets.only(top: 12.0, bottom: 12.0),
                        width: 100.0,
                        alignment: Alignment.centerRight,
                        child: Text(
                          '${order.totalPrice.toStringAsFixed(2)}',
                          style: TextStyle(
                            fontSize: 18.0,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                    ],
                  ),
                );

                return Container(
                  padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
                  child: col,
                  decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          width: 10,
                          color: Colors.black12,
                        )
                    ),
                  ),
                );
                break;
              case 1:
                Column col = Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[],
                );
                col.children.add(Container(
                  width: double.infinity,
                  padding: EdgeInsets.only(top: 0.0, bottom: 16.0),
                  child: Text(
                    S.of(context).delivery_info,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      fontSize: 17.0,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black26,
                        )
                    ),
                  ),
                ),
                );
                if (order.shippingMethod != 'pickup') {
                  col.children.add(Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          width: 110.0,
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                          child: Text(
                            S.of(context).delivery_address,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 2,
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                            child: Text(
                              '${order.address}, ${order.consignee}, ${order.phone}',
                              style: TextStyle(
                                color: Colors.black38,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black12,
                        ),
                      ),
                    ),
                  ));
                } else {
                  col.children.add(Container(
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: <Widget>[
                        Container(
                          width: 110.0,
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                          child: Text(
                            S.of(context).pickup_address,
                            overflow: TextOverflow.ellipsis,
                            maxLines: 2,
                          ),
                        ),
                        Expanded(
                          child: Container(
                            margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                            alignment: Alignment.centerRight,
                            child: Text(
                              '${order.cartInfo.businessInfo.fullAddress}',
                              style: TextStyle(
                                color: Colors.black38,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black12,
                        ),
                      ),
                    ),
                  ));
                }

                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).schedule_delivery,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            '${Utils.timestampToString(context, order.bookedAt, withTime: true)}',
                            style: TextStyle(
                              color: Colors.black38,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));
                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).delivery_method,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            order.shippingMethod == 'pickup' ? S.of(context).pickup : S.of(context).store_delivery,
                            style: TextStyle(
                              color: Colors.black38,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));

                return Container(
                  padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
                  child: col,
                  decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          width: 10,
                          color: Colors.black12,
                        )
                    ),
                  ),
                );
                break;
              case 2:
                Column col = Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[],
                );

                col.children.add(Container(
                  padding: EdgeInsets.only(top: 0.0, bottom: 16.0),
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      Text(
                        S.of(context).order_info,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 17.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(''),
                    ],
                  ),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black26,
                        )
                    ),
                  ),
                ),);

                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).order_number,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Text(
                                '${order.orderNum}',
                                style: TextStyle(
                                  color: Colors.black38,
                                ),
                              ),
                              Container(
                                margin: EdgeInsets.only(left: 10.0, right: 10.0),
                                child: Text(''),
                                decoration: BoxDecoration(
                                  border: Border(
                                    left: BorderSide(
                                        width: 0.5,
                                        color: Colors.black12
                                    ),
                                  ),
                                ),
                              ),
                              GestureDetector(
                                child: Text(
                                  S.of(context).copy,
                                ),
                                onTap: () {
                                  Clipboard.setData(ClipboardData(text: '${order.orderNum}'));
                                  Fluttertoast.showToast(
                                      msg: S.of(context).order_number_copied_to_clipboard,
                                      toastLength: Toast.LENGTH_SHORT,
                                      gravity: ToastGravity.CENTER,
                                      backgroundColor: Colors.black54,
                                      textColor: Colors.white
                                  );
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));

                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).payment_method,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            order.payMethod == 0 ? S.of(context).online_payment : S.of(context).pay_on_deliery,
                            style: TextStyle(
                              color: Colors.black38,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));

                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).payment_status,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              Text(
                                order.paymentStatus == Constants.PAYMENT_STATUS_PAID ? S.of(context).paid : S.of(context).unpaid,
                                style: TextStyle(
                                  color: Colors.black38,
                                ),
                              ),
                              Container(
                                margin: order.paymentStatus != Constants.PAYMENT_STATUS_PAID && order.status != Constants.STATUS_CANCELLED ? EdgeInsets.only(left: 10.0, right: 10.0) : EdgeInsets.only(left: 0.0, right: 0.0),
                                child: order.paymentStatus != Constants.PAYMENT_STATUS_PAID && order.status != Constants.STATUS_CANCELLED ? Text('') : SizedBox.shrink(),
                                decoration: order.paymentStatus != Constants.PAYMENT_STATUS_PAID && order.status != Constants.STATUS_CANCELLED ? BoxDecoration(
                                  border: Border(
                                    left: BorderSide(
                                        width: 0.5,
                                        color: Colors.black12
                                    ),
                                  ),
                                ) : null,
                              ),
                              GestureDetector(
                                child: order.paymentStatus != Constants.PAYMENT_STATUS_PAID
                                    && order.status != Constants.STATUS_CANCELLED
                                    && order.status != Constants.STATUS_COMPLETE ? Text(
                                  S.of(context).pay_now,
                                  style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                  ),
                                ) : SizedBox.shrink(),
                                onTap: () {
                                  Routes.router.navigateTo(context, '/paynow/${order.id}');
                                },
                              ),
                            ],
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));

                col.children.add(Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Container(
                        width: 110.0,
                        margin: EdgeInsets.only(top: 10.0, bottom: 10.0, right: 10.0),
                        child: Text(
                          S.of(context).order_datetime,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 2,
                        ),
                      ),
                      Expanded(
                        child: Container(
                          margin: EdgeInsets.only(top: 10.0, bottom: 10.0),
                          alignment: Alignment.centerRight,
                          child: Text(
                            Utils.timestampToString(context, order.createdAt, withTime: true),
                            style: TextStyle(
                              color: Colors.black38,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border(
                      bottom: BorderSide(
                        width: 0.5,
                        color: Colors.black12,
                      ),
                    ),
                  ),
                ));

                return Container(
                  padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
                  child: col,
                  decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          width: 10,
                          color: Colors.black12,
                        )
                    ),
                  ),
                );
                break;
              case 3:
                Column col = Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[],
                );

                col.children.add(Container(
                  padding: EdgeInsets.only(top: 0.0, bottom: 16.0),
                  width: double.infinity,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        S.of(context).order_fulfillment,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 17.0,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      Text(
                        Utils.getOrderStatus(context, order.status),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 17.0,
                          fontWeight: FontWeight.bold,
                          color: Colors.orange,
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black26,
                        )
                    ),
                  ),
                ),);

                for (Fulfillment fulfillment in order.fulfillments) {
                  col.children.add(Container(
                    padding: EdgeInsets.only(top: 10.0, bottom: 10.0),
                    width: double.infinity,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.start,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          child: fulfillment.shippingMethod.isNotEmpty && fulfillment.trackingNumber != null && fulfillment.trackingNumber.isNotEmpty ?
                          Text(
                            '${fulfillment.shippingMethod} ${fulfillment.trackingNumber}',
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          ) : (fulfillment.shippingMethod.isNotEmpty ? Text(
                            '${fulfillment.shippingMethod}',
                            overflow: TextOverflow.ellipsis,
                            maxLines: 1,
                          ) : SizedBox.shrink()),
                        ),
                        Container(
                          child: fulfillment.note != null && fulfillment.note.isNotEmpty ?
                          Text(
                            '${fulfillment.note}',
                            style: TextStyle(
                              fontSize: 15.0,
                              color: Colors.black38,
                            ),
                            maxLines: 3,
                            overflow: TextOverflow.ellipsis,
                          ) : SizedBox.shrink(),
                        ),
                        Container(
                          child: Text(
                            '${Utils.utcDatetimeStringToLocalDatetimeString(context, fulfillment.createdAt, withTime: true)}',
                            style: TextStyle(
                              fontSize: 12.0,
                              color: Colors.black26,
                            ),
                          ),
                        ),
                      ],
                    ),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          width: 0.5,
                          color: Colors.black12,
                        ),
                      ),
                    ),
                  ));
                }

                return Container(
                  padding: EdgeInsets.only(left: 16.0, right: 16.0, top: 16.0, bottom: 16.0),
                  child: col,
                  decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                          width: 10,
                          color: Colors.black12,
                        )
                    ),
                  ),
                );
                break;
              default:
                return SizedBox();
            }
          },
        ),
      ),
      bottomNavigationBar: Container(
        padding: new EdgeInsets.only(left: 16.0, right: 16.0, top: 5.0, bottom: 5.0),
        color: new Color(0xFFA8A8FF),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Container(
                  padding: EdgeInsets.only(right: 10.0),
                  child: order.status == Constants.STATUS_PENDING && order.paymentStatus == Constants.PAYMENT_STATUS_UNPAID ?
                  TextButton(
                    child: Text(
                      S.of(context).cancel_order,
                    ),
                    onPressed: () {
                      _cancelOrder(context);
                    },
                  ) : SizedBox.shrink(),
                ),
                Container(
                  child: order.status == Constants.STATUS_COMPLETE && !order.hasComment ? ElevatedButton(
                    child: Text(
                      S.of(context).comment,
                    ),
                    onPressed: () {
                      Routes.router.navigateTo(context, '/new-comment/${order.id}');
                    },
                  ) : SizedBox.shrink(),
                ),
              ],
            ),
            Container(
              child: order.paymentStatus != Constants.PAYMENT_STATUS_PAID
                  && order.status != Constants.STATUS_CANCELLED
                  && order.status != Constants.STATUS_COMPLETE ?
              TextButton(
                child: Text(
                  S.of(context).pay_now,
                ),
                onPressed: () {
                  Routes.router.navigateTo(context, '/paynow/${order.id}');
                },
              ) : TextButton(
                child: Text(
                  S.of(context).order_again,
                ),
                onPressed: () {
                  Utils.orderAgain(context, order.cartInfo);
                },
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    if (!kIsWeb) {
      Util.getBytesFromAsset('assets/images/home.png', 100).then((value) {
        homeIcon = BitmapDescriptor.fromBytes(value);
      });
      Util.getBytesFromAsset('assets/images/delivery.png', 80).then((value) {
        deliveryIcon = BitmapDescriptor.fromBytes(value);
      });
      Util.getBytesFromAsset('assets/images/shop.png', 100).then((value) {
        shopIcon = BitmapDescriptor.fromBytes(value);
      });
    }
    _loadOrder();
  }
  
  _loadOrder() {
    HttpUtil.httpGet('v1/orders/${widget.orderId}',
      queryParameters: {
        'expand': 'cart_info,business_info',
      },
    ).then((data) {
      if (mounted) {
        setState(() {
          order = Order.fromJson(data);

          if (!kIsWeb) {
            if (order.shippingMethod == 'store-delivery' && order.status != Constants.STATUS_COMPLETE && order.status != Constants.STATUS_CANCELLED) {
              storeLatLng = LatLng(double.parse(order.businessInfo.address.lat),
                  double.parse(order.businessInfo.address.lng));
              customerLatLng = LatLng(double.parse(order.shippingAddress.lat),
                  double.parse(order.shippingAddress.lng));
              deliveryLatLng =
                  LatLng(order.shipperPosition.lat, order.shipperPosition.lng);

              _polyLine.clear();
              _polyLine.add(
                  Polyline(
                      polylineId: PolylineId('shipper-customer'),
                      color: Colors.green,
                      patterns: [
                        PatternItem.dash(20.0),
                        PatternItem.gap(10),
                      ],
                      width: 3,
                      points: [
                        order.shipperPosition.lat != 0.0 ? deliveryLatLng : storeLatLng,
                        customerLatLng,
                      ]
                  )
              );

              _markers.clear();
              _markers.add(Marker(
                markerId: MarkerId('shop_position'),
                position: storeLatLng,
                infoWindow: InfoWindow(
                  title: S
                      .of(context)
                      .store,
                  snippet: '',
                ),
                icon: shopIcon,
              ));
              _markers.add(Marker(
                markerId: MarkerId('customer_position'),
                position: customerLatLng,
                infoWindow: InfoWindow(
                  title: S
                      .of(context)
                      .customer,
                  snippet: order.shippingAddress.addressLine1,
                ),
                icon: homeIcon,
              ));
              if (order.shipperPosition.lat != 0.0 &&
                  order.shipperPosition.lng != 0.0) {
                _markers.add(Marker(
                  markerId: MarkerId('shipper_position'),
                  position: deliveryLatLng,
                  infoWindow: InfoWindow(
                    title: S
                        .of(context)
                        .delivery_guy,
                    snippet: '',
                  ),
                  icon: deliveryIcon,
                ));
              }
            }
          }
        });
      }
    }).catchError((error) {
      Utils.showMessageDialog(context, error, onOk: () {
        Routes.router.navigateTo(context, "/orders", replace: true);
      });
    });
  }

  _cancelOrder(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(S.of(context).warning),
          content: Text(S.of(context).are_you_sure_to_cancel_the_order),
          actions: <Widget>[
            TextButton(
              child: Text(
                S.of(context).no,
              ),
              style: TextButton.styleFrom(
                backgroundColor: Theme.of(context).primaryColor,
              ),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              child: Text(
                S.of(context).yes_i_am_sure,
              ),
              onPressed: () {
                Navigator.of(context).pop();
                _processCancelOrder();
                if (mounted) {
                  setState(() {
                    order = null;
                  });
                }
              },
            ),
          ],
        );
      }
    );
  }
  
  _processCancelOrder() {
    HttpUtil.httpGet(
      'v1/order-cancel/${widget.orderId}'
    ).then((data) {
      if (mounted) {
        setState(() {
          order = Order.fromJson(data);
        });
      }
    }).catchError((error) {
      Utils.showMessageDialog(context, error, onOk: () {
        Routes.router.navigateTo(context, "/orders", replace: true);
      });
    });
  }
}