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

import com.aliyun.odps.data.Record;
import com.tzld.piaoquan.recommend.server.service.filter.strategy.VideoSourceTypeStrategy;
import com.tzld.piaoquan.recommend.server.service.odps.ODPSManager;
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.time.Duration;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

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

    @Autowired
    private ODPSManager odpsManager;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @XxlJob("updateNotUserUploadUserCache")
    public ReturnT<String> updateNotUserUploadUserCache(String params) {
        // 执行 ODPS Sql，获取数据
        List<String> uids = queryNotUserUploadUser();
        if (CollectionUtils.isEmpty(uids)) {
            XxlJobLogger.log("updateNotUserUploadUserCache, uids is empty");
            return ReturnT.SUCCESS;
        }
        redisTemplate.delete(VideoSourceTypeStrategy.NOT_USER_UPLOAD_USER_KEY);
        redisTemplate.opsForSet().add(VideoSourceTypeStrategy.NOT_USER_UPLOAD_USER_KEY,
                uids.toArray(new String[uids.size()]));
        redisTemplate.expire(VideoSourceTypeStrategy.NOT_USER_UPLOAD_USER_KEY, Duration.ofDays(2));
        
        XxlJobLogger.log("updateNotUserUploadUserCache, uids:{}", uids);
        return ReturnT.SUCCESS;
    }

    private List<String> queryNotUserUploadUser() {
        String sql = "SELECT DISTINCT c.uid\n" +
                "FROM loghubods.operators_channel_day c\n" +
                "WHERE c.type != 'userupload'\n" +
                "AND NOT EXISTS (\n" +
                "    SELECT 1\n" +
                "    FROM loghubods.operators_channel_day b\n" +
                "    WHERE b.uid = c.uid\n" +
                "    AND b.type = 'userupload'\n" +
                ")\n" +
                "ORDER BY c.uid DESC;";
        List<Record> records = odpsManager.query(sql);
        if (records == null || records.size() == 0) {
            return Collections.emptyList();
        }
        return records.stream().map(record -> record.getString(0)).collect(Collectors.toList());
    }


}
