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

import com.google.common.reflect.TypeToken;
import com.tzld.piaoquan.ad.engine.commons.util.JSONUtils;
import com.tzld.piaoquan.ad.engine.service.predict.param.ThresholdPredictModelParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

@Component
public class NewExpInfoHelper {

    public static Map<String,Set<String>> appExpIdCache=new HashMap<>();
    public static Map<String,Exp> expIdAndRangeCache=new HashMap<>();
    public static String flagId;

    @Value("${new.exp,config.v2:[]}")
    private void setNewExpInfo(String str){
        List<ExpConfig> expConfigs= JSONUtils.fromJson(str, new TypeToken<List<ExpConfig>>() {
        }, Collections.emptyList());
        for (ExpConfig expConfig : expConfigs) {
            String appId=expConfig.getAppType();
            for (Layer layer : expConfig.layers) {
                if (layer.layerId.equals("ad-server")){
                    Set<String> expIdSet=new HashSet<>();
                    for (Exp exp : layer.getExps()) {
                        expIdSet.add(exp.getExpId());
                        expIdAndRangeCache.put(exp.getExpId(),exp);
                    }
                    appExpIdCache.put(appId,expIdSet);
                }
            }
        }
    }

    public static int getNewExpGroup(HttpServletRequest httpServletRequest){
        try {
            Map<String, String> expMap = JSONUtils.fromJson(httpServletRequest.getHeader("newGroupInfo"), new TypeToken<Map<String, String>>() {
            }, Collections.emptyMap());
            String groupStr=expMap.get("group");
            if(groupStr.contains("ab100")){
                return -1;
            }
            Map<String, String> groupMap = JSONUtils.fromJson(groupStr, new TypeToken<Map<String, String>>() {
            }, Collections.emptyMap());
            return Integer.parseInt(groupMap.getOrDefault("ad-server","-1"));
        }catch (Exception e){
            return -1;
        }
    }

    public static boolean checkInNewExpGroupAndSetParamIfIn(Collection<String> abCodes, String appId, int groupNumber, String expId, ThresholdPredictModelParam modelParam) {
        if (abCodes.contains(NewExpInfoHelper.flagId)) {
            return checkInNewExpGroupAndSetParamIfIn(appId, groupNumber, expId, modelParam);
        }
        return false;
    }

    public static boolean checkInNewExpGroupAndSetParamIfIn(String appId, int groupNumber, String expId, ThresholdPredictModelParam modelParam) {
        try {
            if (appExpIdCache.get(appId) == null || !appExpIdCache.get(appId).contains(expId)) {
                return false;
            }
            if ((expIdAndRangeCache.get(expId).getAllEnter() && groupNumber < 0)
                    || (
                    expIdAndRangeCache.get(expId).getRange()[0] <= groupNumber && expIdAndRangeCache.get(expId).getRange()[1] >= groupNumber)
            ) {
                for (Map.Entry<String, Object> entry : expIdAndRangeCache.get(expId).getParam().entrySet()) {
                    modelParam.getExtraParam().put(entry.getKey(), entry.getValue());
                }
                return true;
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }


    public static class ExpConfig {
        private String appType;
        private List<Layer> layers;

        public String getAppType() {
            return appType;
        }

        public void setAppType(String appType) {
            this.appType = appType;
        }

        public List<Layer> getLayers() {
            return layers;
        }

        public void setLayers(List<Layer> layers) {
            this.layers = layers;
        }
    }

    public static class Layer {
        private String layerId;
        private int bucketNum;
        private List<Exp> exps;
        private Map<String, String> groupRule;

        public String getLayerId() {
            return layerId;
        }

        public void setLayerId(String layerId) {
            this.layerId = layerId;
        }

        public int getBucketNum() {
            return bucketNum;
        }

        public void setBucketNum(int bucketNum) {
            this.bucketNum = bucketNum;
        }

        public List<Exp> getExps() {
            return exps;
        }

        public void setExps(List<Exp> exps) {
            this.exps = exps;
        }

        public Map<String, String> getGroupRule() {
            return groupRule;
        }

        public void setGroupRule(Map<String, String> groupRule) {
            this.groupRule = groupRule;
        }
    }

    public static class Exp {
        private String expId;
        private int[] range;

        public Boolean getAllEnter() {
            return allEnter;
        }

        public void setAllEnter(Boolean allEnter) {
            this.allEnter = allEnter;
        }

        private boolean allEnter =false;
        private Map<String,Object> param;

        public String getExpId() {
            return expId;
        }

        public void setExpId(String expId) {
            this.expId = expId;
        }

        public int[] getRange() {
            return range;
        }

        public void setRange(int[] range) {
            this.range = range;
        }

        public Map<String, Object> getParam() {
            return param;
        }

        public void setParam(Map<String, Object> param) {
            this.param = param;
        }
    }

    public static String getFlagId() {
        return flagId;
    }
    @Value("${ad.new.exp.flag.id:647}")
    private void setFlagId(String flagId) {
        this.flagId = flagId;
    }
}
