import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:twong/api/index.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/circle_check_box.dart';
import 'package:twong/widgets/num_counter.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;
  bool _editMode = false;
  bool _selectAll = false;

  @override
  void initState() {
    super.initState();
    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) {
              _selectAll = value;
            }, child: Text("全选"), right: false)
        )),
        _editMode ? Spacer() : Container(
          margin: EdgeInsets.only(right: 8.px),
          child: Row(
            children: <Widget>[
              Text('总计:'),
              Text(Utils.formatRMB(6999, 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: () {
              Navigator.pushNamed(context, RouteNames.submitOrder);
            },
            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)),
          ),
        )
      ]),
      bottomNavigationBar: SafeArea(
        child: Container(
          height: 50.px,
          color: Colors.white,
          child: _buildBottom(),
        ),
      ),
      body: Container(
        color: DColors.back,
        child: _cartList == null ? Center(child: CircularProgressIndicator())
            : ListView(
          physics: ClampingScrollPhysics(),
          children: [
            _buildCartList(),
            _buildInvalidList()
          ],
        ),
      ),
    );
  }

  Widget _buildCartList() {
    List<Widget> widgets = List<Widget>();
    for (var info in _cartList.valid) {
      Log.d(info.toJson());
      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: 100.px, width: 100.px,
                image: CachedNetworkImageProvider(info.productInfo["image"])
            ),
            Expanded(child: Container(
                height: 100.px,
                margin: EdgeInsets.only(left: 12.px, right: 12.px),
                child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(info.productInfo["store_name"], style: TextStyle(fontSize: 15.px)),
                      Text(info.productInfo["attrInfo"]["suk"],
                          style: TextStyle(color: Colors.grey, fontSize: 14.px)),
                      Spacer(),
                      Row(children: [
                        Expanded(child: Text(Utils.formatRMB(info.truePrice, show: true),
                            style: TextStyle(color: Colors.red, fontSize: 16.px))),
                        NumCounter(num: info.cart_num, onChange: (value) {
                          Log.d(info.toJson());
                          Network.inst.cartNum(id: info.id, number: value);
                        }, max: info.trueStock)
                      ]),
                    ])
            ))
          ],
        ),
      ));
    }
    return Container(
      width: 350.px,
      margin: EdgeInsets.all(12.px),
      child: Column(children: widgets)
    );
  }

  Widget _buildInvalidList() {
    List<Widget> widgets = List<Widget>();

    return Container(
      child: Column(children: widgets),
    );
  }
}