package ctop.bytedance.ad.common.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author jeecg-boot
 * 2019年12月5日19:57:58
 */
public class StringUtils {
    private static final Pattern LINE_PATTERN = Pattern.compile("_(\\w)");
    private static final Pattern HUMP_PATTERN = Pattern.compile("[A-Z]");
    public static final String COMMA = ",";

    /**
     * 获取请求地址中的某个参数
     * @param url
     * @param name
     * @return
     */
    public static String getParamFromUrl(String url, String name) {
        return urlSplit(url).get(name);
    }

    /**
     * 去掉url中的路径，留下请求参数部分
     * @param url url地址
     * @return url请求参数部分
     */
    private static String truncateUrlPage(String url) {
        String strAllParam = null;
        String[] arrSplit = null;
        url = url.trim().toLowerCase();
        arrSplit = url.split("[?]");
        if (url.length() > 1) {
            if (arrSplit.length > 1) {
                for (int i = 1; i < arrSplit.length; i++) {
                    strAllParam = arrSplit[i];
                }
            }
        }
        return strAllParam;
    }

    /**
     * 将参数存入map集合
     * @param url  url地址
     * @return url请求参数部分存入map集合
     */
    public static Map<String, String> urlSplit(String url) {
        Map<String, String> mapRequest = new HashMap<String, String>();
        String[] arrSplit = null;
        String strUrlParam = truncateUrlPage(url);
        if (strUrlParam == null) {
            return mapRequest;
        }
        arrSplit = strUrlParam.split("[&]");
        for (String strSplit : arrSplit) {
            String[] arrSplitEqual = null;
            arrSplitEqual = strSplit.split("[=]");
            //解析出键值
            if (arrSplitEqual.length > 1) {
                //正确解析
                mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
            } else {
                if (arrSplitEqual[0] != "") {
                    //只有参数没有值，不加入
                    mapRequest.put(arrSplitEqual[0], "");
                }
            }
        }
        return mapRequest;
    }


    public static ArrayList<String> stringCutFromBrace(String origin) {
        String pattern = "(?<=\\{)(.+?)(?=\\})";
        Pattern p = Pattern.compile(pattern);
        ArrayList<String> list = new ArrayList<>();
        Matcher m = p.matcher(origin);
        while (m.find()) {
            list.add(m.group());
        }
        return list;
    }
    /**
     * 将下划线风格转换为驼峰风格
     * @param inputString
     * @return
     */
    public static String underlineToCamehunp(String inputString){
        StringBuilder sb = new StringBuilder();
        boolean nextUppercase = false;
        for (int i = 0; i < inputString.length(); i++) {
            char c = inputString.charAt(i);
            if (c == '_') {
                if (sb.length()>0) {
                    nextUppercase = true;
                }
            }else {
                if (nextUppercase) {
                    sb.append(Character.toUpperCase(c));
                    nextUppercase = false;
                }else {
                    sb.append(Character.toLowerCase(c));
                }
            }
        }
        return sb.toString();
    }

    /** 下划线转驼峰 */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = LINE_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    /** 驼峰转下划线(简单写法，效率低于{@link #humpToLine2(String)}) */
    public static String humpToLine(String str) {
        return str.replaceAll("[A-Z]", "_$0").toLowerCase();
    }

    /** 驼峰转下划线,效率比上面高 */
    public static String humpToLine2(String str) {
        Matcher matcher = HUMP_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    //中文转Unicode
    public static String cnToUnicode(String cn) {
        char[] chars = cn.toCharArray();
        String returnStr = "";
        for (int i = 0; i < chars.length; i++) {
            returnStr += "\\u" + Integer.toString(chars[i], 16);
        }
        return returnStr;
    }

    //Unicode转中文方法
    public static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 使用正则表达式提取中括号中的内容
     * @param msg
     * @return
     */
    public static List<String> extractMessageByRegular(String msg){

        List<String> list=new ArrayList<String>();
        Pattern p = Pattern.compile("\\{([^}]*)\\}");
        Matcher m = p.matcher(msg);
        while(m.find()){
            list.add(m.group().substring(1, m.group().length()-1));
        }
        return list;
    }

    /**
     *
     * 获取目标转化出价
     *
     * @param type 智能投放计划创建出价方式
     *             固定出价 FIX ;
     *             随机出价 RAND;
     *             阶梯出价 STEP
     * @param maxBid 转化出价最大值
     * @param minBid 转化出价最小值
     * @param stepBid 浮动间隔
     * @param lastBid 上次创建计划出价
     * @author zianY
     */
    public static BigDecimal  getRandomAdCpaBid(String type,BigDecimal maxBid,BigDecimal minBid,BigDecimal stepBid,BigDecimal lastBid,BigDecimal strategyCpaBid){
        BigDecimal reuslt = null;
        //固定出价
        if("FIX".equalsIgnoreCase(type)){
            reuslt = strategyCpaBid.setScale(2,RoundingMode.DOWN);
        }
        //随机出价
        if("RAND".equalsIgnoreCase(type)){
            double max = maxBid.doubleValue();
            double min = minBid.doubleValue();
            double randResult = min + (Math.random() * (max - min));
            randResult = (double) Math.round(randResult * 100) / 100;
            reuslt = new BigDecimal(randResult).setScale(2, RoundingMode.DOWN);
        }
        //当出价为阶梯出价时，创建的出价为 最低出价 + N * 浮动间隔 < 最高出价
        if ("STEP".equalsIgnoreCase(type)){
            double max = maxBid.doubleValue();
            double min = minBid.doubleValue();
            double last = lastBid.doubleValue();
            double step = stepBid.doubleValue();
            if(last>max||last<min){
                //如果不在出价范围内，设定为最低出价
                reuslt = minBid.setScale(2, RoundingMode.DOWN);
            }else if((last-min)%step!=0){
                //表示上次是随机出价转变为阶梯出价
                reuslt = minBid.setScale(2, RoundingMode.DOWN);
            }else if(last+step>max){
                reuslt = minBid.setScale(2, RoundingMode.DOWN);
            }else{
                reuslt = lastBid.add(stepBid).setScale(2, RoundingMode.DOWN);
            }
        }
        return reuslt;
    }

    public static int lengthAsSlogan(String a)  {
        char[] c = a.toCharArray();
        int count=0;
        for (char d : c) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(d);
            if (ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                    || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_FORMS
                    || ub == Character.UnicodeBlock.VERTICAL_FORMS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_C
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_D
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS_SUPPLEMENT) {
                count++;
            }

        }
        BigDecimal strNum = new BigDecimal(count);
        BigDecimal strlen = new BigDecimal(a.length());
        BigDecimal res = strlen.subtract(strNum).divide(new BigDecimal(2),0, BigDecimal.ROUND_UP).add(strNum);
        return res.intValue();
    }

    public static String replaceCreativeWordPackageText(String str){
        int left = str.indexOf("{");
        int right = str.indexOf("}");
        if(left < 0){
            return null;
        }
        String newStr = str.substring(left+1, right);
        return newStr;
    }
}
