package com.crm.rely.backend.util;

import com.crm.rely.backend.core.constant.Constants;
import com.crm.rely.backend.core.pojo.view.DailyHistoryTradeView;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;

/**
 * Created by max on 2020/6/19.
 */
public class ListSplitUtil {

    public static <T> List<List<T>> split(List<T> list, Integer maxSize) {
        Integer size = list.size() % maxSize == 0 ? (list.size() / maxSize) : (list.size() / maxSize) + 1;
        if (list.size() < maxSize) {
            maxSize = list.size();
        }
        List<List<T>> result = Lists.newArrayList();

        for (int i = 0; i < size; i++) {

            Integer fromIndex = i * maxSize;
            Integer toIndex = i * maxSize + maxSize > list.size() ? list.size() : i * maxSize + maxSize;

            result.add(list.subList(fromIndex, toIndex));

        }

        return result;

    }

    public static <T> List<List<T>> split(List<T> list) {
        return split(list, Constants.MAX_INSERT_SIZE);
    }

    public static Map<String, List<DailyHistoryTradeView>> splitByDate(List<DailyHistoryTradeView> views) {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");

        Map<String, List<DailyHistoryTradeView>> map = Maps.newHashMap();
        for (DailyHistoryTradeView view : views) {
            String ym = sdf.format(view.getCloseTime());
            List<DailyHistoryTradeView> tradeHistoryViews;
            if ((tradeHistoryViews = map.get(ym)) == null) {
                tradeHistoryViews = Lists.newArrayList();
                map.put(ym, tradeHistoryViews);
            }
            tradeHistoryViews.add(view);
        }


        return map;
    }

    public static <T> Map<String, List<T>> splitByDateCommon(List<T> views) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
        Map<String, List<T>> map = Maps.newHashMap();

        for (T view : views) {
            String ym = sdf.format(view.getClass().getMethod("getCloseTime").invoke(view));
            List<T> list;
            if ((list = map.get(ym)) == null) {
                list = Lists.newArrayList();
                map.put(ym, list);
            }
            list.add(view);
        }

        return map;
    }

}
