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 com.tzld.piaoquan.recommend.server.util.FeatureUtils;
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.apache.commons.lang3.math.NumberUtils;
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 org.springframework.stereotype.Component;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Slf4j
@Component
public class YearReturnCate2RecallStrategy implements RecallStrategy {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private FilterService filterService;

    private final String CLASS_NAME = this.getClass().getSimpleName();

    public static final String PUSH_FROM = "recall_user_year_return_cate2";
    public static final String redisKeyPrefix = "return_1_cate2_recall";

    @Override
    public List<Video> recall(RecallParam param) {

        List<Video> videosResult = new ArrayList<>();
        try {

            if (MapUtils.isEmpty(param.getUserNetworkSeqVideoInfoMap())) {
                return videosResult;
            }

            List<Pair<Long, String>> userNetworkVideoCate2 = this.parseUserActionVideoAndCate2(param.getUserNetworkSeqFeature(), param.getUserNetworkSeqVideoInfoMap());
            if (CollectionUtils.isEmpty(userNetworkVideoCate2)) {
                return videosResult;
            }
            int limit = Math.min(userNetworkVideoCate2.size(), 3);
            List<String> lastTopNCate = userNetworkVideoCate2.subList(0, limit).stream()
                    .map(Pair::getValue)
                    .distinct()
                    .collect(Collectors.toList());

            List<String> freqTopNCate = userNetworkVideoCate2.stream()
                    .map(Pair::getValue)
                    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())).entrySet()
                    .stream()
                    .sorted(Map.Entry.<String, Long>comparingByValue().reversed())
                    .limit(limit)
                    .map(Map.Entry::getKey)
                    .collect(Collectors.toList());


            List<String> allCate2 = Stream.of(lastTopNCate, freqTopNCate)
                    .flatMap(Collection::stream)
                    .distinct()
                    .filter(StringUtils::isNotBlank)
                    .collect(Collectors.toList());

            List<String> keys = this.getRedisKey(allCate2);
            List<String> values = redisTemplate.opsForValue().multiGet(keys);
            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={}", CLASS_NAME, e);
        }

        return videosResult;
    }

    private List<Pair<Long, String>> parseUserActionVideoAndCate2(Map<String, String> userNetworkSeqFeature, Map<Long, Map<String, String>> userNetworkSeqVideoInfoMap) {
        List<Pair<Long, String>> result = new ArrayList<>();
        List<String> actVidSeq = FeatureUtils.extractVidsFromUserNetworkSeqFeature(userNetworkSeqFeature, "a_v_s");
        List<String> actTypeSeq = FeatureUtils.extractVidsFromUserNetworkSeqFeature(userNetworkSeqFeature, "a_t_s");
        if (actVidSeq.size() != actTypeSeq.size()) {
            return new ArrayList<>();
        }

        for (int i = 0; i < actVidSeq.size(); i++) {
            long videoIdL = NumberUtils.toLong(actVidSeq.get(i), -1);
            if (videoIdL <= 0){
                continue;
            }
            String type = actTypeSeq.get(i);
            if (!"click".equals(type)) {
                continue;
            }

            Map<String, String> videoBaseInfo = userNetworkSeqVideoInfoMap.getOrDefault(videoIdL, new HashMap<>());
            String mergeCate2 = videoBaseInfo.get("merge_second_level_cate");
            if (StringUtils.isBlank(mergeCate2)) {
                continue;
            }
            result.add(Pair.of(videoIdL, mergeCate2));
        }
        return result;
    }

    private List<String> getRedisKey(List<String> cate2List) {
        List<String> keys = new ArrayList<>();
        for (String cate2 : cate2List) {
            keys.add(String.format("%s:%s:%s", redisKeyPrefix, cate2, "ros"));
        }
        return keys;
    }

    private Pair<List<Long>, Map<Long, Double>> parseVidAndScore(Long headVid, List<String> values) {
        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());
            }
        }
        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, pushFrom(), scoresMap);
                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);
                    });
                }
            }
        }
    }

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