package com.xmomen.module.core.web;

import com.xmomen.framework.mybatis.page.Page;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;


@Order(1)
@ControllerAdvice
public class JSONResponseBodyAdvice implements ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        // 判断返回类型是否为Page类型
        return returnType.getMethod().getReturnType().isAssignableFrom(Page.class);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        // 判断返回类型是否为Page类型
        if(body instanceof Page){
            Page page = (Page) body;
            Map map = new HashMap();
            // 将Page对象中的分页信息和数据放入map中
            map.put("pageInfo", page.getPageInfo());
            map.put("data", page.getResult());
            return map;
        }
        return body;
    }
}
