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

import com.tzld.piaoquan.ad.engine.commons.score.AbstractScorer;
import com.tzld.piaoquan.ad.engine.commons.score.ScoreParam;
import com.tzld.piaoquan.ad.engine.commons.score.ScorerConfigInfo;
import com.tzld.piaoquan.ad.engine.commons.score.model.CreativeCalibrationModel;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.AdRankItem;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.UserAdFeature;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

public class CreativeCalibrationScorer extends AbstractScorer {


    private static final int LOCAL_TIME_OUT = 150;
    private static final Logger LOGGER = LoggerFactory.getLogger(CreativeCalibrationScorer.class);
    private static final ExecutorService executorService = Executors.newFixedThreadPool(128);

    public CreativeCalibrationScorer(ScorerConfigInfo scorerConfigInfo) {
        super(scorerConfigInfo);
    }

    @Override
    public void loadModel() {
        super.doLoadModel(CreativeCalibrationModel.class);
    }

    @Override
    public List<AdRankItem> scoring(ScoreParam param, UserAdFeature userAdFeature, List<AdRankItem> rankItems) {
        throw new NoSuchMethodError();
    }

    public List<AdRankItem> scoring(final Map<String, String> sceneFeatureMap,
                                    final Map<String, String> userFeatureMap,
                                    final List<AdRankItem> rankItems) {
        if (CollectionUtils.isEmpty(rankItems)) {
            return rankItems;
        }

        long startTime = System.currentTimeMillis();

        List<AdRankItem> result = rankByJava(sceneFeatureMap, userFeatureMap, rankItems);

        LOGGER.debug("[CreativeCalibrationScorer] scoring items size={}, time={} ",
                result.size(), System.currentTimeMillis() - startTime);

        return result;
    }

    private List<AdRankItem> rankByJava(final Map<String, String> sceneFeatureMap,
                                        final Map<String, String> userFeatureMap,
                                        final List<AdRankItem> items) {
        long startTime = System.currentTimeMillis();
        CreativeCalibrationModel model = (CreativeCalibrationModel) this.getModel();
        LOGGER.debug("model size: [{}]", model.getModelSize());

        // 所有都参与打分，按照ctr排序
        multipleCtrScore(items, userFeatureMap, sceneFeatureMap, model);

        // debug log
        if (LOGGER.isDebugEnabled()) {
            for (AdRankItem item : items) {
                LOGGER.debug("before enter feeds model predict ctr score [{}] [{}]", item, item);
            }
        }

        Collections.sort(items);

        LOGGER.debug("[CreativeCalibrationScorer] items size={}, cost={} ",
                items.size(), System.currentTimeMillis() - startTime);
        return items;
    }

    private void multipleCtrScore(final List<AdRankItem> items,
                                  final Map<String, String> userFeatureMap,
                                  final Map<String, String> sceneFeatureMap,
                                  final CreativeCalibrationModel model) {

        List<Callable<Object>> calls = new ArrayList<Callable<Object>>();
        for (int index = 0; index < items.size(); index++) {
            final int fIndex = index;
            calls.add(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    try {
                        calcScore(model, items.get(fIndex), userFeatureMap, sceneFeatureMap);
                    } catch (Exception e) {
                        LOGGER.error("ctr exception: [{}] [{}]", items.get(fIndex), ExceptionUtils.getFullStackTrace(e));
                    }
                    return new Object();
                }
            });
        }

        List<Future<Object>> futures = null;
        try {
            futures = executorService.invokeAll(calls, LOCAL_TIME_OUT, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            LOGGER.error("execute invoke fail: {}", ExceptionUtils.getFullStackTrace(e));
        }

        // 等待所有请求的结果返回, 超时也返回
        int cancel = 0;
        if (futures != null) {
            for (Future<Object> future : futures) {
                try {
                    if (!future.isDone() || future.isCancelled() || future.get() == null) {
                        cancel++;
                    }
                } catch (InterruptedException e) {
                    LOGGER.error("InterruptedException: ", e);
                } catch (ExecutionException e) {
                    LOGGER.error("ExecutionException {},", sceneFeatureMap.size(), e);
                }
            }
        }
    }

    public double calcScore(final CreativeCalibrationModel model,
                            final AdRankItem item,
                            final Map<String, String> userFeatureMap,
                            final Map<String, String> sceneFeatureMap) {
        double ctcvrScore = item.getLrScore();
        double newCtcvrScore = ctcvrScore;
        try {

            double diffRate = model.getDiffRate(item.getAdId());
            newCtcvrScore = ctcvrScore / (1 + diffRate);
            item.setLrScore(newCtcvrScore);
            item.getScoreMap().put("diff_rate", diffRate);
            item.getScoreMap().put("originCtcvrScore", ctcvrScore);
            item.getScoreMap().put("ctcvrScore", newCtcvrScore);
        } catch (Exception e) {
            LOGGER.error("[score calibration] calcScore error: ", e);
        }

        return newCtcvrScore;
    }

}
