package com.tzld.piaoquan.recommend.server.service.filter.strategy;

import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.recommend.server.service.filter.FilterParam;
import com.tzld.piaoquan.recommend.server.service.filter.FilterStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author dyp
 */
@Component
public class SupplyExpStrategy implements FilterStrategy {
    @ApolloJsonValue("${supply.exp.list:[6]}")
    private Set<Integer> supplyExps;

    @Value("${supply.exp.id:666}")
    private int supplyExpId;

    @ApolloJsonValue("${supply.exp.video.list:[]}")
    private Set<Long> supplyExpVideos;
    @ApolloJsonValue("${not.supply.exp.video.list:[]}")
    private Set<Long> notSupplyExpVideos;

    @Override
    public List<Long> filter(FilterParam param) {

        if (param == null) {
            return Collections.emptyList();
        }
        if (StringUtils.isBlank(param.getMid())
                || CollectionUtils.isEmpty(param.getVideoIds())) {
            return param.getVideoIds();
        }

        if (!supplyExps.contains(param.getAppType())) {
            return Lists.newArrayList(param.getVideoIds());
        }
        if (MapUtils.isEmpty(param.getExpIdMap())) {
            return Lists.newArrayList(param.getVideoIds());
        }
        // 供给实验
        if (supplyExpId == NumberUtils.toInt(param.getExpIdMap().get("supply"), -1)) {
            // 对照组视频只在对照组出
            return param.getVideoIds().stream()
                    .filter(l -> !notSupplyExpVideos.contains(l))
                    .collect(Collectors.toList());
        } else {
            // 实验组视频只在实验组出
            return param.getVideoIds().stream()
                    .filter(l -> !supplyExpVideos.contains(l))
                    .collect(Collectors.toList());
        }
    }
}
