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

import 'package:twong/api/index.dart';
import 'package:twong/pages/tabs.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/num_counter.dart';
import 'package:twong/widgets/circle_check_box.dart';

class CartPage extends StatefulWidget {
  final bool show;
  CartPage({Key key, this.show = false}):super(key: key);

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

class _CartPageState extends State<CartPage> {
  CartList _cartList;
  num _price = 0;
  bool _editMode = false;
  Map<String, CartInfo> _priceMap = Map<String, CartInfo>();

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

    Cache.updateToken(null);
    loadData();
  }

  void loadData() {
    Network.inst.getCartList().then((data) {
      if(!mounted) return;
      setState(() {
        _cartList = data;
      });
    });
  }

  void _editClick () {
    setState(() {
      _editMode = !_editMode;
    });
  }

  Widget _buildBottom () {
    return Row(
      children: <Widget>[
        Expanded(child: Container(
            margin: EdgeInsets.only(left: 12.px, right: 12.px),
            child: CircleCheckBox((value) {
              if(value) {
                for (var item in _cartList.valid) {
                  _priceMap[item.id.toString()] = item;
                }
              } else {
                _priceMap.clear();
              }
              _calcPrice();
            }, child: Text("全选"), right: false, initValue:
              _priceMap.length == _cartList?.valid?.length)
        )),
        _editMode ? Spacer() : Container(
          margin: EdgeInsets.only(right: 8.px),
          child: Row(
            children: <Widget>[
              Text('总计:'),
              Text(Utils.formatRMB(_price, show: true),
                  style: TextStyle(color: Colors.red, fontSize: 16.px)),
            ],
          ),
        ),
        Container(
          width: 106.px,
          margin: EdgeInsets.only(right: 10.px),
          child: _editMode ? OutlineButton(
              onPressed: () {},
              highlightedBorderColor: DColors.Main,
              child: Text('删除', style: TextStyle(color: DColors.Main)),
              borderSide: BorderSide(color: Colors.red, width: 0.5.px),
              shape: StadiumBorder()) : FlatButton(
            disabledColor: Colors.grey,
            color: DColors.Main,
            onPressed: () {
              var args = "";
              for(var item in _priceMap.keys) {
                if(_priceMap.values.last.id.toString() == item) {
                  args += item;
                } else {
                  args += (item + ",");
                }
              }
              Navigator.pushNamed(context, RouteNames.submitOrder, arguments: args);
            },
            child: Text('去结算', style: TextStyle(color: Colors.white)),
            shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(20.px)),
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: DAppBar("购物车", autoLeading: widget.show, actions: <Widget>[
        GestureDetector(
          onTap: _editClick,
          child: Container(
            width: 60.px,
            alignment: Alignment.center,
            child: Text(_editMode ? '完成' : '编辑',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.white)),
          ),
        )
      ]),
      body: SafeArea(
        child: Container(
          color: DColors.back,
          child: Column(
            children: [
              _buildHeader(),
              Expanded(child: _cartList == null
                  ? Center(child: Utils.loadingWidget)
                  : ListView(
                physics: ClampingScrollPhysics(),
                children: [
                  _buildNoData(),
                  _buildCartList(),
                  _buildInvalidList()
                ],
              )),
              Container(
                height: 50.px,
                color: Colors.white,
                child: _buildBottom(),
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildHeader() {
    var style = TextStyle(color: Colors.grey, fontSize: 11.px);
    return Container(
      height: 32.px,
      color: Colors.white,
      width: double.infinity,
      padding: EdgeInsets.only(left: 12.px, right: 12.px),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Icon(IconFonts.done_outline, color: Colors.grey, size: 16.px),
          Text(" 官方直营 100% 正品保障", style: style),
          Spacer(),
          Icon(IconFonts.done_outline, color: Colors.grey, size: 16.px),
          Text(" 所有商品精挑细选", style: style),
          Spacer(),
          Icon(IconFonts.done_outline, color: Colors.grey, size: 16.px),
          Text(" 售后无忧", style: style),
        ],
      ),
    );
  }

  Widget _buildNoData() {
    if(_cartList.valid.length < 1 && _cartList.invalid.length < 1) {
      return Container(
        height: 300.px,
        child: Center(child: Text("暂无商品，去添加点什么吧")),
      );
    } else {
      return Container();
    }
  }

  Widget _buildCartList() {
    List<Widget> widgets = List<Widget>();
    for (var info in _cartList.valid) {
      widgets.add(Container(
        margin: EdgeInsets.only(bottom: 6.px),
        padding: EdgeInsets.all(6.px),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10.px)
        ),
        child: Row(
          children: [
            Container(
              width: 32.px,
              height: 88.px,
              child: CircleCheckBox((value)=> _onSelected(value, info),
                  child: Container(), initValue: _priceMap.containsKey(info.id.toString())),
            ),
            Image(
                height: 88.px, width: 88.px,
                image: CachedNetworkImageProvider(info.productInfo["image"])
            ),
            Expanded(child: Container(
                height: 88.px,
                margin: EdgeInsets.only(left: 12.px, right: 12.px),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(info.productInfo["store_name"],
                          style: TextStyle(fontSize: 12.px)),
                      Text(info.productInfo["attrInfo"]["suk"],
                          style: TextStyle(color: Colors.grey, fontSize: 12.px)),
                      Spacer(),
                      Row(children: [
                        Expanded(child: Text(Utils.formatRMB(info.truePrice, show: true),
                            style: TextStyle(color: Colors.red, fontSize: 14.px))),
                        NumCounter(num: info.cart_num, onChange: (value) {
                          Network.inst.cartNum(id: info.id, number: value).then((res) {
                            info.cart_num = value;
                            if(_priceMap.containsKey(info.id.toString())) {
                              _priceMap[info.id.toString()].cart_num = value;
                              _calcPrice();
                            }
                          });
                        }, max: info.trueStock)
                      ]),
                    ])
            ))
          ]),
      ));
    }
    return Container(
      margin: EdgeInsets.only(left: 12.px, right: 12.px, top: 6.px),
      child: Column(children: widgets)
    );
  }

  _onSelected(bool selected, CartInfo info) {
    Log.d(selected);
    if (selected) {
      _priceMap[info.id.toString()] = info;
    } else {
      _priceMap.remove(info.id.toString());
    }
    _calcPrice();
  }

  _calcPrice() {
    num total = 0;
    for(var info in _priceMap.values) {
      total += info.truePrice * info.cart_num;
    }

    setState(() {
      _price = total;
    });
  }

  Widget _buildInvalidList() {
    if (_cartList.invalid.length < 1) {
      return Container();
    }

    List<Widget> widgets = List<Widget>();
    for (var info in _cartList.invalid) {
      widgets.add(Container(
        margin: EdgeInsets.only(bottom: 6.px),
        padding: EdgeInsets.all(6.px),
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(10.px)
        ),
        child: Row(
            children: [
              Image(
                  height: 88.px, width: 88.px,
                  image: CachedNetworkImageProvider(info.productInfo["image"])
              ),
              Expanded(child: Container(
                  height: 88.px,
                  margin: EdgeInsets.only(left: 12.px, right: 12.px),
                  child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(info.productInfo["store_name"],
                            style: TextStyle(fontSize: 14.px)),
                        Text(info.productInfo["attrInfo"]["suk"],
                            style: TextStyle(
                                color: Colors.grey, fontSize: 13.px)),
                        Spacer(),
                        Row(children: [
                          Expanded(child: Text(Utils.formatRMB(
                              info.truePrice, show: true),
                              style: TextStyle(
                                  color: Colors.red, fontSize: 14.px))),
                          Container(
                            width: 68.px,
                            height: 24.px,
                            child: OutlineButton(
                                onPressed: () {},
                                highlightedBorderColor: DColors.Main,
                                child: Text('删除',
                                    style: TextStyle(color: DColors.Main)),
                                borderSide: BorderSide(
                                    color: Colors.red, width: 0.5.px)),
                          )
                        ]),
                      ])
              ))
            ]),
      ));
    }
    return Container(
      margin: EdgeInsets.only(left: 12.px, right: 12.px),
      child: Container(
        width: double.infinity,
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(6.px)
        ),
        padding: EdgeInsets.all(6.px),
        child: Column(
          children: [
            Row(
              children: [
                Expanded(child: Text("失效的商品")),
                Container(
                  width: 78.px,
                  height: 26.px,
                  margin: EdgeInsets.only(bottom: 2.px),
                  child: OutlineButton(
                    onPressed: () {},
                    shape: StadiumBorder(),
                    highlightedBorderColor: DColors.Main,
                    child: Text('全部删除', style: TextStyle(color: DColors.Main)),
                    borderSide: BorderSide(color: Colors.red, width: 0.5.px),
                  ),
                ),
              ],
            ),
            Column(children: widgets)
          ],
        ),
      ),
    );
  }
}