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

import com.tzld.piaoquan.recommend.server.common.base.Constant;
import com.tzld.piaoquan.recommend.server.service.flowpool.FlowPoolService;
import com.tzld.piaoquan.recommend.server.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author dyp
 */
@Service
@Slf4j
public class FlowPoolWithLevelFilterService extends AbstractFilterService {
    @Autowired
    private FlowPoolService flowPoolService;

    public FilterResult filter(FilterParam param) {
        List<Long> videoIds = viewFilter(param);

        videoIds = filterDistributeCountAndDel(param, videoIds);

        return new FilterResult(videoIds);
    }

    private List<Long> filterDistributeCountAndDel(FilterParam param, List<Long> videoIds) {
        if (CollectionUtils.isEmpty(videoIds)
                || MapUtils.isEmpty(param.getFlowPoolMap())) {
            return videoIds;
        }
        Map<Long, String> flowPoolMap = videoIds.stream()
                .filter(v -> param.getFlowPoolMap().containsKey(v)
                        && StringUtils.isNotBlank(param.getFlowPoolMap().get(v)))
                .collect(Collectors.toMap(
                        v -> v,
                        v -> param.getFlowPoolMap().get(v)));

        Map<Long, Integer> distributeCountMap;
        //供给流量池实验
        Set<String> abExpCodes = param.getAbExpCodes();
        if (Objects.nonNull(abExpCodes) && abExpCodes.contains(Constant.SUPPLY_AB_CODE_ID)) {
//        if (Objects.equals(Constant.SUPPLY_AB_CODE, param.getAbCode())) {
            distributeCountMap = flowPoolService.getSupplyDistributeCountWithLevel(flowPoolMap);
        } else {
            distributeCountMap = flowPoolService.getDistributeCountWithLevel(flowPoolMap);
        }
//        Map<Long, Integer> distributeCountMap = flowPoolService.getDistributeCountWithLevel(flowPoolMap);

        List<Long> remainVideoIds = new ArrayList<>();
        for (Long videoId : videoIds) {
            if (distributeCountMap.get(videoId) != null
                    && distributeCountMap.get(videoId) > 0) {
                remainVideoIds.add(videoId);
            }
        }
        return remainVideoIds;
    }
}
