import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:zhiying_base_widget/pages/goods_details_page/goods_details_page.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_list_style_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_model.dart';
import 'package:zhiying_base_widget/widgets/home/home_goods/models/home_goods_style_model.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

// ignore: must_be_immutable
class HomeGoodsItemSingle extends StatelessWidget {
  final HomeGoodsModel goods;
  final HomeGoodsStyleModel style;
  Map<String, dynamic> data;
  final double marginLeft;
  final double marginRight;
  final double marginTop;
  final double marginBottom;
  final String indexImage;

  ///排序标题

  HomeGoodsItemSingle(this.goods, this.style, {Key key, this.data, this.marginBottom = 4, this.marginTop = 4, this.marginLeft = 12.5, this.marginRight = 12.5, this.indexImage})
      : super(key: key) {
    if (this.data != null && this.data.containsKey('data')) {
      String data = this.data['data'];
      Map<String, dynamic> json = Map<String, dynamic>.from(jsonDecode(data));
      this.data = json;
    }
  }

  /// 跳到商品详情
  void _onJumpGoodsDetails(BuildContext context, HomeGoodsModel goods) {
    RouterUtil.hideKeyboard(context);
    Navigator.push(context, CupertinoPageRoute(builder: (_) => GoodsDetailsPage(goods.toJson())));
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () => _onJumpGoodsDetails(context, goods),
      child: Stack(
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(left: marginLeft, right: marginRight, top: marginTop, bottom: marginBottom),
            padding: EdgeInsets.all(7.5),
            decoration: BoxDecoration(color: Colors.white, borderRadius: BorderRadius.all(Radius.circular(7.5))),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Container(
                  width: 126,
                  height: 126,
                  margin: EdgeInsets.only(right: 10),
                  child: ClipRRect(
                    borderRadius: BorderRadius.circular(7.5),
                    child: CachedNetworkImage(
                      imageUrl: goods.goodImage,
                      fit: BoxFit.fitHeight,
                    ),
                  ),
                ),
                Expanded(
                  child: Container(
                    height: 126,
                    width: double.infinity,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          width: double.infinity,
                          child: _createTitle(),
                        ),
                        style?.listStyle?.hotRank?.isOpen == "0" ? _createShop() : Container(),
                        _createCupone(),
                        style?.listStyle?.hotRank?.isOpen == "0" ? Expanded(child: Container()) : Container(),
                        _createBottom(),
                        style?.listStyle?.hotRank?.isOpen == "1" ? Expanded(child: Container()) : Container(),
                        style?.listStyle?.hotRank?.isOpen == "1" ? _buildHotItem() : Container()
                      ],
                    ),
                  ),
                )
              ],
            ),
          ),
          style?.listStyle?.hotRank?.isOpen == "1"
              ? Align(
                  alignment: Alignment.topLeft,
                  child: Container(
                    decoration: BoxDecoration(image: DecorationImage(image: CachedNetworkImageProvider(indexImage ?? ""))),
                    margin: EdgeInsets.only(left: 20, top: 4),
                    height: 30,
                    width: 30,
                  ),
                )
              : Container(
                  width: 0,
                  height: 0,
                )
        ],
      ),
    );
  }

  Widget _createTitle() {
    List<InlineSpan> list = List();
    if (goods.providerName != null && goods.providerName != '') {
      HomeGoodsStyleModelProviders providers;
      int providersLength = style?.listStyle?.providers?.length ?? 0;
      if (providersLength > 0) {
        for (int i = 0; i < style?.listStyle?.providers?.length ?? 0; i++) {
          HomeGoodsStyleModelProviders item = style.listStyle?.providers[i];
          if (goods.provider == item.type) {
            providers = item;
            break;
          }
        }
      }

      list.add(WidgetSpan(
        child: Container(
          padding: EdgeInsets.only(left: 2, right: 2, top: 3, bottom: 3),
          margin: EdgeInsets.only(right: 4),
          child: Text(
            goods.providerName,
            style: TextStyle(
              fontSize: 9,
              height: 1,
              // color: HexColor.fromHex(style.providerNameColor),
              color: HexColor.fromHex(providers?.providerNameColor),
            ),
          ),
          decoration: BoxDecoration(
              // color: HexColor.fromHex(style.providerNameBackgroundColor),
              color: HexColor.fromHex(providers?.providerBgColor),
              borderRadius: BorderRadius.circular(2.5)),
        ),
      ));
    }
    list.add(TextSpan(
      text: goods.goodTitle,
      style: TextStyle(fontSize: 15, color: HexColor.fromHex('#333333'), fontWeight: style?.listStyle?.isTitleBold=="1"? FontWeight.bold:FontWeight.w500),
    ));
    return RichText(
      maxLines: 2,
      overflow: TextOverflow.ellipsis,
      text: TextSpan(children: list),
    );
  }

  Widget _createShop() {
    return Container(
      margin: EdgeInsets.only(top: 5),
      width: double.infinity,
      child: Row(
        children: <Widget>[
          Container(
            width: 15,
            height: 15,
            margin: EdgeInsets.only(right: 2),
            child: CachedNetworkImage(
              imageUrl: style?.listStyle?.shopIcon ?? '',
              fit: BoxFit.fitHeight,
            ),
          ),
          Expanded(
              child: Text(
            goods.shopName,
            maxLines: 1,
            style: TextStyle(color: HexColor.fromHex(style?.listStyle?.shopNameColor ?? '#666666'), fontSize: 11, fontWeight: FontWeight.w400),
          ))
        ],
      ),
    );
  }

  Widget _createCupone() {
    List<Widget> widgets = List();
    if (goods.coupon != null && goods.coupon != '') {
      var couponDe = style?.listStyle?.couponCommission?.coupon?.bgImg == 'img'
          ? BoxDecoration(
              image: DecorationImage(
                image: CachedNetworkImageProvider(style?.listStyle?.couponCommission?.coupon?.bgImg ?? ''),
              ),
              borderRadius: BorderRadius.circular(2.5),
            )
          : BoxDecoration(
              color: HexColor.fromHex(style?.listStyle?.couponCommission?.coupon?.bgColor),
              borderRadius: BorderRadius.circular(2.5),
            );

      widgets.add(Visibility(
        visible: style?.listStyle?.couponCommission?.coupon.isShow=="1"?true:false,
        child: Container(
          margin: EdgeInsets.only(right: 5),
          padding: EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3),
          // decoration: BoxDecoration(
          //   color: HexColor.fromHex(style.couponBgColor),
          //   borderRadius: BorderRadius.circular(2.5),
          // ),

          // child: Text(
          //   goods.coupon,
          //   textAlign: TextAlign.center,
          //   maxLines: 1,
          //   style: TextStyle(
          //     height: 1,
          //     fontSize: 11,
          //     // color: HexColor.fromHex(style.couponFontColor),
          //     color:  HexColor.fromHex(style?.couponCommission?.coupon?.couponFontColor),
          //   ),
          // ),
          decoration: couponDe,
          child: RichText(
            maxLines: 1,
            textAlign: TextAlign.center,
            text: TextSpan(
                text: '${goods?.coupon ?? '0'}',
                style: TextStyle(
                  height: 1,
                  fontSize: 11,
                  color: HexColor.fromHex(style?.listStyle?.couponCommission?.coupon?.fontColor),
                ),
                children: [
                  TextSpan(
                    text: '${style?.listStyle?.couponCommission?.coupon?.text ?? '元劵'}',
                    style: TextStyle(
                      height: 1,
                      fontSize: 11,
                      color: HexColor.fromHex(style?.listStyle?.couponCommission?.coupon?.fontColor),
                    ),
                  )
                ]),
          ),
        ),
      ));
    }

    if (goods.commission != null || goods.commission != '') {
      var commissionDe = style?.listStyle?.couponCommission?.commission?.bgType == 'img'
          ? BoxDecoration(
              image: DecorationImage(
                image: CachedNetworkImageProvider(style?.listStyle?.couponCommission?.commission?.bgImg ?? ''),
              ),
              borderRadius: BorderRadius.circular(2.5),
            )
          : BoxDecoration(
              color: HexColor.fromHex(style?.listStyle?.couponCommission?.commission?.bgColor),
              borderRadius: BorderRadius.circular(2.5),
            );

      widgets.add(
        Visibility(
          visible: style?.listStyle?.couponCommission?.commission.isShow=="1"?true:false,
          child: Container(
            margin: EdgeInsets.only(right: 5),
            padding: EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3),
            // decoration: BoxDecoration(
            //   color: HexColor.fromHex(style.commissionBgColor),
            //   borderRadius: BorderRadius.circular(2.5),
            // ),
            // child: Text(
            //   goods.commission,
            //   textAlign: TextAlign.center,
            //   maxLines: 1,
            //   style: TextStyle(
            //     height: 1,
            //     fontSize: 11,
            //     // color: HexColor.fromHex(style.commissionFontColor),
            //     color: HexColor.fromHex(style?.couponCommission?.commission?.commissionFontColor),
            //   ),
            // ),
            decoration: commissionDe,
            child: RichText(
              maxLines: 1,
              textAlign: TextAlign.center,
              text: TextSpan(
                  text: '${style?.listStyle?.couponCommission?.commission?.text ?? ''}',
                  style: TextStyle(
                    height: 1,
                    fontSize: 11,
                    color: HexColor.fromHex(style?.listStyle?.couponCommission?.commission?.fontColor),
                  ),
                  children: [
                    TextSpan(
                      text: '${goods?.commission ?? '0'}',
                      style: TextStyle(
                        height: 1,
                        fontSize: 11,
                        color: HexColor.fromHex(style?.listStyle?.couponCommission?.commission?.fontColor),
                      ),
                    )
                  ]),
            ),
          ),
        ),
      );
    }

    return Container(
      margin: EdgeInsets.only(top: 6),
      child: Row(
        children: widgets,
      ),
    );
  }

  Widget _createBottom() {
    return Container(
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[
          _createPrice(),
          _createOriginPrice(),
          Expanded(child: Container()),
          style?.listStyle?.hotRank?.isOpen == "0" ? _createSale() : Container(),
        ],
      ),
    );
  }

  Widget _createPrice() {
    return RichText(
      maxLines: 1,
      overflow: TextOverflow.ellipsis,
      text: TextSpan(children: [
        TextSpan(
          text: '￥',
          style: TextStyle(
            fontSize: 10,
            color: HexColor.fromHex(style?.listStyle?.currentPriceColor),
            fontWeight: FontWeight.bold,
            fontFamily: 'Din',
            package: 'zhiying_comm',
          ),
        ),
        TextSpan(
          text: goods.currentPrice,
          style: TextStyle(
            fontSize: 20,
            color: HexColor.fromHex(style?.listStyle?.currentPriceColor),
            fontWeight: FontWeight.bold,
            fontFamily: 'Din',
            package: 'zhiying_comm',
          ),
        )
      ]),
    );
  }

  Widget _createOriginPrice() {
    return Padding(
        padding: EdgeInsets.only(bottom: 2),
        child: Text(
          '￥${goods.marketPrice}',
          style: TextStyle(
            fontSize: 11,
            height: 1,
            color: HexColor.fromHex(style?.listStyle?.marketPriceColor),
            fontWeight: FontWeight.normal,
            fontFamily: 'Din',
            package: 'zhiying_comm',
            decoration: TextDecoration.lineThrough,
          ),
        ));
  }

  Widget _createSale() {
    return Text(
      '${goods.inorderCount}',
      style: TextStyle(fontSize: 11, color: HexColor.fromHex('#999999')),
    );
  }

  ///热点
  _buildHotItem() {
    var hotRank = style?.listStyle?.hotRank;
    return Row(
      children: <Widget>[
        Expanded(
            child: Stack(
          alignment: Alignment.centerLeft,
          children: <Widget>[
            Row(
              children: <Widget>[
                Expanded(
                    child: Container(
                  alignment: Alignment.centerLeft,
                  height: 20,
                  padding: EdgeInsets.only(
                    left: 20,
                  ),
                  margin: EdgeInsets.only(right: 20, left: 10),
                  color: HexColor.fromHex(hotRank.bgColor ?? ""),
                  child: Text(
                    (goods.inorderCount ?? ""),
                    style: TextStyle(color: Colors.white, fontSize: 11, fontFamily: 'Din', package: 'zhiying_comm'),
                  ),
                ))
              ],
            ),
            Container(
              width: 24,
              height: 24,
              child: CachedNetworkImage(
                imageUrl: hotRank?.hotSaleImg ?? "",
                width: 24,
                height: 24,
                placeholder: (context, _) => Container(color: Colors.yellow),
                fit: BoxFit.fill,
              ),
            ),
            Align(
                alignment: Alignment.centerRight,
                child: Container(
                  height: 24,
                  width: 63.5,
                  decoration: BoxDecoration(
                      image: DecorationImage(image: CachedNetworkImageProvider(hotRank.buyNowImg ?? ""), fit: BoxFit.fitWidth), borderRadius: BorderRadius.circular(20)),
                  margin: EdgeInsets.only(right: 0),
                ))
          ],
        ))
      ],
    );
  }
}
