package com.tzld.piaoquan.ad.engine.commons.helper;

import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@Slf4j
@Component
public class AnomalousCidDataHelper {
    @Autowired
    protected AlgorithmRedisHelper algRedisHelper;

    private static final String redisKey = "ad:engine:strategy:control:cid:anomalous_ctcvr";

    private volatile static Set<Long> cidSet = Collections.emptySet();

    // 服务启动时初始化数据
    @PostConstruct
    public void init() {
        Set<Long> cidSet1 = updateCidSet();
        cidSet = Collections.unmodifiableSet(cidSet1);
    }

    // 每5分钟更新一次数据
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void scheduledUpdate() {
        Set<Long> cidSet1 = updateCidSet();
        cidSet = Collections.unmodifiableSet(cidSet1);
    }

    public static boolean contains(long cid) {
        if (CollectionUtils.isNotEmpty(cidSet)) {
            return cidSet.contains(cid);
        }
        return false;
    }

    private Set<Long> updateCidSet() {
        try {
            Set<Long> tmpCidSet = new HashSet<>();
            String value = algRedisHelper.get(redisKey);
            if (null != value && !value.isEmpty()) {
                String[] cells = value.split(",");
                for (String cell : cells) {
                    tmpCidSet.add(Long.valueOf(cell));
                }
            }
            log.info("anomalous cid set init success size={}", tmpCidSet.size());
            return tmpCidSet;
        } catch (Exception e) {
            log.error("update anomalous cid error", e);
        }
        return Collections.emptySet();
    }
}
