package com.tzld.piaoquan.ad.engine.service.score.deprecated;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.tzld.piaoquan.ad.engine.commons.redis.AlgorithmRedisHelper;
import com.tzld.piaoquan.ad.engine.commons.score.ScoreParam;
import com.tzld.piaoquan.ad.engine.commons.util.ComparatorUtil;
import com.tzld.piaoquan.ad.engine.commons.dto.AdPlatformCreativeDTO;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.AdRankItem;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.math3.distribution.BetaDistribution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class VideoAdThompsonScorerV2 {
    Logger log = LoggerFactory.getLogger(VideoAdThompsonScorerV2.class);

    @Autowired
    private AlgorithmRedisHelper redisHelper;
    // redis:cid_action:{$cid}
    private String redisCreativeStatisticsPrefix = "redis:cid_action:";
    // redis:vid_cid_action:{$vid}_{$cid}
    private String redisVideoCreativeStatisticsPrefix = "redis:vid_cid_action:";

    private final String redisCidActionKeyV1 = "redis:cid_action_v1:";
    private final String redisCidVidActionKeyV1 = "redis:vid_cid_action_v1:";

    private Map<String, Double> exp663Param = new HashMap<>();
    private Map<String, Double> exp664Param = new HashMap<>();
    private Map<String, Double> exp665Param = new HashMap<>();
    private Map<String, Double> exp666Param = new HashMap<>();
    private Map<String, Double> exp669Param = new HashMap<>();
    private Map<String, Object> exp670Param = new HashMap<>();
    private Map<String, Object> exp671Param = new HashMap<>();
    private Map<String, Object> exp672Param = new HashMap<>();

    Random random = new Random();
    Gson gson = new Gson();

    public List<AdRankItem> thompsonScorerByExp663(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        List<AdRankItem> result = new LinkedList<>();
        Map<Long, CreativeStatistic> creativeStatisticsMap = this.batchFindCreativeRedisCache(redisCreativeStatisticsPrefix, adIdList);

        double alpha = exp663Param.getOrDefault("alpha", 0d);
        double beta = exp663Param.getOrDefault("beta", 0d);

        for (AdPlatformCreativeDTO dto : adIdList) {

            // 日志上报扩展参数
            Map<String, Object> ext = new HashMap<>();
            double score = 0.0;
            double cpa = 0.0;
            try {
                CreativeStatistic cidStatistics = creativeStatisticsMap.getOrDefault(dto.getCreativeId(), new CreativeStatistic());
                cpa = cidStatistics.parseCpaToDouble();

                double order;
                double exp;
                order = cidStatistics.parseOrderToDouble();
                exp = cidStatistics.parseExpToDouble();

                double s1 = 0.0;
                double a = order + alpha;
                double b = exp + beta;
                if (a != 0 && b != 0) {
                    s1 = a / b;
                }

                score = s1 * cpa;

                ext.put("alpha", alpha);
                ext.put("beta", beta);
                ext.put("order", order);
                ext.put("exp", exp);
                ext.put("s1", s1);
                ext.put("pairOrSingle", "single");
                ext.put("cidStatistic", JSON.toJSONString(cidStatistics));
                ext.put("cpa", cpa);
            } catch (Exception e) {
                log.error("svc=663exp, error: ", e);
            }
            AdRankItem item = new AdRankItem();
            item.setCpa(cpa);
            item.setAdId(dto.getCreativeId());
            item.setScore(score);
            item.setExt(ext);
            item.setVideoId(param.getVideoId());
            item.setScore_type(663);
            item.setWeight(dto.getWeight());
            item.setCreativeCode(dto.getCreativeCode());
            result.add(item);
        }

        result.sort(ComparatorUtil.equalsRandomComparator());
        return result;
    }

    public List<AdRankItem> thompsonScorerByExp664(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        List<AdRankItem> result = new LinkedList<>();
        String jsonStr;
        CreativeStatistic statistic = null;
        List<String> redisKey = new LinkedList<>();
        adIdList.forEach(creativeDTO -> {
            redisKey.add(redisVideoCreativeStatisticsPrefix + param.getVideoId() + "_" + creativeDTO.getCreativeId());
        });
        List<String> values = redisHelper.getValues(redisKey);
        int i = 0;
        double score = 0d;
        for (AdPlatformCreativeDTO dto : adIdList) {
            AdRankItem item = new AdRankItem();
            item.setVideoId(param.getVideoId());
            item.setCpa(dto.getCpa());
            item.setAdId(dto.getCreativeId());
            try {

                jsonStr = values.get(i);
                if (jsonStr == null) {
                    score = exp664Param.getOrDefault("randomMin", 0.000001)
                            + (random.nextDouble() *
                            (exp664Param.getOrDefault("randomMax", 0.00001) - exp664Param.getOrDefault("randomMin", 0.000001)));
                } else {
                    statistic = gson.fromJson(jsonStr, CreativeStatistic.class);
                    score = (exp664Param.getOrDefault("alpha", 1d) + Long.parseLong(statistic.getOrder()))
                            / (exp664Param.getOrDefault("beta", 10000d) + Long.parseLong(statistic.getExp()));
                }
                double s1 = score;
                score = score * dto.getCpa() * dto.getBid1() * dto.getBid2();
                item.setScore(score);

                Map<String, Object> ext = this.extMap(statistic, "664", dto.getCpa(), null,
                        exp664Param.getOrDefault("alpha", 1d), exp664Param.getOrDefault("beta", 10000d), null);
                ext.put("s1", s1);
                item.setCreativeCode(dto.getCreativeCode());
                item.setWeight(dto.getWeight());
                item.setExt(ext);
                item.setScore_type(664);
            } catch (Exception e) {
                log.error("svc=thompsonScorerByExp664 {}", gson.toJson(e.getStackTrace()));
            }
            result.add(item);
            i++;
        }

        Collections.sort(result);
        return result;
    }

    public List<AdRankItem> thompsonScorerByExp665(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        List<AdRankItem> result = new LinkedList<>();
        String jsonStr;
        CreativeStatistic statistic = null;
        List<String> redisKey = new LinkedList<>();
        adIdList.forEach(creativeDTO -> {
            redisKey.add(redisCreativeStatisticsPrefix + creativeDTO.getCreativeId());
        });
        // view/sum（view）
        List<String> values = redisHelper.getValues(redisKey);
        int i = 0;
        double score = 0d;
        for (AdPlatformCreativeDTO dto : adIdList) {
            AdRankItem item = new AdRankItem();
            item.setVideoId(param.getVideoId());
            item.setCpa(dto.getCpa());
            item.setAdId(dto.getCreativeId());
            try {
                jsonStr = values.get(i);
                if (jsonStr == null) {
                    score = betaSampler(exp665Param.getOrDefault("alpha", 1d), exp665Param.getOrDefault("beta", 100000d));
                } else {
                    statistic = gson.fromJson(jsonStr, CreativeStatistic.class);
                    score = betaSampler(exp665Param.getOrDefault("alpha", 1d) + Long.parseLong(statistic.getOrder()),
                            (exp665Param.getOrDefault("beta", 100000d) + Long.parseLong(statistic.getExp()))) / (1 + exp665Param.getOrDefault("beta_k", 9d));
                }
                double s1 = score;
                score = score * dto.getCpa() * dto.getBid1() * dto.getBid2();
                item.setScore(score);
                item.setScore_type(665);
                item.setWeight(dto.getWeight());

                Map<String, Object> ext = this.extMap(statistic, "665", dto.getCpa(), null,
                        exp665Param.getOrDefault("alpha", 1d), exp665Param.getOrDefault("beta", 10000d), null);
                ext.put("s1", s1);
                item.setCreativeCode(dto.getCreativeCode());
                item.setExt(ext);
            } catch (Exception e) {
                log.error("svc=thompsonScorerByExp665 {}", gson.toJson(e.getStackTrace()));
            }
            result.add(item);
            i++;
        }

        Collections.sort(result);
        return result;
    }

    public List<AdRankItem> thompsonScorerByExp666(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        List<AdRankItem> result = new LinkedList<>();
        Map<Long, CreativeStatistic> creativeStatisticsMap = this.batchFindCreativeRedisCache(redisCreativeStatisticsPrefix, adIdList);
        Map<Long, CreativeStatistic> videoCreativeStatisticsMap = this.batchFindCreativeRedisCache(redisVideoCreativeStatisticsPrefix + param.getVideoId() + "_", adIdList);

        double alpha = exp666Param.getOrDefault("alpha", 0d);
        double beta = exp666Param.getOrDefault("beta", 0d);
        double betaK = exp666Param.getOrDefault("beta_k", 0d) + 1;
        double viewThreshold = exp666Param.getOrDefault("viewThreshold", 7000d);

        for (AdPlatformCreativeDTO dto : adIdList) {
            Long cid = dto.getCreativeId();
            String pairOrSingle;
            double order;
            double exp;
            CreativeStatistic vidCidStatistics = videoCreativeStatisticsMap.getOrDefault(cid, new CreativeStatistic());
            CreativeStatistic cidStatistics = creativeStatisticsMap.getOrDefault(cid, new CreativeStatistic());
            // 日志上报扩展参数
            Map<String, Object> ext = new HashMap<>();
            double score = 0.0;
            double cpa = cidStatistics.parseCpaToDouble();
            try {


                if (vidCidStatistics.parseExpToDouble() >= viewThreshold) {
                    pairOrSingle = "pair";
                    order = vidCidStatistics.parseOrderToDouble();
                    exp = vidCidStatistics.parseExpToDouble();
                } else {
                    pairOrSingle = "single";
                    order = cidStatistics.parseOrderToDouble();
                    exp = cidStatistics.parseExpToDouble();
                }

                double s1 = this.betaSampler((alpha + order), ((beta + exp) / betaK));
                score = s1 * cpa;


                ext.put("alpha", alpha);
                ext.put("beta", beta);
                ext.put("beta_k", betaK);
                ext.put("order", order);
                ext.put("exp", exp);
                ext.put("s1", s1);
                ext.put("viewThreshold", viewThreshold);
                ext.put("pairOrSingle", pairOrSingle);
                ext.put("cidStatistic", JSON.toJSONString(cidStatistics));
                ext.put("vidCidStatistic", JSON.toJSONString(vidCidStatistics));
                ext.put("cpa", cpa);
            } catch (Exception e) {
                log.error("svc=666exp, error: ", e);
            }
            AdRankItem item = new AdRankItem();
            item.setCpa(cpa);
            item.setAdId(dto.getCreativeId());
            item.setScore(score);
            item.setExt(ext);
            item.setVideoId(param.getVideoId());
            item.setScore_type(666);
            item.setWeight(dto.getWeight());
            item.setCreativeCode(dto.getCreativeCode());
            result.add(item);
        }

        result.sort(ComparatorUtil.equalsRandomComparator());
        return result;
    }

    public List<AdRankItem> thompsonScorerByExp669(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        Map<Long, CreativeStatistic> creativeStatisticsMap = this.batchFindCreativeRedisCache(redisCidActionKeyV1, adIdList);
        Map<Long, CreativeStatistic> videoCreativeStatisticsMap = this.batchFindCreativeRedisCache(redisCidVidActionKeyV1 + param.getVideoId() + "_", adIdList);
        Double creativeExpSum = this.sumCreativeStatisticExp(creativeStatisticsMap.values());
        Double videoCreativeExpSum = this.sumCreativeStatisticExp(videoCreativeStatisticsMap.values());

        List<AdRankItem> result = new ArrayList<>(adIdList.size());
        this.calcScore(result, adIdList, 1d, creativeExpSum, videoCreativeExpSum, creativeStatisticsMap, videoCreativeStatisticsMap, exp669Param);
        result.sort(ComparatorUtil.equalsRandomComparator());

        for (AdRankItem adRankItem : result) {
            adRankItem.setVideoId(param.getVideoId());
            adRankItem.setScore_type(699);
        }

        return result;
    }

    public List<AdRankItem> thompsonScorerByExp670(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        Map<Long, CreativeStatistic> cidMap = this.batchFindCreativeRedisCache(redisCidActionKeyV1, adIdList);
        Map<Long, CreativeStatistic> vidCidMap = this.batchFindCreativeRedisCache(redisCidVidActionKeyV1 + param.getVideoId() + "_", adIdList);

        double w1 = Double.parseDouble(exp670Param.getOrDefault("w1", "1").toString());
        double w2 = Double.parseDouble(exp670Param.getOrDefault("w2", "1").toString());

        double alpha = Double.parseDouble(exp670Param.getOrDefault("alpha", "0").toString());
        double cidBeta = Double.parseDouble(exp670Param.getOrDefault("cidBeta", "0").toString());
        double vidCidBeta = Double.parseDouble(exp670Param.getOrDefault("vidCidBeta", "0").toString());


        List<AdRankItem> result = new ArrayList<>(adIdList.size());

        for (AdPlatformCreativeDTO dto : adIdList) {

            // 日志上报扩展参数
            Map<String, Object> ext = new HashMap<>();
            double score = 0;
            double cpa = 0.0;
            try {

                CreativeStatistic cidStatistic = cidMap.getOrDefault(dto.getCreativeId(), new CreativeStatistic());
                CreativeStatistic vidCidStatistic = vidCidMap.getOrDefault(dto.getCreativeId(), new CreativeStatistic());

                cpa = cidStatistic.parseCpaToDouble();
                double cidExp = cidStatistic.parseExpToDouble();
                double vidCidExp = vidCidStatistic.parseExpToDouble();

                // double cidScore = this.betaSampler(cidStatistic.parseOrderToDouble() + alpha, cidStatistic.parseExpToDouble() + cidBeta);
                // double vidCidScore = this.betaSampler(vidCidStatistic.parseOrderToDouble() + alpha, vidCidStatistic.parseExpToDouble() + vidCidBeta);
                double cidScore = this.orderDivideExp(cidStatistic);
                double vidCidScore = this.orderDivideExp(vidCidStatistic);


                double b = w1 * vidCidExp + w2 * cidExp;
                if (b != 0) {
                    score = ((w1 * vidCidScore * vidCidExp + w2 * cidScore * cidExp) / b) * cpa;
                }

                ext.put("w1", w1);
                ext.put("w2", w2);
                ext.put("cidScore", cidScore);
                ext.put("vidCidScore", vidCidScore);
                ext.put("cidA", alpha);
                ext.put("vidCidA", alpha);
                ext.put("cidB", cidBeta);
                ext.put("vidCidB", vidCidBeta);
                ext.put("cidExp", cidExp);
                ext.put("vidCidExp", vidCidExp);
                ext.put("bid1", dto.getBid1());
                ext.put("bid2", dto.getBid2());
                ext.put("cidStatistic", JSON.toJSONString(cidStatistic));
                ext.put("vidCidStatistic", JSON.toJSONString(vidCidStatistic));
                ext.put("cpa", cpa);
            } catch (Exception e) {
                log.error("svc=670exp, error: ", e);
                score = 0; // 确保在异常情况下`score`有一个默认值
            }

            AdRankItem item = new AdRankItem();
            item.setCpa(cpa);
            item.setAdId(dto.getCreativeId());
            item.setWeight(dto.getWeight());
            item.setScore(score);
            item.setExt(ext);
            item.setBid1(dto.getBid1());
            item.setBid2(dto.getBid2());
            item.setCreativeCode(dto.getCreativeCode());
            item.setScore_type(670);
            item.setVideoId(param.getVideoId());
            result.add(item);

        }

        result.sort(ComparatorUtil.equalsRandomComparator());
        return result;
    }

    private void calcScore(List<AdRankItem> result, List<AdPlatformCreativeDTO> adIdList, Double alpha, Double cidBeta, Double vidCidBeta, Map<Long, CreativeStatistic> cidMap, Map<Long, CreativeStatistic> vidCidMap, Map<String, Double> expParam) {
        for (AdPlatformCreativeDTO dto : adIdList) {

            CreativeStatistic cidStatistic = cidMap.getOrDefault(dto.getCreativeId(), new CreativeStatistic());
            CreativeStatistic vidCidStatistic = vidCidMap.getOrDefault(dto.getCreativeId(), new CreativeStatistic());

            double cidExp = cidStatistic.parseExpToDouble();
            double vidCidExp = vidCidStatistic.parseExpToDouble();

            double cidScore = this.calcThompsonScore(expParam, cidStatistic, alpha, cidBeta);
            double vidCidScore = this.calcThompsonScore(expParam, vidCidStatistic, alpha, vidCidBeta);

            double w1 = expParam.getOrDefault("w1", 1d);
            double w2 = expParam.getOrDefault("w2", 1d);

            double cpa = cidStatistic.parseCpaToDouble();

            double score = 0;
            if (w1 != 0 || w2 != 0) {
                score = ((w1 * vidCidScore * vidCidExp + w2 * cidScore * cidExp) / (w1 * vidCidExp + w2 * cidExp)) * cpa;
            }


            // 日志上报扩展参数
            Map<String, Object> ext = new HashMap<>();
            ext.put("w1", w1);
            ext.put("w2", w2);
            ext.put("cidScore", cidScore);
            ext.put("vidCidScore", vidCidScore);
            ext.put("cidA", alpha);
            ext.put("vidCidA", alpha);
            ext.put("cidB", cidBeta);
            ext.put("vidCidB", vidCidBeta);
            ext.put("cidExp", cidExp);
            ext.put("vidCidExp", vidCidExp);
            ext.put("bid1", dto.getBid1());
            ext.put("bid2", dto.getBid2());
            ext.put("cidStatistic", JSON.toJSONString(cidStatistic));
            ext.put("vidCidStatistic", JSON.toJSONString(vidCidStatistic));
            ext.put("cpa", cpa);

            log.info("svc=699And670Score, score: {}, param: {}", score, JSON.toJSONString(ext));


            AdRankItem item = new AdRankItem();
            item.setCpa(cpa);
            item.setAdId(dto.getCreativeId());
            item.setWeight(dto.getWeight());
            item.setScore(score);
            item.setExt(ext);
            item.setBid1(dto.getBid1());
            item.setBid2(dto.getBid2());
            item.setCreativeCode(dto.getCreativeCode());

            result.add(item);

        }
    }


    private Map<Long, CreativeStatistic> batchFindCreativeRedisCache(String keyPrefix, List<AdPlatformCreativeDTO> adIdList) {
        Map<Long, CreativeStatistic> resultMap = new HashMap<>();
        List<String> redisKeys = adIdList.stream()
                .map(dto -> keyPrefix + dto.getCreativeId())
                .collect(Collectors.toList());

        List<String> values = redisHelper.getValues(redisKeys);
        for (int i = 0; i < adIdList.size(); i++) {
            Long cid = adIdList.get(i).getCreativeId();
            String value = values.get(i);
            if (StringUtils.isNotBlank(value)) {
                resultMap.put(cid, gson.fromJson(value, CreativeStatistic.class));
            }
        }

        return resultMap;
    }

    private double orderDivideExp(CreativeStatistic statistic) {
        double order = statistic.parseOrderToDouble();
        double exp = statistic.parseExpToDouble();
        if (exp != 0) {
            return order / exp;
        }
        return 0.0;
    }

    private double calcThompsonScore(Map<String, Double> expParam, CreativeStatistic creativeStatistic, Double defaultAlpha, Double defaultBeta) {
        Double alpha = expParam.getOrDefault("alpha", defaultAlpha);
        Double beta = expParam.getOrDefault("beta", defaultBeta);

        double order = creativeStatistic.parseOrderToDouble() + alpha;
        double exp = creativeStatistic.parseExpToDouble() + beta;

        log.info("calcThompsonScore.order: {}, exp: {}", order, exp);
        return this.betaSampler(order, exp);
    }

    private Double sumCreativeStatisticExp(Collection<CreativeStatistic> creativeStatistics) {
        return creativeStatistics.stream()
                .map(CreativeStatistic::getExp)
                .filter(StringUtils::isNotBlank)
                .collect(Collectors.summarizingDouble(Double::parseDouble))
                .getSum();
    }

    private Map<String, Object> extMap(CreativeStatistic statistic, String abCode, Double cpa, Double viewThreshold, Double alpha, Double beta, Double beta_k) {
        Map<String, Object> map = new HashMap<>();
        if (Objects.nonNull(viewThreshold)) {
            map.put("viewThreshold", viewThreshold);
        }
        map.put("alpha", alpha);
        map.put("beta", beta);
        map.put("beta_k", beta_k);
        map.put("cpa", cpa);
        if (Objects.nonNull(statistic)) {
            map.put("click", statistic.click);
            map.put("order", statistic.getOrder());
            map.put("exp", statistic.getExp());
        }
        return map;
    }

    public List<AdRankItem> thompsonScorerByExp672(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        return statisticsScore(param, adIdList, exp672Param, 672);
    }

    public List<AdRankItem> thompsonScorerByExp671(ScoreParam param, List<AdPlatformCreativeDTO> adIdList) {
        return statisticsScore(param, adIdList, exp671Param, 671);
    }

    private List<AdRankItem> statisticsScore(ScoreParam param, List<AdPlatformCreativeDTO> adIdList, Map<String, Object> expParam, int scoreType){
        String cidRedisKey = expParam.getOrDefault("cidActionRedisKey", redisCreativeStatisticsPrefix).toString();
        String vidCidRedisKey = expParam.getOrDefault("vidCidActionRedisKey", redisVideoCreativeStatisticsPrefix).toString();
        double viewThreshold = Double.parseDouble(expParam.getOrDefault("viewThreshold", "7000").toString());

        // RedisKey前缀判断
        if (!StringUtils.equals(redisCidActionKeyV1, cidRedisKey) && !StringUtils.equals(redisCreativeStatisticsPrefix, cidRedisKey)) {
            cidRedisKey = redisCreativeStatisticsPrefix;
        }
        if (!StringUtils.equals(redisCidVidActionKeyV1, vidCidRedisKey) && !StringUtils.equals(redisVideoCreativeStatisticsPrefix, vidCidRedisKey)) {
            vidCidRedisKey = redisVideoCreativeStatisticsPrefix;
        }

        Map<Long, CreativeStatistic> paramCidRedisCache = this.batchFindCreativeRedisCache(cidRedisKey, adIdList);
        Map<Long, CreativeStatistic> paramVidCidRedisCache = this.batchFindCreativeRedisCache(vidCidRedisKey + param.getVideoId() + "_", adIdList);

        List<AdRankItem> result = new ArrayList<>(adIdList.size());
        for (AdPlatformCreativeDTO dto : adIdList) {
            Map<String, Object> ext = new HashMap<>();
            double score = 0.0;
            double cpa = 0.0;
            Long cid = dto.getCreativeId();
            try {
                String pairOrSingle = "pair";
                CreativeStatistic vidCidStatistic = paramVidCidRedisCache.getOrDefault(cid, new CreativeStatistic());
                CreativeStatistic cidStatistic = paramCidRedisCache.getOrDefault(cid, new CreativeStatistic());

                cpa = cidStatistic.parseCpaToDouble();

                double order = vidCidStatistic.parseOrderToDouble();
                double exp = vidCidStatistic.parseExpToDouble();

                if (exp < viewThreshold) {
                    pairOrSingle = "single";
                    order = cidStatistic.parseOrderToDouble();
                    exp = cidStatistic.parseExpToDouble();
                }

                if (exp != 0) {
                    score = (order / exp) * cpa;
                }

                ext.put("order", order);
                ext.put("exp", exp);
                ext.put("viewThreshold", viewThreshold);
                ext.put("pairOrSingle", pairOrSingle);
                ext.put("cidStatistic", JSON.toJSONString(cidStatistic));
                ext.put("vidCidStatistic", JSON.toJSONString(vidCidStatistic));
                ext.put("cpa", cpa);
            } catch (Exception e) {
                log.error("svc=statisticsScore, error: ", e);
            }

            AdRankItem item = new AdRankItem();
            item.setCpa(cpa);
            item.setAdId(dto.getCreativeId());
            item.setScore(score);
            item.setExt(ext);
            item.setVideoId(param.getVideoId());
            item.setScore_type(scoreType);
            item.setWeight(dto.getWeight());
            item.setCreativeCode(dto.getCreativeCode());
            result.add(item);

        }
        result.sort(ComparatorUtil.equalsRandomComparator());
        return result;
    }


    class CreativeStatistic {

        private String exp;
        private String click;
        private String order;
        private String cpa;

        public CreativeStatistic() {
        }

        public void setCpa(String cpa) {
            this.cpa = cpa;
        }

        public String getExp() {
            if (exp == null || "".equals(exp)) {
                return "0";
            }
            return exp;
        }

        public double parseExpToDouble() {
            if (StringUtils.isBlank(exp)) {
                return 0.0;
            }
            return Double.parseDouble(exp);
        }

        public void setExp(String exp) {
            this.exp = exp;
        }

        public String getClick() {
            if (click == null || "".equals(click)) {
                return "0";
            }
            return click;
        }

        public double parseClickToDouble() {
            if (StringUtils.isBlank(click)) {
                return 0.0;
            }
            return Double.parseDouble(click);
        }

        public void setClick(String click) {
            this.click = click;
        }

        public String getOrder() {
            if (order == null || "".equals(order)) {
                return "0";
            }
            return order;
        }

        public double parseOrderToDouble() {
            if (StringUtils.isBlank(order)) {
                return 0.0;
            }
            return Double.parseDouble(order);
        }

        public void setOrder(String order) {
            this.order = order;
        }

        public String getCpa() {
            if (cpa == null || "".equals(cpa)) {
                return "0";
            }
            return cpa;
        }

        public double parseCpaToDouble() {
            if (StringUtils.isBlank(cpa)) {
                return 0.0;
            }
            return Double.parseDouble(cpa);
        }
    }

    double betaSampler(double alpha, double beta) {
        if (alpha == 0 || beta == 0) {
            return 0.0d;
        }
        BetaDistribution betaSample = new BetaDistribution(alpha, beta);
        return betaSample.sample();
    }

    @Value("${ad.engine.new.thompson.exp.V2.663:{\"randomMin\":0.000001,\"randomMax\":0.00001,\"alpha\":1,\"beta\":10000}}")
    public void setExp663Param(String str) {
        this.exp663Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.664:{}}")
    public void setExp664Param(String str) {
        this.exp664Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.665:{}}")
    public void setExp665Param(String str) {
        this.exp665Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.666:{}}")
    public void setExp666Param(String str) {
        this.exp666Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.669:{}}")
    public void setExp669Param(String str) {
        this.exp669Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.670:{}}")
    public void setExp670Param(String str) {
        this.exp670Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.671:{}}")
    public void setExp671Param(String str) {
        this.exp671Param = gson.fromJson(str, Map.class);
    }

    @Value("${ad.engine.new.thompson.exp.V2.672:{}}")
    public void setExp672Param(String str) {
        this.exp672Param = gson.fromJson(str, Map.class);
    }
}
