package com.centreproject.common.utils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.centreproject.common.core.page.PageDomain;
import com.centreproject.common.core.page.TableSupport;
import com.centreproject.common.utils.sql.SqlUtil;

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

/**
 * @author zhonglei.xu
 */
public class PageUtils {
    /**
     * 设置请求分页数据（适配MyBatis-Plus）
     */
    public static <T> Page<T> startPage() {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        return new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());
    }

    /**
     * 构建排序条件（安全方式）
     */
    public static <T> void buildOrderBy(QueryWrapper<T> wrapper) {
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            // 安全解析排序字段
            String[] orders = orderBy.split("\\s+");
            if (orders.length == 1) {
                wrapper.orderByAsc(orders[0]);
            } else if (orders.length == 2 && "desc".equalsIgnoreCase(orders[1])) {
                wrapper.orderByDesc(orders[0]);
            } else if (orders.length == 2 && "asc".equalsIgnoreCase(orders[1])) {
                wrapper.orderByAsc(orders[0]);
            }
        }
    }

    /**
     * 构建分页和排序条件
     */
    public static <T> Page<T> startOrderPage() {
        Page<T> page = startPage();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotEmpty(pageDomain.getOrderBy())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            page.setOrders(parseOrderItems(orderBy));
        }
        return page;
    }

    /**
     * 解析排序条件
     */
    private static List<OrderItem> parseOrderItems(String orderBy) {
        List<OrderItem> orderItems = new ArrayList<>();
        String[] clauses = orderBy.split(",");
        for (String clause : clauses) {
            String[] parts = clause.trim().split("\\s+");
            if (parts.length == 1) {
                orderItems.add(OrderItem.asc(parts[0]));
            } else if (parts.length == 2) {
                if ("desc".equalsIgnoreCase(parts[1])) {
                    orderItems.add(OrderItem.desc(parts[0]));
                } else {
                    orderItems.add(OrderItem.asc(parts[0]));
                }
            }
        }
        return orderItems;
    }
}