package com.tzld.piaoquan.ad.engine.service.predict.v2;


import com.alibaba.fastjson.JSONObject;
import com.tzld.piaoquan.ad.engine.commons.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public abstract class ThresholdPredictStrategy extends BasicPredict {

    abstract Map<String, Double> thresholdConfig(PredictContext ctx);

    abstract List<String> genThresholdKeys(PredictContext ctx);

    @Override
    public Map<String, Object> predict(PredictContext ctx) {
        Map<String, Double> thresholdConfig = this.thresholdConfig(ctx);

        double score = this.calcScoreByMid(ctx.getMid());

        List<String> thresholdKeys = genThresholdKeys(ctx);

        String finalThresholdKeys = "";
        double threshold = 0d;

        for (String thresholdKey : thresholdKeys) {
            if (thresholdConfig.containsKey(thresholdKey)) {
                finalThresholdKeys = thresholdKey;
                threshold = thresholdConfig.get(thresholdKey);
                break;
            }
        }

        Map<String, Object> rtnMap = new HashMap<>();
        if (score < threshold) {
            rtnMap.putAll(rtnAdPredict(ctx));
            rtnMap.put("model", this.name());
        } else {
            rtnMap.putAll(rtnNoAdPredict(ctx));
            rtnMap.put("no_ad_strategy", this.name());
        }

        rtnMap.put("score", score);
        rtnMap.put("threshold", threshold);
        rtnMap.put("userLayer", ctx.getUserLayer());
        rtnMap.put("thresholdParamKey", finalThresholdKeys);
        rtnMap.put("shareType", ctx.getHandleAfterShareType());

        this.printLog(rtnMap, ctx, thresholdConfig);

        return rtnMap;

    }

    protected void printLog(Map<String, Object> rtnMap, PredictContext ctx, Map<String, Double> thresholdConfig) {
        JSONObject logJson = new JSONObject();
        logJson.putAll(rtnMap);
        logJson.put("mid", ctx.getMid());
        logJson.put("appType", ctx.getAppType());

        logJson.put("expId", this.name());
        logJson.put("adPlatformType", ctx.getAdPlatformType());
        logJson.put("abCode", ctx.getAdAbCode());
        logJson.put("configItem", thresholdConfig);
        logJson.put("rootSessionId", ctx.getRootSessionId());

        log.info("广告跳出选择 -- {}实验结果: {}, 参数: {}",
                this.name(), JSONUtils.toJson(rtnMap), logJson.toJSONString());
    }
}
