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

import com.aliyun.odps.data.Record;
import com.tzld.piaoquan.recommend.server.service.filter.strategy.GeneralSpiderStrategy;
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.stream.Collectors;

@Component
@Slf4j
public class GeneralSpiderUserCacheJob {

    @Autowired
    private ODPSManager odpsManager;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

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

    private List<String> queryGeneralSpiderUser() {
        //1000条左右，少于10000条 直接查
        String sql = "SELECT DISTINCT uid FROM loghubods.operators_channel_day WHERE type = '全面spider';";
        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());
    }


}
