package com.engine.organization.util.page;

import com.engine.organization.annotation.TableTitle;
import lombok.Data;
import lombok.ToString;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

@Data
@ToString
public class PageInfo<T> extends com.github.pagehelper.PageInfo<T> {
    Class<T> clazz;

    public void setColumns(List<Column> columns) {
        this.columns.addAll(columns);
    }

    List<Column> columns = new ArrayList<>();
    List<DataSource> dataSource = new ArrayList<>();

    public PageInfo() {
    }

    public PageInfo(Class<T> clazz) {
        this.clazz = clazz;
        this.columns = buildColumns();
    }

    public PageInfo(List<T> list) {
        super(list);
    }

    public PageInfo(List<T> list, Class<T> clazz) {
        super(list);
        this.clazz = clazz;
        this.columns = buildColumns();
    }


    public List<Column> buildColumns() {
        if (clazz == null) {
            return this.columns;
        }
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            boolean isanno = f.isAnnotationPresent(TableTitle.class);
            if (isanno) {
                TableTitle annotation = f.getAnnotation(TableTitle.class);
                String title = annotation.title();
                String dataIndex = annotation.dataIndex();
                String key = annotation.key();
                boolean display = annotation.display();
                String width = annotation.width();
                boolean sorter = annotation.sorter();
                Column column = Column.builder().sorter(sorter).width(width).title(title).dataIndex(dataIndex).key(key).display(display).build();
                columns.add(column);
            }
        }
        return columns;
    }
}
