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

import com.tzld.piaoquan.recommend.server.service.score.ScorerConfigInfo;
import com.tzld.piaoquan.recommend.server.service.score4recall.AbstractScorer4Recall;
import com.tzld.piaoquan.recommend.server.service.score4recall.model4recall.Model4RecallKeyValue;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;

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


public class ContentBaseRecallScore extends AbstractScorer4Recall {

    public ContentBaseRecallScore(ScorerConfigInfo configInfo) {
        super(configInfo);
    }

    @Override
    public void loadModel() {
        doLoadModel(Model4RecallKeyValue.class);
    }

    @Override
    public List<Pair<Long, Double>> recall(Map<String, String> params) {
        Model4RecallKeyValue model = (Model4RecallKeyValue) this.getModel();
        if (model == null || MapUtils.isEmpty(model.kv)) {
            return Collections.emptyList();
        }
        String tags = params.get("tags");
        if (StringUtils.isBlank(tags)) {
            return Collections.emptyList();
        }
        List<String> tagList = Arrays.stream(tags.split(",")).collect(Collectors.toList());
        List<Pair<Long, Double>> result = new ArrayList<>();
        for (String tag : tagList) {
            List<Pair<Long, Double>> videoAndScores = model.kv.get(tag);
            if (CollectionUtils.isNotEmpty(videoAndScores)) {
                result.addAll(videoAndScores);
            }
        }
        // 结果去重
        Set<Long> videoIdSet = new HashSet<>();
        List<Pair<Long, Double>> distinctResult = new ArrayList<>();
        for (Pair<Long, Double> pair : result) {
            if (pair.getLeft() == null || pair.getRight() == null) {
                continue;
            }
            if (videoIdSet.add(pair.getLeft())) {
                distinctResult.add(pair);
            }
        }
        return distinctResult;
    }


}