package com.yvan.springmvc;

import com.baomidou.mybatisplus.plugins.pagination.Pagination;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.Maps;

import java.io.IOException;
import java.util.Map;

public class PageModelSerializer extends JsonSerializer<Pagination> {
    public static final SimpleModule MODEL;

    static {
        MODEL = new SimpleModule();
        MODEL.addSerializer(Pagination.class, new PageModelSerializer());
    }

    @Override
    public void serialize(Pagination pagionation,
                          JsonGenerator gen,
                          SerializerProvider serializers) throws IOException, JsonProcessingException {

        Map<String, Object> map = Maps.newLinkedHashMap();
        map.put("pageSize", pagionation.getSize());
        map.put("pageNo", pagionation.getCurrent());
        map.put("next", pagionation.hasNext() ? pagionation.getCurrent() + 1 : pagionation.getCurrent());
        map.put("last", pagionation.getPages());
        map.put("first", 1);
        map.put("prev", pagionation.hasPrevious() ? pagionation.getCurrent() - 1 : pagionation.getCurrent());
        map.put("count", pagionation.getTotal());
        gen.writeObject(map);

        //gen.writeNumberField("pageSize", pagionation.getSize());
        //gen.writeNumberField("pageNo", pagionation.getCurrent());
        //gen.writeNumberField("next", pagionation.hasNext() ? pagionation.getCurrent() + 1 : pagionation.getCurrent());
        //gen.writeNumberField("last", pagionation.getPages());
        //gen.writeNumberField("first", 1);
        //gen.writeNumberField("prev", pagionation.hasPrevious() ? pagionation.getCurrent() - 1 : pagionation.getCurrent());
        //gen.writeNumberField("count", pagionation.getTotal());
    }
}
