package cn.axzo.workflow.core.common.utils;

import cn.axzo.workflow.common.model.request.BpmPageParam;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.sf.jsqlparser.expression.Alias;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.schema.Table;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

public class BpmnMyBatisUtils {
    private static final String MYSQL_ESCAPE_CHARACTER = "`";

    public BpmnMyBatisUtils() {
    }

    public static <T> Page<T> buildPage(BpmPageParam pageParam) {
        return buildPage(pageParam, (Collection)null);
    }

    public static <T> Page<T> buildPage(BpmPageParam pageParam, Collection<BpmnSortingField> sortingFields) {
        Page<T> page = new Page((long)pageParam.getPageNo(), (long)pageParam.getPageSize());
        if (!CollectionUtil.isEmpty(sortingFields)) {
            page.addOrder((List)sortingFields.stream().map((sortingField) -> {
                return "asc".equals(sortingField.getOrder()) ? OrderItem.asc(sortingField.getField()) : OrderItem.desc(sortingField.getField());
            }).collect(Collectors.toList()));
        }

        return page;
    }

    public static void addInterceptor(MybatisPlusInterceptor interceptor, InnerInterceptor inner, int index) {
        List<InnerInterceptor> inners = new ArrayList(interceptor.getInterceptors());
        inners.add(index, inner);
        interceptor.setInterceptors(inners);
    }

    public static String getTableName(Table table) {
        String tableName = table.getName();
        if (tableName.startsWith("`") && tableName.endsWith("`")) {
            tableName = tableName.substring(1, tableName.length() - 1);
        }

        return tableName;
    }

    public static Column buildColumn(String tableName, Alias tableAlias, String column) {
        return new Column(tableAlias != null ? tableAlias.getName() + "." + column : column);
    }
}
