package com.sf._02_遍历集合;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class Test2 {


    public static void main(String[] args) {
        List<Goods> goods = initGoods();
        // 删除库存为0 商品
//        removeGoods(goods);
//        // 遍历商品信息
//        queryGoods(goods);
        // 添加商品库存
        incrGoodsStock(goods);

        queryGoods(goods);

        totalGoodsPrice(goods);
        // 根据商品名称查询商品信息
        System.out.println(queryGoodByName("手机1", goods));
    }

    /**
     * 根据商品名称查询商品信息
     */
    private static Goods queryGoodByName(String name, List<Goods> goods) {
        for (Goods good : goods) {
            if(name.equals(good.getName())){
                return good;
            }
        }
        return null;
    }

    /**
     * 统计库存总价
     * @param goods
     */
    private static void totalGoodsPrice(List<Goods> goods) {
        double totalPrice = 0;
        for (Goods good : goods) {
            totalPrice += good.getStock() * good.getPrice();
        }
        System.out.println("库存总价为:"+ totalPrice);
    }

    /**
     * 添加商品库存
     * @param goods
     */
    private static void incrGoodsStock(List<Goods> goods) {
        Iterator<Goods> iterator = goods.iterator();
        while (iterator.hasNext()){
            Goods good = iterator.next();
            // 判断价格是否大于1000
            if(good.getPrice() >1000){
                good.setStock(good.getStock() + 5);
            }
        }
    }

    /**
     * 删除库存为0的商品
     * @param goods
     */
    private static void removeGoods(List<Goods> goods) {
        Iterator<Goods> iterator = goods.iterator();
        while (iterator.hasNext()){
            Goods ele = iterator.next();
            // 判断库存是否为0
            if(ele.getStock() == 0){
                iterator.remove();
            }
        }
    }

    /**
     * 遍历集合信息
     * fori 循环
     * foreach 循环
     * 迭代器
     * @param goods
     */
    private static void queryGoods(List<Goods> goods) {
//        for (int i = 0; i < goods.size(); i++) {
//            System.out.println(goods.get(i));
//        }
//        System.out.println("----------------");
//        for (Goods good : goods) {
//            System.out.println(good);
//        }
//        System.out.println("-------------------");
        Iterator<Goods> iterator = goods.iterator();
        while (iterator.hasNext()){
            Goods next = iterator.next();
            System.out.println(next);
        }
    }


    /**
     * 初始化商品集合
     * @return
     */
    public static List<Goods> initGoods(){
        ArrayList<Goods> goods = new ArrayList<>();
        goods.add(new Goods(1,"手机",10,1000));
        goods.add(new Goods(2,"手机1",0,2000));
        goods.add(new Goods(3,"手机2",10,2000));
        goods.add(new Goods(4,"手机3",10,3100));
        goods.add(new Goods(5,"手机4",10,2000));
        return goods;
    }
}
