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


import com.tzld.piaoquan.ad.engine.commons.score.BaseLRModelScorer;
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.LRModel;
import com.tzld.piaoquan.recommend.feature.domain.ad.base.*;
import com.tzld.piaoquan.recommend.feature.domain.ad.feature.VlogAdCtrLRFeatureExtractor;
import com.tzld.piaoquan.recommend.feature.model.sample.LRSamples;
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.List;
import java.util.concurrent.*;


//@Service
public class VlogAdCvrLRScorer extends BaseLRModelScorer {

    private final static int CORE_POOL_SIZE = 64;

    private static final int LOCAL_TIME_OUT = 150;
    private final static Logger LOGGER = LoggerFactory.getLogger(VlogAdCvrLRScorer.class);
    private static final ExecutorService executorService = Executors.newFixedThreadPool(8);
    private static final double defaultUserCtrGroupNumber = 10.0;
    private static final int enterFeedsScoreRatio = 10;
    private static final int enterFeedsScoreNum = 20;

    public VlogAdCvrLRScorer(ScorerConfigInfo configInfo) {
        super(configInfo);
    }

    @Override
    public List<AdRankItem> scoring(final ScoreParam param,
                                    final UserAdFeature userFeature,
                                    final List<AdRankItem> rankItems) {

        if (userFeature == null || CollectionUtils.isEmpty(rankItems)) {
            return rankItems;
        }

        long startTime = System.currentTimeMillis();
        LOGGER.info("VlogAdCvrLRScorer.scorerConfigInfo.getModelPath: {}: {}", scorerConfigInfo.getModelPath(), this.getModel());
        LRModel model = (LRModel) this.getModel();
        LOGGER.debug("model size: [{}]", model.getModelSize());

        List<AdRankItem> result = rankItems;
        result = rankByJava(rankItems, param.getRequestContext(), userFeature);

        LOGGER.debug("ctr ranker time java items size={}, time={} ", result != null ? result.size() : 0,
                System.currentTimeMillis() - startTime);

        return result;
    }

    private List<AdRankItem> rankByJava(final List<AdRankItem> items,
                                        final AdRequestContext requestContext,
                                        final UserAdFeature user) {
        long startTime = System.currentTimeMillis();
        LRModel model = (LRModel) this.getModel();
        LOGGER.debug("model size: [{}]", model.getModelSize());

        // userAdBytes
        UserAdBytesFeature userInfoBytes = null;
        userInfoBytes = new UserAdBytesFeature(user);

        // 所有都参与打分，按照cvr排序
        multipleScore(items, userInfoBytes, requestContext, model);

        // debug log
        if (LOGGER.isDebugEnabled()) {
            for (int i = 0; i < items.size(); i++) {
                LOGGER.debug("after enter feeds model predict ctr score [{}] [{}]", items.get(i), items.get(i).getScore());
            }
        }

        LOGGER.debug("ctr ranker java execute time: [{}]", System.currentTimeMillis() - startTime);
        LOGGER.debug("[ctr ranker time java] items size={}, cost={} ", items != null ? items.size() : 0,
                System.currentTimeMillis() - startTime);
        return items;
    }


    /**
     * 计算 predict cvr
     */
    public double calcScore(final LRModel lrModel,
                            final AdRankItem item,
                            final UserAdBytesFeature userInfoBytes,
                            final AdRequestContext requestContext) {

        LRSamples lrSamples = null;
        VlogAdCtrLRFeatureExtractor bytesFeatureExtractor;
        bytesFeatureExtractor = new VlogAdCtrLRFeatureExtractor();

        try {
            AdItemBytesFeature newsInfoBytes = new AdItemBytesFeature(item.getItemFeature());
            lrSamples = bytesFeatureExtractor.single(userInfoBytes, newsInfoBytes,
                    new AdRequestContextBytesFeature(requestContext));
        } catch (Exception e) {
            LOGGER.error("extract feature error for imei={}, doc={}, [{}]", new Object[]{new String(userInfoBytes.getMid()), item.getAdId(),
                    ExceptionUtils.getFullStackTrace(e)});
        }


        double pro = 0.0;
        if (lrSamples != null && lrSamples.getFeaturesList() != null) {
            try {
                pro = lrModel.score(lrSamples);

            } catch (Exception e) {
                LOGGER.error("score error for doc={} exception={}", new Object[]{
                        item.getAdId(), ExceptionUtils.getFullStackTrace(e)});
            }
        }
//        lrSamples.toBuilder().setPredictCtr(pro);
        item.setCvr(pro);
        return pro;
    }


    /**
     * 并行打分
     *
     * @param items
     * @param userInfoBytes
     * @param requestContext
     * @param model
     */
    private void multipleScore(final List<AdRankItem> items,
                                  final UserAdBytesFeature userInfoBytes,
                                  final AdRequestContext requestContext,
                                  final LRModel model) {

        List<Callable<Object>> calls = new ArrayList<Callable<Object>>();
        for (int index = 0; index < items.size(); index++) {
            final int fIndex = index;
            items.get(fIndex).setScore(0.0);   //原始分为 cube中的粗打分，如果超时，为原始值存在问题， 需要置0
            calls.add(new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                    try {
                        calcScore(model, items.get(fIndex), userInfoBytes, requestContext);
                    } catch (Exception e) {
                        LOGGER.error("ctr exception: [{}] [{}]", items.get(fIndex).adId, 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 {},{}", ExceptionUtils.getFullStackTrace(e));
                } catch (ExecutionException e) {
                    LOGGER.error("ExecutionException {},{}", requestContext.getApptype(),
                            ExceptionUtils.getFullStackTrace(e));
                }
            }
        }
        LOGGER.debug("Ctr Score {}, Total: {}, Cancel: {}", new Object[]{requestContext.getApptype(), items.size(), cancel});
    }
}