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

import 'package:twong/api/index.dart';
import 'package:twong/config/pay_config.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/app_bar.dart';
import 'package:twong/widgets/circle_check_box.dart';
import 'package:twong/widgets/payment.dart';

class OrderSubmitPage extends StatefulWidget {
  final ProductInfo 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;
  double _integral = 0;
  Map<String, double> _priceMap = Map<String, double>();

  @override
  void initState() {
    super.initState();
    Log.d(widget.info.toJson());

    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();
            Log.d(confirmInfo.toJson());
          });
    });
  }

  @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: 16.px)),
              Text("${I18n.$}${_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["运费"] = double.parse(info.result.pay_postage);
        });
    }).catchError((err) {
      BotToast.showText(text: err.toString());
    });
  }

  _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))
        )
    );
  }

  Widget _buildAddressList() {
    List<Widget> widgets = List<Widget>();
    if (widgets.length < 1) {
      return Column(
        children: [
          Container(height: 280.px),
          Container(
            padding: EdgeInsets.only(left: 16.px, right: 16.px),
            width: double.infinity,
            child: FlatButton(
              color: DColors.Main,
              shape: StadiumBorder(),
              child: Text("添加收货地址", style: TextStyle(color: Colors.white)),
              onPressed: () async {
                var ret = await Navigator.pushNamed(context, RouteNames.editAddress);
                Log.d(ret);
              },
            ),
          )
        ],
      );
    }
    return Column(
      children: widgets,
    );
  }

  void _selectAddress() {
    showModalBottomSheet(
        context: context,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10.px), topRight: Radius.circular(10.px)
        )),
        builder: (BuildContext context) {
          return SafeArea(child: Container(
            height: 360.px,
            child: ListView(
              physics: ClampingScrollPhysics(),
              children: [
                Text("选择地址", style: TextStyle(fontSize: 16.px), textAlign: TextAlign.center),
                _buildAddressList()
              ],
            ),
          ));
        });
    Network.inst.getAddress().then((res) {
      Log.d(res);
    });
  }

  Widget _buildAddress() {
    return InkWell(
      onTap: _selectAddress,
      child: _styleBox(
        child: _address == null ? Container(
          child: Text("设置收货地址", style: TextStyle(fontSize: 16.px)),
        ) : Container(
          child: Row(
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(children: [
                    Text(_address.real_name),
                    Container(width: 20.px),
                    Text(_address.phone),
                  ],),
                  Text("${_address.province}${_address.city}${_address.district}${_address.detail}"),
                ],
              ),
              Spacer(),
              Icon(Icons.keyboard_arrow_right, size: 26.px)
            ],
          ),
        )
      ),
    );
  }

  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 ? double.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)
                )
              ]
            ),
          ))
        ],
      ),
    );
  }

  Widget _buildExpress() {
    var postage = _data == null ? 0 : double.parse(_data.pay_postage);
    return _styleBox(
      child: Row(
        children: [
          Expanded(child:Text("快递费用")),
          Text(postage > 0 ? Utils.formatRMB(postage)
              : "免运费", 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 _buildPayment() {
  //   List<Widget> widgets = List<Widget>();
  //   for(var item in PayConfig.payTypes) {
  //     widgets.add(InkWell(child: Container(
  //       height: 44.px,
  //       width: double.infinity,
  //       margin: EdgeInsets.only(bottom: 8.px),
  //       decoration: ShapeDecoration(
  //         color: Colors.white,
  //         shape: RoundedRectangleBorder(
  //             side: BorderSide(width: 0.5.px, color: _payType == item ? DColors.Main : Colors.grey),
  //             borderRadius: BorderRadius.all(Radius.circular(6.px))),
  //       ),
  //       child: Center(child: Text(item)),
  //     ), onTap: _payType == item ? null : () {
  //       setState(() {
  //         _payType = item;
  //       });
  //     }));
  //   }
  //   return _styleBox(
  //     child: Column(
  //       crossAxisAlignment: CrossAxisAlignment.start,
  //       children: [
  //         Text("支付方式"),
  //         Divider(),
  //         Column(children: widgets)
  //       ],
  //     ),
  //   );
  // }

  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));
  }
}