package com.xydl.cac.util;

import java.util.*;

public class DataUtil {

    // 从数据里每天抽取num条
    public static List<Map<String, Object>> pickNumPerDay(List<Map<String, Object>> source, Integer numPerDay) throws Exception {

        // 按天划分
        LinkedHashMap<String, List<Map<String, Object>>> map = new LinkedHashMap<>();
        for (Map<String, Object> item : source) {
            String time = (String) item.get("acquisitionTime");
            Date date = DateUtil.parse(time);
            String day = DateUtil.format(date, "yyyy-MM-dd");

            List<Map<String, Object>> list = map.get(day);
            if (list == null) {
                list = new ArrayList<>();
                list.add(item);
                map.put(day, list);
            } else {
                list.add(item);
            }
        }

        // 过滤多余
        for (List<Map<String, Object>> list : map.values()) {
            if (list.size() > numPerDay) {
                reduceOneDaySize(list, numPerDay);
            }
        }

        // 合并返回
        List<Map<String, Object>> result = new ArrayList<>();
        for (List<Map<String, Object>> list : map.values()) {
            result.addAll(list);
        }
        return result;
    }

    private static void reduceOneDaySize(List<Map<String, Object>> list, Integer numPerDay) {
        int m = list.size() / numPerDay;
        int x = list.size() - numPerDay;
        if (m == 1) {
            if (x == 1) {
                list.remove(0);
            } else {
                int idx = 0;
                while (list.size() > numPerDay) {
                    if (idx >= list.size()) {
                        idx = 0;
                    }
                    list.remove(idx);
                    idx++;
                }
            }
        } else {
            List<Map<String, Object>> newlist = new ArrayList<>();
            for (int i = 0; i < numPerDay; i++) {
                int idx = m * (i + 1) - 1;
                Map<String, Object> item = list.get(idx);
                newlist.add(item);
            }
            list.clear();
            list.addAll(newlist);
        }
    }
}
