package com.zhiqiyun.open.manager.params;

import com.zhiqiyun.open.mybatis.paginator.domain.Order;
import com.zhiqiyun.open.mybatis.paginator.domain.PageBounds;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
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 PageBounds getPageBounds() {
        PageBounds bounds = new PageBounds(this.getCurrent(), this.getPageSize());

        List<Order> orders = new ArrayList<>();
        if (this.sorter != null && this.sorter.size() > 0) {
            for (String key : this.sorter.keySet()) {
                String directionString = this.sorter.get(key);
                directionString = directionString.replace("end", "");
                orders.add(Order.create(key, Order.Direction.valueOf(directionString.toUpperCase())));
            }
        }

        bounds.setOrders(orders);
        return bounds;
    }


    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;
    }
}
