package com.tykj.model.utils;

import com.tykj.model.entity.vo.QueryCondition;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * @author C
 */
@Slf4j
public class HqlUtil {

    public static String createQuery(String tableName, List<String> columnNames, List<QueryCondition> conditions, String groupByColumn) {
        StringBuilder result = new StringBuilder("select ");
        if (Objects.isNull(columnNames) || columnNames.isEmpty()) {
            result.append("entity ");
        } else {
            for (String columnName : columnNames) {
                result.append("entity.").append(columnName).append(",");
            }
            result.delete(result.lastIndexOf(","),result.length() );
        }
        result.append(" from ").append(tableName).append(" entity ");
        if (Objects.nonNull(conditions) && !conditions.isEmpty()) {
            result.append(" where ");
            for (QueryCondition condition : conditions) {
                result.append("entity.")
                        .append(condition.getName())
                        .append(" " + condition.getType() + " ")
                        .append("'")
                        .append(condition.getValue())
                        .append("'");
                if (condition.getConnectionType()!=null){
                    result.append(condition.getConnectionType().getType());
                }
            }
            if (result.lastIndexOf(" and ") > -1) {
                result.delete(result.lastIndexOf(" and "), result.length());
            }
            if (result.lastIndexOf(" or ") > -1) {
                result.delete(result.lastIndexOf(" or "), result.length());
            }
        }
        if (StringUtils.isNotEmpty(groupByColumn)) {
            result.append(" group by entity." + groupByColumn);
        }
        System.out.println(result.toString());
        return result.toString();
    }

}
