import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:fcs/domain/entities/discount_by_weight.dart';
import 'package:fcs/domain/entities/rate.dart';
import 'package:fcs/domain/entities/shipment.dart';
import 'package:fcs/domain/vo/shipment_status.dart';
import 'package:fcs/domain/vo/delivery_address.dart';

import 'cargo_type.dart';
import 'package.dart';

class Carton {
  String id;
  String shipmentID;
  String shipmentNumber;
  String senderFCSID;
  String senderName;
  String receiverFCSID;
  String receiverName;
  String receiverAddress;
  String receiverNumber;
  String boxNumber;
  String status;
  String cargoDesc;
  String desc;
  double width;
  double height;
  double length;
  int shipmentWeight;
  bool isChecked;
  bool isShipmentCarton;
  String cartonType;
  String fcsID;
  String userName;
  String userID;
  String fcsShipmentID;
  String fcsShipmentNumber;
  String mixCartonID;
  String mixCartonNumber;

  int rate;
  int weight;
  String packageType;
  String pickUpID;
  List<String> photos;
  String remark;
  DateTime arrivedDate;
  String cartonNumber;

  List<String> packageIDs;
  List<Package> packages;
  List<CargoType> cargoTypes;

  DeliveryAddress deliveryAddress;
  Shipment shipment;

  int get amount => rate != null && weight != null ? rate * weight : 0;

  String get packageNumber =>
      shipmentNumber + "-" + receiverNumber + " #" + boxNumber;
  double get price => rate.toDouble() * weight;

  double get actualWeight =>
      cargoTypes == null ? 0 : cargoTypes.fold(0, (p, e) => e.weight + p);

  double getShipmentWeight(double volumetricRatio) {
    if (length == null ||
        length <= 0 ||
        width == null ||
        width <= 0 ||
        height == null ||
        height <= 0 ||
        volumetricRatio == null ||
        volumetricRatio <= 0) return 0;

    return (length * width * height) / volumetricRatio;
  }

  /// getCargoTypeForCalWeight returns carton with shipment weight
  List<CargoType> getCargoTypeForCalWeight(double volumetricRatio) {
    // get shipment weight
    double volume = (length ?? 0) * (width ?? 0) * (height ?? 0);
    double sw = volume / volumetricRatio ?? 0;

    // get actual weight
    double aw = cargoTypes.fold(0.0, (p, c) => p + c.weight);
    if (aw == 0 || sw == 0) return [];

    cargoTypes.forEach((e) {
      double calWeight = aw > sw ? e.weight : e.weight / aw * sw;
      e.calWeight = calWeight;
    });
    return cargoTypes;
  }

  /// calAmount returns total amount
  double calAmount(Rate rate) {
    // get shipment weight
    double volume = (length ?? 0) * (width ?? 0) * (height ?? 0);
    double sw = volume / rate.volumetricRatio ?? 0;

    // get actual weight
    double aw = cargoTypes.fold(0.0, (p, c) => p + c.weight);
    if (aw == 0 || sw == 0) return 0;

    DiscountByWeight discountByWeight =
        rate.getDiscountByWeight(sw > aw ? sw : aw);

    double total = 0;
    cargoTypes.forEach((e) {
      double cargoWeight = aw > sw ? e.weight : e.weight / aw * sw;
      double r =
          e.rate - (discountByWeight != null ? discountByWeight.discount : 0);
      double amount = cargoWeight * r;
      total += amount;
    });
    return total;
  }

  List<ShipmentStatus> shipmentHistory;

  Carton(
      {this.id,
      this.shipmentID,
      this.shipmentNumber,
      this.senderFCSID,
      this.senderName,
      this.receiverFCSID,
      this.receiverName,
      this.receiverNumber,
      this.receiverAddress,
      this.boxNumber,
      this.desc,
      this.width,
      this.height,
      this.length,
      this.shipmentWeight,
      this.isChecked = false,
      this.cartonType,
      this.fcsID,
      this.userID,
      this.userName,
      this.rate = 0,
      this.weight = 0,
      this.packageType,
      this.pickUpID,
      this.remark,
      this.status,
      this.arrivedDate,
      this.cargoDesc,
      this.shipmentHistory,
      this.packages,
      this.cargoTypes,
      this.cartonNumber,
      this.fcsShipmentID,
      this.fcsShipmentNumber,
      this.packageIDs,
      this.mixCartonID,
      this.mixCartonNumber,
      this.isShipmentCarton = false,
      this.deliveryAddress});

  Map<String, dynamic> toMap() {
    List _cargoTypes = cargoTypes.map((c) => c.toMap()).toList();
    List _packages = packages?.map((c) => c.toJson())?.toList();
    return {
      "id": id,
      'fcs_shipment_id': fcsShipmentID,
      'user_id': userID,
      'cargo_types': _cargoTypes,
      'packages': _packages,
      'length': length,
      'width': width,
      'height': height,
      'delivery_address': deliveryAddress?.toMap(),
      'carton_type': cartonType,
      'mix_carton_id': mixCartonID,
    };
  }

  factory Carton.fromMap(Map<String, dynamic> map, String docID) {
    var _arrivedDate = (map['arrived_date'] as Timestamp);
    var da = map['delivery_address'];
    var _da = da != null ? DeliveryAddress.fromMap(da, da["id"]) : null;
    var cargoTypesMaps =
        List<Map<String, dynamic>>.from(map['cargo_types'] ?? []);
    var cargoTypes =
        cargoTypesMaps.map((e) => CargoType.fromMap(e, e["id"])).toList();
    return Carton(
        id: docID,
        arrivedDate: _arrivedDate != null ? _arrivedDate.toDate() : null,
        shipmentID: map['shipment_id'],
        shipmentNumber: map['shipment_number'],
        receiverNumber: map['receiver_number'],
        boxNumber: map['box_number'],
        length: map['length'],
        width: map['width'],
        height: map['height'],
        userName: map['user_name'],
        fcsID: map['fcs_id'],
        cartonType: map['carton_type'],
        cartonNumber: map['carton_number'],
        userID: map['user_id'],
        fcsShipmentID: map['fcs_shipment_id'],
        fcsShipmentNumber: map['fcs_shipment_number'],
        isShipmentCarton: map['is_shipment_carton'],
        mixCartonID: map['mix_carton_id'],
        mixCartonNumber: map['mix_carton_number'],
        status: map['status'],
        packageIDs: List<String>.from(map['package_ids'] ?? []),
        deliveryAddress: _da,
        cargoTypes: cargoTypes);
  }

  @override
  bool operator ==(Object other) => other is Carton && other.id == id;

  @override
  int get hashCode => id.hashCode;
}
