package com.fs.common.utils;

import com.fs.common.core.domain.SortRule;

import java.util.ArrayList;
import java.util.List;

public class SortUtils {

    /**
     * 解析排序规则
     * @param sortStr   排序字符串  a(desc),b(asc),c(desc)
     * @return list
     */
    public static List<SortRule> parseSort(String sortStr) {
        List<SortRule> rules = new ArrayList<>();
        if (StringUtils.isBlank(sortStr)) {
            return rules;
        }

        String[] sortParts = sortStr.split(",");
        for (String part : sortParts) {
            String[] split = part.trim().split("\\(");
            if (split.length != 2) {
                continue;
            }

            String field = split[0].trim().replace(" ", ""); // 字段名：a, b, c

            String direction = split[1].replace(")", "").trim(); // 方向：desc
            if (!"asc".equalsIgnoreCase(direction) && !"desc".equalsIgnoreCase(direction)) {
                continue;
            }

            rules.add(new SortRule(field, direction));
        }
        return rules;
    }
}
