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.lang3.tuple.Pair;
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 LayerCustomerFlowControlDataHelper {
    @Autowired
    protected AlgorithmRedisHelper algRedisHelper;

    private static final String redisKey = "ad:engine:strategy:flowcontrol:layer_customer";
    private static final String keyFormat = "%s:%s:%s";

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

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

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

    public static Pair<Double, Double> getWeight(String layer, String profession, String customerId) {
        if (null != layerCustomerMap) {
            String key = String.format(keyFormat, layer, profession, customerId);
            if (layerCustomerMap.containsKey(key)) {
                return layerCustomerMap.get(key);
            }
        }
        return null;
    }

    private Map<String, Pair<Double, Double>> updateLayerCustomerMap() {
        Map<String, Pair<Double, Double>> tmpLayerCustomerMap = 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) {
                        String key = pair[0];
                        String[] values = pair[1].split(":");
                        if (2 == values.length) {
                            double cpmDiff = Double.parseDouble(values[0]);
                            double viewRate = Double.parseDouble(values[1]);
                            tmpLayerCustomerMap.put(key, Pair.of(cpmDiff, viewRate));
                        }
                    }
                }
            }
            log.info("update layer customer flow control success size={}", tmpLayerCustomerMap.size());
        } catch (Exception e) {
            log.error("update layer customer flow control error", e);
        }
        return tmpLayerCustomerMap;
    }
}
