package com.zhiqiyun.open.mvc.manager.params;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author jtoms
 */
@Data
@Slf4j
public class QueryPageParams {
    private Integer current = 1;
    private Integer pageSize = 10;
    private Map<String, String> sorter;

    public <T> Page<T> getPage() {
        Page<T> page = new Page<>(this.getCurrent(), this.getPageSize());

        if (this.sorter != null && this.sorter.size() > 0) {
            for (String key : this.sorter.keySet()) {
                String directionString = this.sorter.get(key);
                if (StringUtils.equalsIgnoreCase("ascend", directionString)) {
                    page.addOrder(OrderItem.asc(key));
                } else {
                    page.addOrder(OrderItem.desc(key));
                }
            }
        }
        return page;
    }


    public Map<String, Object> getQueryWrapper() {
        Map<String, Object> result = new HashMap<>();

        Class<?> sourceClass = this.getClass();
        //拿到所有的字段,不包括继承的字段
        Field[] sourceFiled = sourceClass.getDeclaredFields();
        for (Field field : sourceFiled) {
            try {
                //设置可访问,不然拿不到private
                field.setAccessible(true);
                result.put(field.getName(), field.get(this));
            } catch (Exception e) {
                log.error("", e);
            }
        }
        return result;
    }
}
