package com.tzld.piaoquan.ad.engine.commons.util;

import com.tzld.piaoquan.ad.engine.commons.score.ScoreParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;

@Slf4j
public class RootSessionIdTailUtil {
    public static final int rankTailN = 6;
    public static final int reRankTailN = 7;
    public static final long allApp = 999;

    // appType: 999 表示全量
    public static List<RootSessionIdExpConfig> getRootSessionIdTailConfig(ScoreParam scoreParam, int nFromEnd, List<RootSessionIdExpConfig> rootSessionIdConfig) {
        try {
            List<RootSessionIdExpConfig> hitConfigs = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(rootSessionIdConfig)) {
                Long appType = scoreParam.getAppType();
                String tail = getNthCharFromEnd(scoreParam.getRootSessionId(), nFromEnd);
                for (RootSessionIdExpConfig item : rootSessionIdConfig) {
                    Set<Long> appTypeSet = item.getAppType();
                    if (null == appTypeSet) {
                        continue;
                    }

                    // match all
                    if (appTypeSet.contains(allApp)) {
                        hitConfigs.add(item);
                        continue;
                    }
                    // match app & tail
                    Set<String> tailSet = item.getTail();
                    if (null != appType && null != tail && null != tailSet) {
                        if (appTypeSet.contains(appType) && tailSet.contains(tail)) {
                            hitConfigs.add(item);
                            continue;
                        }
                    }
                }
            }
            return hitConfigs;
        } catch (Exception e) {
            log.error("rootSessionId尾号配置异常", e);
        }
        return Collections.emptyList();
    }

    public static String getNthCharFromEnd(String rootSessionId, int nFromEnd) {
        if (StringUtils.isBlank(rootSessionId) || nFromEnd < 1) {
            return null;
        }

        // 计算开始位置
        int position = rootSessionId.length() - nFromEnd;

        // 检查位置是否有效
        if (position < 0) {
            return null;
        }
        return String.valueOf(rootSessionId.charAt(position));
    }
}
