
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/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/num_counter.dart';

class ProductAttrPage extends StatefulWidget {
  final Details data;
  final bool showAll;
  final bool isCart;
  final Function(ProductInfo) cartBack;
  final Function(ProductInfo) callback;
  ProductAttrPage(this.data, {Key key, this.isCart = false, this.showAll = false,
    this.callback, this.cartBack }): super(key: key);

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

class _ProductAttrPageState extends State<ProductAttrPage> {
  int _buyCount = 1;
  ProductInfo _selectAttr;
  List<String> _selectSuk = List<String>();

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

    if(widget.data.productAttr.length > 0) {
      var attrList = widget.data.productValue as Map<String, dynamic>;
      for (var i in widget.data.productAttr) {
        // var sku = i.attr_values.firstWhere((element) {
        //   return attrList.containsKey(element);
        // });
        var sku = i.attr_values.first;
        _selectSuk.add(sku);
      }
      _selectAttr = ProductInfo.fromJson(attrList.values.first);
    } else {
      _setDefault();
    }
  }

  void _setDefault({int stock }) {
    _selectAttr = ProductInfo();
    _selectAttr.image = widget.data.storeInfo.image;
    _selectAttr.product_id = widget.data.storeInfo.id;
    _selectAttr.price = widget.data.storeInfo.price;
    _selectAttr.vip_price = widget.data.storeInfo.vip_price;
    _selectAttr.stock = stock == null ? widget.data.storeInfo.stock : stock;
  }

  void _updateSelect() {
    var attrList = widget.data.productValue as Map<String, dynamic>;
    var _skuKey = "";
    for(var sku in _selectSuk) {
      _skuKey = "$_skuKey,$sku";
    }

    var key = _skuKey.replaceFirst(",", "");
    if(attrList.containsKey(key)) {
      setState(() {
        _selectAttr =
            ProductInfo.fromJson(attrList[key]);
      });
    } else {
      Log.w("not fond [$key] in sku values");
      setState(() {
        _setDefault(stock: 0);
      });
    }
  }

  Widget _buildHeader() {
    return Container(
      height: 100.px,
      padding: EdgeInsets.all(10.px),
      child: Flex(
        direction: Axis.horizontal,
        children: [
          InkWell(
            onTap: () {
              Utils.showPhoto(image: _selectAttr.image);
            },
            child: CachedNetworkImage(imageUrl: _selectAttr.image),
          ),
          Expanded(
              child: Container(
                padding: EdgeInsets.only(left: 10.px),
                child: Column(
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Expanded(child: Container(
                          height: 30.px,
                          width: double.infinity,
                          child: Text(widget.data.storeInfo.store_name),
                        )),
                        InkWell(
                          onTap: () => Navigator.pop(context),
                          child: Icon(Icons.close, color: Colors.grey, size: 18.px),
                        )
                      ],
                    ),
                    Spacer(),
                    Flex(
                      direction: Axis.horizontal,
                      children: [
                        Text('￥' + _selectAttr.price.toString(),
                            style: TextStyle(
                                color: DColors.price, fontSize: 16.px)),
                        Spacer(),
                        Text('库存：${_selectAttr.stock}', style:
                        TextStyle(color: Colors.grey,
                            fontWeight: FontWeight.w300,
                            fontSize: 12.px)),
                        Spacer()
                      ],
                    )
                  ],
                ),
              )
          ),
        ],
      ),
    );
  }

  Widget _buildAttrButton(String name, int idx) {
    if (_selectSuk.contains(name)) {
      return Container(
        height: 30.px,
        margin: EdgeInsets.all(3.px),
        padding: EdgeInsets.only(left: 16.px, right: 16.px, top: 6.px),
        child: Text(
            name, style: TextStyle(color: Colors.white, fontSize: 12.px)),
        decoration: BoxDecoration(
            color: DColors.Main,
            borderRadius: BorderRadius.all(Radius.circular(20.px))
        ),
      );
    }
    return InkWell(
          onTap: () {
            _selectSuk[idx] = name;
            _updateSelect();
          },
          child: Container(
            height: 30.px,
            margin: EdgeInsets.all(3.px),
            padding: EdgeInsets.only(left: 16.px, right: 16.px, top: 6.px),
            decoration: ShapeDecoration(
              color: Colors.white,
              shape: RoundedRectangleBorder(side: BorderSide(width: 0.5.px, color: DColors.Main),
                    borderRadius: BorderRadius.all(Radius.circular(20.px))),
            ),
            child: Text(
                name, style: TextStyle(color: DColors.Main, fontSize: 12.px)),
          ),
    );
  }

  Widget _buildAttr(ProductAttr attr, int idx) {
    var widgets = List<Widget>();
    for(var attrName in attr.attr_values) {
      widgets.add(_buildAttrButton(attrName, idx));
    }

    return Flex(
      direction: Axis.vertical,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Container(
          width: double.infinity,
          padding: EdgeInsets.only(bottom: 2.px),
          child: Text(attr.attr_name),
        ),
        Container(
          child: Wrap(
            direction: Axis.horizontal,
            children: widgets,
          ),
        )
      ],
    );
  }

  Widget _buildProductAttr () {
    var widgets = List<Widget>();
    var idx = 0;
    for(var attr in widget.data.productAttr) {
      widgets.add(_buildAttr(attr, idx++));
    }

    return Container(
      width: MediaQuery.of(context).size.width,
      padding: EdgeInsets.all(12.px),
      child: Flex(
        mainAxisSize: MainAxisSize.max,
        direction: Axis.vertical,
        children: widgets,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(child: Container(
      height: widget.data.productAttr.length > 0 ? null : 260.px,
      child: Column(
        children: [
          _buildHeader(),
          Expanded(child: _buildProductAttr()),
          _buildCounter(),
          _buildButtons(),
          Container(height: 6.px)
        ],
      ),
    ));
  }

  Widget _buildCounter() {
    return Container(
      margin: EdgeInsets.only(left: 12.px, right: 12.px, bottom: 6.px),
      child: Row(
        children: [
          Text("购买数量"),
          Spacer(),
          NumCounter(num: 1, onChange: (value) {
            _buyCount = value;
          }, max: _selectAttr.stock),
        ],
      ),
    );
  }

  Widget _buildButtons() {
    if (_selectAttr.stock < 1) {
      return Container(
        width: 400.px,
        margin: EdgeInsets.only(left: 10.px, right: 10.px),
        child: FlatButton(
          color: DColors.Main,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
          onPressed: null,
          disabledColor: Colors.grey,
          child: Text("暂时无货", style: TextStyle(color: Colors.white)),
        ),
      );
    }
    if (!widget.showAll) {
      return Container(
        width: 400.px,
        margin: EdgeInsets.only(left: 10.px, right: 10.px),
        child: FlatButton(
          color: DColors.Main,
          shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
          onPressed: _submitClick,
          child: Text(widget.isCart ? "加入购物车" : "立即购买", style: TextStyle(color: Colors.white)),
        ),
      );
    } else {
      return Row(
        children: [
          Expanded(child: Container(
            margin: EdgeInsets.only(left: 12.px, right: 10.px),
            child: FlatButton(
              color: DColors.Main,
              shape: StadiumBorder(),
              onPressed: _toCart,
              child: Text("加入购物车", style: TextStyle(color: Colors.white)),
            ),
          )),Expanded(child: Container(
            margin: EdgeInsets.only(left: 12.px, right: 10.px),
            child: FlatButton(
              color: DColors.Main,
              shape: StadiumBorder(),
              onPressed: _toBuy,
              child: Text("立即购买", style: TextStyle(color: Colors.white)),
            ),
          ))
        ],
      );
    }
  }

  void _submitClick() {
    if(widget.isCart) {
      _toCart();
    } else {
      _toBuy();
    }
  }

  void _toBuy() {
    Navigator.pop(context);
    Navigator.pushNamed(context, RouteNames.submitOrder, arguments: _selectAttr);
    widget.callback?.call(_selectAttr);
  }

  void _toCart() {
    Network.inst.addCart(cartNum: _buyCount, productId: _selectAttr.product_id,
        uniqueId: _selectAttr.unique, news: 0).then((res) {
          Log.d(res);
          BotToast.showText(text:"商品已经添加到购物车!");
          Navigator.pop(context);
          widget.cartBack?.call(_selectAttr);
    });
  }
}