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

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.tzld.piaoquan.recommend.server.model.Video;
import com.tzld.piaoquan.recommend.server.service.filter.FilterParam;
import com.tzld.piaoquan.recommend.server.service.filter.FilterResult;
import com.tzld.piaoquan.recommend.server.service.filter.RegionFilterService;
import com.tzld.piaoquan.recommend.server.service.recall.FilterParamFactory;
import com.tzld.piaoquan.recommend.server.service.recall.RecallParam;
import com.tzld.piaoquan.recommend.server.service.recall.RecallStrategy;
import com.tzld.piaoquan.recommend.server.service.score.ScorerUtils;
import com.tzld.piaoquan.recommend.server.service.score4recall.ScorerPipeline4Recall;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author zhangbo
 */
@Component
public class ContentBaseRecallStrategy implements RecallStrategy {

    public static final String PUSH_FORM = "content_base_recall_strategy";

    private static final String VIDEO_2_TAG_REDIS_KEY = "content:base:video:tags:";

    @Value("${recommend.content.base.recall.strategy.limit:50}")
    private Integer limit;
    @Resource
    private RegionFilterService filterService;
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Video> recall(RecallParam param) {
        Long videoId = param.getVideoId();
        Map<String, String> param4Model = new HashMap<>(1);
        String redisKey = VIDEO_2_TAG_REDIS_KEY + videoId;
        String tags = redisTemplate.opsForValue().get(redisKey);
        try {
            String tagStr = JSONObject.parseObject(tags).getString("tags");
            param4Model.put("tags", tagStr);
        } catch (Exception e) {
            return Collections.emptyList();
        }
        // 2 通过model拿到召回list
        ScorerPipeline4Recall pipeline = ScorerUtils.getScorerPipeline4Recall("content_base_recall.conf");
        List<List<Pair<Long, Double>>> results = pipeline.recall(param4Model);
        List<Pair<Long, Double>> result = results.get(0);
        for (int i = 1; i < results.size(); ++i) {
            result.addAll(results.get(i));
        }
        Map<Long, Double> videoMap = new LinkedHashMap<>();
        for (Pair<Long, Double> v : result) {
            videoMap.put(v.getLeft(), v.getRight());
        }
        FilterParam filterParam = FilterParamFactory.create(param, Lists.newArrayList(videoMap.keySet()));
        FilterResult filterResult = filterService.filter(filterParam);
        List<Video> videosResult = new ArrayList<>();
        if (filterResult != null && CollectionUtils.isNotEmpty(filterResult.getVideoIds())) {
            filterResult.getVideoIds().stream()
                    // 按照 rovScore 倒序排序
                    .sorted(Comparator.comparing(vid -> videoMap.getOrDefault(vid, 0.0)).reversed())
                    .limit(limit).forEach(vid -> {
                        Video video = new Video();
                        video.setVideoId(vid);
                        video.setAbCode(param.getAbCode());
                        video.setRovScore(videoMap.get(vid));
                        video.setPushFrom(pushFrom());
                        videosResult.add(video);
                    });
        }
        return videosResult;
    }

    @Override
    public String pushFrom() {
        return PUSH_FORM;
    }


}
