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

import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.spring.annotation.ApolloJsonValue;
import com.tzld.piaoquan.ad.engine.commons.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class PredictStrategyByMorning56 extends BasicPredict {

    @ApolloJsonValue("${experiment.morning56.root.session.id.tail.config:[]}")
    private List<RootSessionIdTailConfigItem> configItems;

    @Override
    public String name() {
        return "morning56";
    }

    @Override
    public Map<String, Object> predict(PredictContext ctx) {

        String rootSessionId = ctx.getRootSessionId();
        String userLayer = ctx.getUserLayer();
        String shareType = ctx.getShareType();
        if (CollectionUtils.isEmpty(configItems) || StringUtils.isAnyBlank(rootSessionId, userLayer, shareType)) {
            Map<String, Object> returnMap = new HashMap<>();
            returnMap.putAll(rtnNoAdPredict(ctx));
            returnMap.put("msg","no_config_error");
            return returnMap;
        }

        double score = this.calcScoreByMid(ctx.getMid());
        String tail = rootSessionId.substring(rootSessionId.length() - 1);
        if (StringUtils.isNotBlank(shareType)) {
            shareType = shareType.replace("return", "")
                    .replace("mids", "");
        }

        for (RootSessionIdTailConfigItem item : configItems) {
            if (item.getTail().contains(tail)) {
                Map<String, Object> returnMap = new HashMap<>();
                double threshold;
                String thresholdKey = "";

                // 生成可用的Key列表
                List<String> keys = Arrays.asList(userLayer + "_" + shareType, "default_" + shareType, "default_threshold");
                for (String key : keys) {
                    if (item.getConfig().containsKey(key)) {
                        thresholdKey = key;
                        break;
                    }
                }


                threshold = item.getConfig().getOrDefault(thresholdKey, 0.0);

                if (score < threshold) {
                    returnMap.putAll(rtnAdPredict(ctx));
                    returnMap.put("model", this.name());
                } else {
                    returnMap.putAll(rtnNoAdPredict(ctx));
                    returnMap.put("no_ad_strategy", this.name());
                }

                returnMap.put("score", score);
                returnMap.put("threshold", threshold);
                returnMap.put("userLayer", userLayer);

                JSONObject logJson = new JSONObject();
                logJson.putAll(returnMap);
                logJson.put("mid", ctx.getMid());
                logJson.put("appType", ctx.getAppType());
                logJson.put("rootSessionIdTail", tail);
                logJson.put("shareType", shareType);

                logJson.put("expId", "morning56Exp");
                logJson.put("thresholdParamKey", thresholdKey);
                logJson.put("adPlatformType", ctx.getAdPlatformType());
                logJson.put("abCode", ctx.getAdAbCode());
                logJson.put("configItem", item);
                logJson.put("rootSessionId", ctx.getRootSessionId());

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

                return returnMap;
            }
        }

        Map<String, Object> returnMap = new HashMap<>();
        returnMap.putAll(rtnNoAdPredict(ctx));
        returnMap.put("msg","no_config_error");
        return returnMap;
    }

}
