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

import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
import lombok.extern.slf4j.Slf4j;
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.HashMap;
import java.util.Map;

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

    private static final String redisKey = "ad:engine:strategy:clib:v3:l6:cid_layer";
    private static final String keyFormat = "%s:%s:%s";

    private volatile static Map<String, Double> cidMap = Collections.emptyMap();

    // 服务启动时初始化数据
    @PostConstruct
    public void init() {
        Map<String, Double> map = updateCidMap();
        cidMap = Collections.unmodifiableMap(map);
    }

    // 每5分钟更新一次数据
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void scheduledUpdate() {
        Map<String, Double> map = updateCidMap();
        cidMap = Collections.unmodifiableMap(map);
    }

    public static Double getCopc(String model, String cid, String layer) {

        if (null != cidMap) {
            String key = String.format(keyFormat, model, cid, layer);
            if (cidMap.containsKey(key)) {
                if (cidMap.get(key) != null && cidMap.get(key) > 0) {
                    return cidMap.get(key);
                }
            }
            key = String.format(keyFormat, model, cid, "sum");
            if (cidMap.containsKey(key)) {
                if (cidMap.get(key) != null && cidMap.get(key) > 0) {
                    return cidMap.get(key);
                }
            }
            key = String.format(keyFormat, model,"sum",layer);
            if (cidMap.containsKey(key)) {
                if (cidMap.get(key) != null && cidMap.get(key) > 0) {
                    return cidMap.get(key);
                }
            }
        }
        return null;
    }

    private Map<String, Double> updateCidMap() {
        Map<String, Double> tmpCidSMap = new HashMap<>();
        try {
            String value = algRedisHelper.get(redisKey);
            if (null != value && !value.isEmpty()) {
                String[] cells = value.split(",");
                for (String cell : cells) {
                    String[] pair = cell.split("_");
                    if (2 == pair.length) {
                        tmpCidSMap.put(pair[0], Double.parseDouble(pair[1]));
                    }
                }
            }
            log.info("CreativeUserLayerDataHelperV2L6 update cid layer copc success size={}", tmpCidSMap.size());
        } catch (Exception e) {
            log.error("CreativeUserLayerDataHelperV2L6 update cid layer copc error", e);
        }
        return tmpCidSMap;
    }
}
