package com.gingersoft.gsa.cloud.table.mvp.model.utils;

import com.gingersoft.gsa.cloud.order.commodity.OrderDetail;

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

/**
 * 作者：ELEGANT_BIN
 * 版本：1.6.0
 * 创建日期：2020-03-05
 * 修订历史：2020-03-05
 * 描述：
 */
public class OrderAssemblyUtil {

    /**
     * 組裝食品結構
     * @param orderDetails
     * @return
     */
    public static List<OrderDetail> assemblyOrder(List<OrderDetail> orderDetails) {
        List<OrderDetail> newOrderDetails = new ArrayList<>();
        for (int i = 0; i < orderDetails.size(); i++) {
            OrderDetail order = orderDetails.get(i);
            if (order.getItemType() == 1) {
                newOrderDetails.add(order);
                newOrderDetails.addAll(getOrdersItem2ByParentId(orderDetails, order.getId(),order.getProductId(), i));
            }
        }
        return newOrderDetails;//10 + 7
    }

    private static List<OrderDetail> getOrdersItem2ByParentId(List<OrderDetail> orderDetails, long id, long productId,int startIndex) {
        List<OrderDetail> orders = new ArrayList<>();
        for (int i = startIndex; i < orderDetails.size(); i++) {
            OrderDetail item = orderDetails.get(i);
            if (item.getItemType() == 3 && item.getParentId() == id) {
                item.setParentProductId(productId);
                //添加主食品細項
                orders.add(item);
            }
        }

        for (int i = startIndex; i < orderDetails.size(); i++) {
            OrderDetail item = orderDetails.get(i);
            if (item.getItemType() == 2 && item.getParentId() == id) {
                item.setParentProductId(productId);
                //添加子食品
                orders.add(item);
                orders.addAll(getOrdersItem3ByParentId(orderDetails,item.getId(),item.getProductId(),i));
            }
        }
        return orders;
    }

    private static List<OrderDetail> getOrdersItem3ByParentId(List<OrderDetail> orderDetails, long id, long productId, int startIndex) {
        List<OrderDetail> orders = new ArrayList<>();
        for (int i = startIndex; i < orderDetails.size(); i++) {
            OrderDetail item = orderDetails.get(i);
            if (item.getItemType() == 3 && item.getParentId() == id) {
                item.setParentProductId(productId);
                //添加子食品細項
                orders.add(item);
            }
        }
        return orders;
    }
}
