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

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.tzld.piaoquan.ad.engine.service.predict.param.request.ThresholdPredictModelRequestParam;
import lombok.extern.slf4j.Slf4j;

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

@Slf4j
public class ConvertUtil {

    public static PredictContext predictParam2Context(ThresholdPredictModelRequestParam param) {
        PredictContext context = new PredictContext();
        context.setMid(param.getMid());
        context.setVideoId(Optional.ofNullable(param.getVideoId()).map(Object::toString).orElse(""));
        context.setAppType(Optional.ofNullable(param.getAppType()).map(Object::toString).orElse(""));
        context.setAdAbCode(param.getAbTestCode());

        context.setRegion(param.getRegion());
        context.setCity(param.getCity());
        context.setPqtId(param.getPqtId());
        context.setUserExternalSource(param.getUserExternalSource());
        context.setShareLayer(param.getShareLayer());
        context.setMachineInfo(param.getMachineInfo());

        context.setRootSessionId(param.getRootSessionId());
        context.setAdPlatformType(param.getAdPlatformType());
        context.setShareType(param.getShareType());
        context.setUserLayer(param.getUserLayer());

        JSONObject abExpInfo = param.getAbExpInfo();
        Map<String, JSONObject> expConfigMap = ConvertUtil.parseAbTest002Info(abExpInfo);
        context.setExpCodeSet(expConfigMap.keySet());
        context.setExpConfigMap(expConfigMap);

        return context;
    }


    private static Map<String, JSONObject> parseAbTest002Info(JSONObject abExpInfo) {
        Map<String, JSONObject> abTest002Info = new HashMap<>();
        try {
            List<JSONObject> abTest002 = abExpInfo.getJSONArray("ab_test002").toJavaObject(new TypeReference<List<JSONObject>>() {
            });

            for (JSONObject json : abTest002) {
                String expCode = json.getString("abExpCode");
                JSONObject configValue = json.getJSONObject("configValue");
                abTest002Info.put(expCode, configValue);
            }

        } catch (Exception e) {
            log.error("ConvertUtil解析广告层实验配置异常: ", e);
        }

        return abTest002Info;
    }

}
