package entity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

//¹ºÎï³µÀà
public class Cart {

	// ¹ºÂòÉÌÆ·µÄ¼¯ºÏ
	private HashMap<Items, Integer> goods;

	// ¹ºÎï³µµÄ×Ü½ð¶î
	private double totalPrice;

	// ¹¹Ôì·½·¨
	public Cart() {
		goods = new HashMap<Items, Integer>();
		totalPrice = 0.0;
	}

	public HashMap<Items, Integer> getGoods() {
		return goods;
	}

	public void setGoods(HashMap<Items, Integer> goods) {
		this.goods = goods;
	}

	public double getTotalPrice() {
		return totalPrice;
	}

	public void setTotalPrice(double totalPrice) {
		this.totalPrice = totalPrice;
	}

	// Ìí¼ÓÉÌÆ·½ø¹ºÎï³µµÄ·½·¨
	public boolean addGoodsInCart(Items item, int number) {
		if (goods.containsKey(item)) {
			goods.put(item, goods.get(item) + number);
		} else {
			goods.put(item, number);
		}
		calTotalPrice(); // ÖØÐÂ¼ÆËã¹ºÎï³µµÄ×Ü½ð¶î
		return true;
	}

	// É¾³ýÉÌÆ·µÄ·½·¨
	public boolean removeGoodsFromCart(Items item) {
		goods.remove(item);
		calTotalPrice(); // ÖØÐÂ¼ÆËã¹ºÎï³µµÄ×Ü½ð¶î
		return true;
	}

	// Í³¼Æ¹ºÎï³µµÄ×Ü½ð¶î
	public double calTotalPrice() {
		double sum = 0.0;
		Set<Items> keys = goods.keySet(); // »ñµÃ¼üµÄ¼¯ºÏ
		Iterator<Items> it = keys.iterator(); // »ñµÃµü´úÆ÷¶ÔÏó
		while (it.hasNext()) {
			Items i = it.next();
			sum += i.getPrice() * goods.get(i);
		}
		this.setTotalPrice(sum); // ÉèÖÃ¹ºÎï³µµÄ×Ü½ð¶î
		return this.getTotalPrice();
	}

	public static void main(String[] args) {

		// ÏÈ´´½¨Á½¸öÉÌÆ·¶ÔÏó
		Items i1 = new Items(1, "ÎÖÌØÀºÇòÐ¬", "ÎÂÖÝ", 200, 500, "001.jpg");
		Items i2 = new Items(2, "ÀîÄþÔË¶¯Ð¬", "¹ãÖÝ", 300, 500, "002.jpg");
		Items i3 = new Items(1, "ÎÖÌØÀºÇòÐ¬", "ÎÂÖÝ", 200, 500, "001.jpg");

		Cart c = new Cart();
		c.addGoodsInCart(i1, 1);
		c.addGoodsInCart(i2, 2);
		// ÔÙ´Î¹ºÂòÎÖÌØÀºÇòÐ¬£¬¹ºÂò3Ë«
		c.addGoodsInCart(i3, 3);

		// ±äÁ¿¹ºÎïÉÌÆ·µÄ¼¯ºÏ
		Set<Map.Entry<Items, Integer>> items = c.getGoods().entrySet();
		for (Map.Entry<Items, Integer> obj : items) {
			System.out.println(obj);
		}

		System.out.println("¹ºÎï³µµÄ×Ü½ð¶î£º" + c.getTotalPrice());

	}

}
