
import 'package:flutter/material.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:provider/provider.dart';

import 'package:twong/api/index.dart';
import 'package:twong/config/pay_config.dart';
import 'package:twong/providers/address.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/config/style.dart';
import 'package:twong/models/index.dart';
import 'package:twong/router/index.dart';
import 'package:twong/widgets/address_bar.dart';
import 'package:twong/widgets/address_item.dart';
import 'package:twong/widgets/app_bar.dart';
import 'package:twong/widgets/circle_check_box.dart';
import 'package:twong/widgets/floading.dart';
import 'package:twong/widgets/payment.dart';

class OrderSubmitPage extends StatefulWidget {
  final dynamic info;
  OrderSubmitPage(this.info, {Key key}): super(key: key);

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

}

class _OrderSubmitPageState extends State<OrderSubmitPage> {
  Address _address;
  ConfirmInfo _info;
  ComputeData _data;
  num _integral = 0;
  Map<String, num> _priceMap = Map<String, num>();

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

    Utils.loading();
    if(widget.info is ProductInfo) {
      Network.inst.addCart(productId: widget.info.product_id,
          uniqueId: widget.info.unique).then((cartId) {
        Network.inst.confirmOrder(cartId).then((confirmInfo) {
          setState(() {
            _info = confirmInfo;
            _address = confirmInfo.addressInfo;
          });
          _computeOrder();
          Utils.closeLoading();
        });
      });
    } else if(widget.info is String) {
      Network.inst.confirmOrder(widget.info).then((confirmInfo) {
        setState(() {
          _info = confirmInfo;
          _address = confirmInfo.addressInfo;
        });
        _computeOrder();
        Utils.closeLoading();
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:DAppBar("提交订单"),
      body: Container(
        color: DColors.back,
        padding: EdgeInsets.only(left: 10.px, right: 10.px),
        child: ListView(
          physics: ClampingScrollPhysics(),
          children: [
            _buildAddress(),
            _buildProducts(),
            _buildIntegral(),
            _buildExpress(),
            _buildExtInfo(),
            // _buildPayment(),
            _buildResult()
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: 40.px,
          padding: EdgeInsets.only(left: 16.px, right: 16.px),
          child: Row(
            children: [
              Text("合计：", style: TextStyle(fontSize: 14.px)),
              Text(I18n.$, style: TextStyle(fontSize: 12.px, color: DColors.price)),
              Text(Utils.formatRMB(_data == null ? 0 : _data.pay_price),
                  style: TextStyle(fontSize: 18.px, color: DColors.price)),
              Spacer(),
              FlatButton(
                onPressed: _submitOrder,
                shape: StadiumBorder(),
                child: Text("立即结算", style: TextStyle(color: Colors.white)),
                color: Colors.red,
              )
            ],
          ),
        ),
      ),
    );
  }

  _computeOrder() {
    Network.inst.computedOrder(_info.orderKey, addressId: _address.id,
      payType: PayConfig.payTypes.first.key, useIntegral: _integral).then((ComputeInfo info) {
        setState(() {
          _data = info.result;
          _priceMap["积分抵扣"] = - info.result.deduction_price.toDouble();
          _priceMap["运费"] = info.result.pay_postage;
        });
    }).catchError((err, stack) {
      // Log.d(stack);
      BotToast.showText(text: err.toString());
      Navigator.pop(context);
    });
  }

  _submitOrder() {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.px), topRight: Radius.circular(10.px)
        )),
        builder: (BuildContext context) {
          return Payment(PaymentInfo(_info.orderKey, _address.id, _integral));
        });
  }

  Widget _styleBox({ Widget child }) {
    return Container(
        child: child,
        margin: EdgeInsets.only(top: 12.px),
        padding: EdgeInsets.only(
            top: 6.px, bottom: 6.px, left: 12.px, right: 12.px),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(6.px))
        )
    );
  }

  void _selectAddress() {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.px), topRight: Radius.circular(10.px)
        )),
        builder: (BuildContext context) {
          return AddressBar(onSelected: _onSelectedAddress, address: _address);
        });
  }

  void _onSelectedAddress(Address address) {
    setState(() {
      _address = address;
    });
  }

  Widget _buildAddress() {
    return InkWell(
      onTap: _selectAddress,
      child: _styleBox(
        child: _address == null ? Container(
          child: Text("设置收货地址", style: TextStyle(fontSize: 16.px)),
        ) : AddressItem(_address, editable: false),
      ),
    );
  }

  Widget _buildProducts() {
    int count = 0;
    if (_info != null) {
      for (var cart in _info.cartInfo) {
        count += cart.cart_num;
      }
    }
    return _styleBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("共 $count 件商品"),
          Divider(),
          _buildProductList()
        ],
      ),
    );
  }

  Widget _buildProductList() {
    List<Widget> widgets = List<Widget>();
    if (_info != null) {
      for (var info in _info.cartInfo) {
        widgets.add(Container(
          width: double.infinity,
          child: Row(
            children: [
              Image(
                  height: 86.px, width: 86.px,
                  image: CachedNetworkImageProvider(info.productInfo["image"])
              ),
              Expanded(child: Container(
                  height: 86.px,
                  margin: EdgeInsets.only(left: 12.px, right: 12.px),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Expanded(child: Text(
                                  info.productInfo["store_name"])),
                              Text(" x ${info.cart_num}", style:
                              TextStyle(color: Colors.grey, fontSize: 16.px)),
                            ]),
                        Text(info.productInfo["attrInfo"]["suk"],
                            style: TextStyle(color: Colors.grey, fontSize: 14.px)),
                        Spacer(),
                        Text(Utils.formatRMB(info.truePrice, show: true),
                            style: TextStyle(
                                color: Colors.red, fontSize: 16.px)),
                      ])
              ))
            ],
          ),
        ));
      }
    }
    return Column(children: widgets);
  }

  Widget _buildIntegral() {
    return _styleBox(
      child: Row(
        children: [
          Expanded(child: Text("积分抵扣")),
          CircleCheckBox((value) {
            _integral = value ? num.parse(_info.userInfo.integral) : 0;
            _computeOrder();
          }, size: 20.px, color: DColors.Main, child: RichText(
            text: TextSpan(
                text: "当前可用积分: ",
                style: TextStyle(color: Colors.black),
                children: [
                  TextSpan(
                  text: _info == null ? "0" : _info.userInfo.integral,
                  style: TextStyle(color: Colors.red)
                )
              ]
            ),
          ), initValue: _integral > 0)
        ],
      ),
    );
  }

  Widget _buildExpress() {
    var postage = _data == null ? 0 : _data.pay_postage;
    return _styleBox(
      child: Row(
        children: [
          Expanded(child:Text("快递费用")),
          Text(postage > 0 ? Utils.formatRMB(postage, show: true)
              : "免运费", style: TextStyle(color: Colors.grey)),
        ],
      ),
    );
  }

  Widget _buildExtInfo() {
    return _styleBox(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text("备注信息"),
          TextField(
            keyboardType: TextInputType.multiline,
            decoration: InputDecoration(
              hintText: "请添加备注(150字以内)",
              border: InputBorder.none,
            ),
          )
        ],
      ),
    );
  }

  Widget _buildResult() {
    List<Widget> widgets = List<Widget>();
    widgets.add(Row(
      children: [
        Expanded(child: Text("商品总价")),
        Text(_data == null ? "-" : Utils.formatRMB(_data.total_price, show: true))
      ],
    ));
    for(var item in _priceMap.keys) {
      var price = _priceMap[item];
      if (price != 0) {
        var sign = price > 0 ? "+" : "-";
        widgets.add(Container(
          margin: EdgeInsets.only(top: 4.px),
          child: Row(
            children: [
              Expanded(child: Text(item)),
              Text("$sign${Utils.formatRMB(price.abs(), show: true)}",
                style: TextStyle(color: Colors.grey))
            ],
          ),
        ));
      }
    }
    return _styleBox(child: Column(children: widgets));
  }
}