

import 'dart:convert';

import 'business.dart';
import 'cart_line_item.dart';
import 'extra_fee.dart';

class CartInfo {
  int? id;
  double? originPrice;
  double? discountPrice;
  double? totalPrice;
  Business? businessInfo;
  List<CartLineItem>? productList;
  List<ExtraFee>? extraFeeList;
  List<ExtraFee>? discountList;
  int? deliveryMethod;
  String? shippingMethod;
  double? amountPaid;
  String? extraData;

  CartInfo.fromJson(Map<String, dynamic> json)
    : id = json['id'],
      originPrice = json['origin_price'] != null ? double.parse(json['origin_price'].toString()) : 0.0,
      discountPrice = json['discount_price'] != null ? double.parse(json['discount_price'].toString()) : 0.0,
      totalPrice = json['total_price'] != null ? double.parse(json['total_price'].toString()) : 0.0,
      businessInfo = json['business_info'] != null ? Business.fromJson(json['business_info']) : null,
      productList = (json['product_list'] as List).map((i) => CartLineItem.fromJson(i)).toList(),
      extraFeeList = (json['extra_fee_list'] as List).map((i) => ExtraFee.fromJson(i)).toList(),
      discountList = (json['discount_list'] as List).map((e) => ExtraFee.fromJson(e)).toList(),
      deliveryMethod = json['delivery_method'],
      shippingMethod = json['shipping_method'],
      amountPaid = double.parse(json['amount_paid'].toString()),
      extraData = json['extra_data'];

  Map<String, dynamic> toJson() => {
    'id': id,
    'origin_price': originPrice,
    'discount_price': discountPrice,
    'total_price': totalPrice,
    'business_info': businessInfo,
    'product_list': productList,
    'extra_fee_list': extraFeeList,
    'discount_list': discountList,
    'delivery_method': deliveryMethod,
    'shipping_method': shippingMethod,
    'amount_paid': amountPaid,
    'extra_data': extraData,
  };

  addToCart(CartLineItem item) {
    if (productList == null) {
      productList = [item];
    } else {
      productList!.add(item);
    }

  }

  removeFromCart() {

  }

  @override
  String toString() {
    return json.encode(this);
  }

  CartInfo();

  double getTotalPrice() {
    double newTotal = 0.0;
    originPrice = 0.0;
    discountPrice = 0.0;
    totalPrice = 0.0;
    for (var i = 0; i < (productList?.length ?? 0); i++) {
      newTotal += productList![i].getTotalPrice();
    }
    originPrice = newTotal;
    totalPrice = newTotal;
    return totalPrice ?? 0.0;
  }

  int getProductListTotalQuantity() {
    int qty = 0;
    if (productList != null && productList!.length > 0) {
      for (var i = 0; i < productList!.length; i++) {
        qty += (productList![i].quantity ?? 0).round();
      }
    }
    return qty;
  }
}