package com.mingzuozhibi.modules.core;

import com.mingzuozhibi.commons.base.PageController;
import com.mingzuozhibi.commons.mylog.JmsEnums;
import com.mingzuozhibi.commons.mylog.JmsEnums.Name;
import com.mingzuozhibi.commons.mylog.JmsEnums.Type;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.Predicate;
import java.util.ArrayList;
import java.util.List;

@RestController
public class MessageController extends PageController {

    @Autowired
    private MessageRepository messageRepository;

    @GetMapping(value = "/api/messages/{name}", produces = MEDIA_TYPE)
    public String findAll(
        @PathVariable Name name,
        @RequestParam(required = false) String search,
        @RequestParam(required = false) List<Type> types,
        @PageableDefault(size = 20, sort = "id", direction = Sort.Direction.DESC) Pageable pageable) {

        return pageResult(messageRepository.findAll((Specification<Message>) (root, query, cb) -> {
            ArrayList<Predicate> array = new ArrayList<>();
            array.add(cb.equal(root.get("name"), name));
            if (StringUtils.isNotBlank(search)) {
                array.add(cb.like(root.get("text"), "%" + search + "%"));
            }
            if (types != null && !types.isEmpty() && types.size() < JmsEnums.Type.values().length) {
                array.add(cb.in(root.get("type")).value(types));
            }
            return query.where(array.toArray(new Predicate[0])).getRestriction();
        }, pageable));

    }

}

@@ -391,20 +391,23 @@
 ain.Page
-able
+Request
 ;%0Aimport
@@ -445,16 +445,67 @@
 n.Sort;%0A
+import org.springframework.data.domain.Sort.Order;%0A
 import o
@@ -558,61 +558,8 @@
 on;%0A
-import org.springframework.data.web.PageableDefault;%0A
 impo
@@ -937,25 +937,16 @@
 findAll(
-%0A        
 @PathVar
@@ -962,16 +962,34 @@
 e name,%0A
+                  
         
@@ -1035,16 +1035,34 @@
 search,%0A
+                  
         
@@ -1123,98 +1123,138 @@
     
-@PageableDefault(size = 20, sort = %22id%22, direction = Sort.Direction.DESC) Pageable pageabl
+                  @RequestParam(defaultValue = %221%22) int page,%0A                          @RequestParam(defaultValue = %2220%22) int siz
 e) %7B
@@ -1887,16 +1887,65 @@
  %7D, 
-pageable
+PageRequest.of(page - 1, size, Sort.by(Order.desc(%22id%22)))
 ));%0A

set page base one