package com.engine.organization.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author:dxfeng
 * @createTime: 2022/06/23
 * @version: 1.0
 */
public class PageInfoSortUtil {

    /**
     * 获取排序SQL规则
     *
     * @param sortParams
     * @return
     */
    public static String getSortSql(String sortParams, String defaultOrder) {
        JSONArray jsonArray = JSONObject.parseArray(sortParams);
        if (CollectionUtils.isNotEmpty(jsonArray)) {
            JSONObject jsonObject = (JSONObject) jsonArray.get(0);
            String orderKey = jsonObject.getString("orderkey");
            String sortOrder = jsonObject.getString("sortOrder").replace("end", "");
            return "t." + orderKey + " " + sortOrder;
        }
        return defaultOrder;
    }

    /**
     * 驼峰转下划线
     *
     * @param param
     * @return
     */
    private static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || "".equals(param)) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }
        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }

    /**
     * 下划线转驼峰
     *
     * @param str
     * @return
     */
    public static String underlineToHump(String str) {
        //正则匹配下划线及后一个字符，删除下划线并将匹配的字符转成大写
        Matcher matcher = Pattern.compile("_([a-z])").matcher(str);
        StringBuffer sb = new StringBuffer(str);
        if (matcher.find()) {
            sb = new StringBuffer();
            //将当前匹配的子串替换成指定字符串，并且将替换后的子串及之前到上次匹配的子串之后的字符串添加到StringBuffer对象中
            //正则之前的字符和被替换的字符
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
            //把之后的字符串也添加到StringBuffer对象中
            matcher.appendTail(sb);
        } else {
            //去除除字母之外的前面带的下划线
            return sb.toString().replaceAll("_", "");
        }
        return underlineToHump(sb.toString());
    }
}
