package examples.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.odps.data.Record;
import org.apache.commons.collections4.MapUtils;

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

public class AdUtil {

    public static final String IS_API_FLAG = "1";

    /**
     * 将线上metaFeature中的Key替换为大数据表中的Key，用于定位问题
     */
    public static JSONObject keyReplace(JSONObject featureJson) {
        JSONObject newJson = new JSONObject();
        Map<String, String> keyMap = new HashMap<String, String>() {{
            put("alg_cid_feature_basic_info", "b1_feature");
            put("alg_cid_feature_adver_action", "b2_feature");
            put("alg_cid_feature_cid_action", "b3_feature");
            put("alg_cid_feature_region_action", "b4_feature");
            put("alg_cid_feature_app_action", "b5_feature");
            put("alg_cid_feature_week_action", "b6_feature");
            put("alg_cid_feature_hour_action", "b7_feature");
            put("alg_cid_feature_brand_action", "b8_feature");
            put("alg_cid_feature_weChatVersion_action", "b9_feature");
            put("alg_mid_feature_ad_action", "c1_feature");
            put("alg_cid_feature_vid_cf", "d1_feature");
            put("alg_cid_feature_vid_cf_rank", "d2_feature");
            put("alg_vid_feature_basic_info", "d3_feature");
            put("alg_mid_feature_return_tags", "e1_feature");
            put("alg_mid_feature_share_tags", "e2_feature");
        }};

        for (Map.Entry<String, Object> entry : featureJson.entrySet()) {
            String key = keyMap.getOrDefault(entry.getKey(), entry.getKey());
            newJson.put(key, entry.getValue());
        }

        return newJson;
    }

    /**
     * 是否有回传，用于生产数据时的过滤
     */
    public static boolean isApi(Record record) {

        if (record.isNull("extend_alg")) {
            return false;
        }

        JSONObject extendAlgJson = JSON.parseObject(record.getString("extend_alg"));
        if (MapUtils.isEmpty(extendAlgJson)) {
            return false;
        }
        if (extendAlgJson.containsKey("extinfo")) {
            JSONObject extInfoJson = extendAlgJson.getJSONObject("extinfo");
            if (extInfoJson.containsKey("isApi")) {
                return IS_API_FLAG.equals(extInfoJson.getString("isApi"));
            }
        }
        if (extendAlgJson.containsKey("is_api")) {
            return IS_API_FLAG.equals(extendAlgJson.getString("is_api"));
        }
        return true;
    }
}
