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

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.FilterService;
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 lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;

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

@Slf4j
public abstract class AbstractRedisRecallStrategy implements RecallStrategy {
    @Autowired
    private FilterService filterService;
    @Autowired
    @Qualifier("redisTemplate")
    public RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Video> recall(RecallParam param) {
        List<Video> videosResult = new ArrayList<>();
        try {
            List<String> keys = getRedisKeys(param);
            if (null != keys && !keys.isEmpty()) {
                List<String> values = redisTemplate.opsForValue().multiGet(keys);
                if (null != values && !values.isEmpty()) {
                    Pair<List<Long>, Map<Long, Double>> pair = parseVidAndScore(param.getVideoId(), values);
                    fillVideoResult(param, pair, videosResult);
                }
            }
        } catch (Exception e) {
            log.error("recall is wrong in {}, error={}", pushFrom(), e);
        }
        return videosResult;
    }

    private Pair<List<Long>, Map<Long, Double>> parseVidAndScore(Long headVid, List<String> values) {
        int topN = getTopN();
        Map<Long, Double> scoresMap = new HashMap<>();
        if (null != values && !values.isEmpty()) {
            for (String value : values) {
                if (null != value && !value.isEmpty()) {
                    String[] cells = value.split("\t");
                    if (2 == cells.length) {
                        List<Long> ids = Arrays.stream(cells[0].split(",")).map(Long::valueOf).collect(Collectors.toList());
                        List<Double> scores = Arrays.stream(cells[1].split(",")).map(Double::valueOf).collect(Collectors.toList());
                        if (!ids.isEmpty() && ids.size() == scores.size()) {
                            for (int i = 0; i < ids.size(); ++i) {
                                long vid = ids.get(i);
                                double score = scores.get(i);
                                if (vid == headVid) {
                                    continue;
                                }
                                double oldScore = scoresMap.getOrDefault(vid, 0.0);
                                scoresMap.put(vid, Math.max(oldScore, score));
                            }
                        }
                    }
                }
            }
        }
        List<Long> idsList = new ArrayList<>();
        if (!scoresMap.isEmpty()) {
            List<Pair<Long, Double>> list = new ArrayList<>();
            for (Map.Entry<Long, Double> entry : scoresMap.entrySet()) {
                list.add(MutablePair.of(entry.getKey(), entry.getValue()));
            }
            list.sort(Comparator.comparingDouble(o -> -o.getRight()));
            for (Pair<Long, Double> pair : list) {
                idsList.add(pair.getLeft());
                if (idsList.size() >= topN) {
                    break;
                }
            }
        }
        return new MutablePair<>(idsList, scoresMap);
    }

    private void fillVideoResult(RecallParam param, Pair<List<Long>, Map<Long, Double>> pair, List<Video> videosResult) {
        if (null != pair) {
            List<Long> ids = pair.getLeft();
            Map<Long, Double> scoresMap = pair.getRight();
            if (null != ids && null != scoresMap && !ids.isEmpty()) {
                FilterParam filterParam = FilterParamFactory.create(param, ids);
                FilterResult filterResult = filterService.filter(filterParam);
                if (null != filterResult && CollectionUtils.isNotEmpty(filterResult.getVideoIds())) {
                    filterResult.getVideoIds().forEach(vid -> {
                        Video video = new Video();
                        video.setVideoId(vid);
                        video.setRovScore(scoresMap.getOrDefault(vid, 0D));
                        video.setPushFrom(pushFrom());
                        videosResult.add(video);
                    });
                }
            }
        }
    }

    abstract List<String> getRedisKeys(RecallParam param);

    abstract int getTopN();
}
