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

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
public class PredictStrategyBy673 extends ThresholdPredictStrategy {

    @Value("${filter.with.region:1}")
    private String filterWithRegion;
    @Override
    Map<String, Double> thresholdConfig(PredictContext ctx) {

        if (StringUtils.isAnyBlank(ctx.getUserExternalSource(), ctx.getShareLayer())) {
            return Collections.emptyMap();
        }

        try {
            JSONObject json = ctx.getExpConfigMap().getOrDefault("673", new JSONObject());
            String configKey = String.format("%s:%s", ctx.getUserExternalSource(), ctx.getShareLayer());
            if("1".equals(filterWithRegion) && StringUtils.isNotBlank(configKey)) {
                String region = StringUtils.isBlank(ctx.getRegion()) ? "未知地区" : ctx.getRegion();
                String city = StringUtils.isBlank(ctx.getCity()) ? "未知地区" : ctx.getCity();
                configKey = configKey + ":" + region + "_" + city;
                log.info( "PredictStrategyBy673 configKey: {}", configKey);
            }
            JSONObject configJson = json.getJSONObject(configKey);
            if (MapUtils.isEmpty(configJson)) {
                return Collections.emptyMap();
            }
            return configJson.toJavaObject(new TypeReference<Map<String, Double>>() {
            });
        } catch (Exception e) {
            log.error("PredictStrategyBy673 parse 673 exp param error \n", e);
            return Collections.emptyMap();
        }
    }

    @Override
    public Map<String, Object> predict(PredictContext ctx) {
        Map<String, Double> thresholdConfig = this.thresholdConfig(ctx);
        if (MapUtils.isEmpty(thresholdConfig)) {
            return null;
        }
        double score = this.calcScoreByMid(ctx.getMid());

        List<String> thresholdKeys = genThresholdKeys(ctx);
        if (CollectionUtils.isEmpty(thresholdKeys)) {
            return null;
        }

        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;

    }


    @Override
    List<String> genThresholdKeys(PredictContext ctx) {

        List<String> keys = new ArrayList<>();
        for (String appType : Arrays.asList(ctx.getAppType(), "default")) {
            for (String userLayer : Arrays.asList(ctx.getUserLayer(), "default")) {
                keys.add(String.join("_", appType, userLayer, ctx.getHandleAfterShareType()));
            }
        }
        keys.add("default_threshold");
        return keys;
    }

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

}
