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 org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

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

    public static final String PUSH_FORM = "app_fallback_recall_strategy";

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

    @Override
    public List<Video> recall(RecallParam param) {
        // 1 获取省份key 放入参数map中
        String regionCode = param.getRegionCode();
        String redisKey;
        if (StringUtils.isBlank(regionCode) || StringUtils.equals(regionCode, "110100")
                || StringUtils.equals(regionCode, "430100")) {
            // 北京和长沙
            redisKey = "app_fallback_recall_strategy_safe_videos";
        } else {
            // 其他
            redisKey = "app_fallback_recall_unsafe_strategy_videos";
        }
        String videoIds = redisTemplate.opsForValue().get(redisKey);
        if (StringUtils.isBlank(videoIds)) {
            return Collections.emptyList();
        }
        List<Long> videoIdList = Arrays.asList(videoIds.split(",")).stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());
        FilterParam filterParam = FilterParamFactory.create(param, videoIdList);
        FilterResult filterResult = filterService.filter(filterParam);
        List<Video> videosResult = new ArrayList<>();
        if (filterResult != null && CollectionUtils.isNotEmpty(filterResult.getVideoIds())) {
            filterResult.getVideoIds().stream().limit(500)
                    .forEach(vid -> {
                        Video video = new Video();
                        video.setVideoId(vid);
                        video.setPushFrom(pushFrom());
                        videosResult.add(video);
                    });
        }
        return videosResult;
    }

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


}
