package com.tzld.piaoquan.recommend.server.xxl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.data.Record;
import com.tzld.piaoquan.recommend.server.common.base.Constant;
import com.tzld.piaoquan.recommend.server.service.odps.ODPSManager;
import com.tzld.piaoquan.recommend.server.service.recall.strategy.FlowPoolLastDayTopRecallStrategy;
import com.tzld.piaoquan.recommend.server.service.recall.strategy.TopGoodPerformanceVideoRecallStrategy;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sunxy
 */
@Component
@Slf4j
public class SyncFlowPoolRecentTopVideoJob {

    @Autowired
    private ODPSManager odpsManager;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @XxlJob("syncFlowPoolRecentTopVideo")
    public ReturnT<String> syncFlowPoolRecentTopVideo(String params) {
        // 执行 ODPS Sql，获取数据
        List<Long> videoIds = queryTopVideoIdsByLast6Hour(200);
        if (CollectionUtils.isEmpty(videoIds)) {
            XxlJobLogger.log("syncFlowPoolRecentTopVideo, videoIds is empty");
            return ReturnT.SUCCESS;
        }
        XxlJobLogger.log("syncFlowPoolRecentTopVideo, videoIds:{}", videoIds);
        // 将数据写入 Redis
        redisTemplate.opsForValue().set(Constant.VIDEO_PERFORMANCE_DATA_REDIS_KEY + FlowPoolLastDayTopRecallStrategy.PUSH_FORM,
                JSONObject.toJSONString(videoIds), 2, TimeUnit.HOURS);
        return ReturnT.SUCCESS;
    }

    private List<Long> queryTopVideoIdsByLast6Hour(Integer topNum) {
        String sql = "SELECT videoid FROM loghubods.flow_pool_video_info_per_hour " +
                "WHERE dt = '" + odpsManager.getNowHour() + "' " +
                "ORDER BY 12hour_return_cnt DESC LIMIT " + topNum + ";";
        List<Record> records = odpsManager.query(sql);
        if (records == null || records.size() == 0) {
            return null;
        }
        return records.stream().map(record -> record.getBigint(0)).collect(Collectors.toList());
    }

    @XxlJob("syncGoodPerformanceVideo")
    public ReturnT<String> syncGoodPerformanceVideo(String params) {
        // 执行 ODPS Sql，获取数据
        List<Long> videoIds = queryGoodPerformanceVideo(100);
        if (CollectionUtils.isEmpty(videoIds)) {
            XxlJobLogger.log("syncGoodPerformanceVideo, videoIds is empty");
            return ReturnT.SUCCESS;
        }
        XxlJobLogger.log("syncGoodPerformanceVideo, videoIds:{}", videoIds);
        // 将数据写入 Redis
        redisTemplate.opsForValue().set(Constant.VIDEO_PERFORMANCE_DATA_REDIS_KEY + TopGoodPerformanceVideoRecallStrategy.PUSH_FORM,
                JSONObject.toJSONString(videoIds), 2, TimeUnit.HOURS);
        return ReturnT.SUCCESS;
    }

    private List<Long> queryGoodPerformanceVideo(int limit) {
        String sql = "SELECT videoid FROM loghubods.long_period_good_performance_video " +
                "WHERE dt = '" + odpsManager.getNowHour() + "' " +
                "ORDER BY rov DESC LIMIT " + limit + ";";
        List<Record> records = odpsManager.query(sql);
        if (records == null || records.size() == 0) {
            return null;
        }
        return records.stream().map(record -> record.getBigint(0)).collect(Collectors.toList());
    }


}
