package com.malk.utils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class UtilMc {

    /**
     * distinctByKey [SQL去重只能返回列, 不支持返回实体对象]
     * -
     * 成员列表去除重复userId
     * 简写: poList.stream().filter(UtilMc.distinctByKey(XdDdApproveRecordPo::getOpenUserId)).collect(Collectors.toList())
     * 展开: List<XdDdApproveRecordPo> poList = new ArrayList<>();
     * poPage.getContent().stream().filter(UtilMc.distinctByKey(p -> p.getOpenUserId()))
     * .forEach(poList::add);
     * 打印: poList.forEach(System.out::println);
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> Objects.isNull(seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE));
    }

    /**
     * 集合内Map唯一值, 返回集合 [返回去重后数据本身]
     */
    public static List<Map> distinctByKey(List<Map> dataList, String key) {
        return dataList.stream().filter(distinctByKey(item -> item.get(key))).collect(Collectors.toList());
    }

    /**
     * 工具方法 [forEach 索引]
     */
    public static Consumer<Object> consumerWithIndex(BiConsumer<Object, Integer> consumer) {
        class Obj {
            int i;
        }
        Obj obj = new Obj();
        return t -> {
            int index = obj.i++;
            consumer.accept(t, index);
        };
    }
}
