package com.how2java.springboot.web;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.how2java.springboot.dao.CategoryDAO;
import com.how2java.springboot.pojo.Category;
@Controller
public class CategoryController {
@Autowired CategoryDAO categoryDAO;
@GetMapping("/listCategory")
public String listCategory(Model m,@RequestParam(value = "start", defaultValue = "0") intstart,@RequestParam(value = "size", defaultValue = "5") int size){
String query = "商品";
SearchQuery searchQuery=getEntitySearchQuery(start,size,query);
Page<Category> page = categoryDAO.search(searchQuery);
m.addAttribute("page", page);
return "listCategory";
}
private SearchQuery getEntitySearchQuery(int start, int size, String searchContent) {
FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery()
.add(QueryBuilders.matchAllQuery(),
ScoreFunctionBuilders.weightFactorFunction(100))
.scoreMode("sum")
.setMinScore(10);
Sort sort = new Sort(Sort.Direction.DESC,"id");
Pageable pageable = new PageRequest(start, size,sort);
return new NativeSearchQueryBuilder()
.withPageable(pageable)
.withQuery(functionScoreQueryBuilder).build();
}
@RequestMapping("/addCategory")
public String addCategory(Category c) throws Exception {
int id = currentTime();
c.setId(id);
categoryDAO.save(c);
return "redirect:listCategory";
}
private int currentTime() {
SimpleDateFormat sdf = new SimpleDateFormat("MMddHHmmss");
String time= sdf.format(new Date());
return Integer.parseInt(time);
}
@RequestMapping("/deleteCategory")
public String deleteCategory(Category c) throws Exception {
categoryDAO.delete(c);
return "redirect:listCategory";
}
@RequestMapping("/updateCategory")
public String updateCategory(Category c) throws Exception {
categoryDAO.save(c);
return "redirect:listCategory";
}
@RequestMapping("/editCategory")
public String ediitCategory(int id,Model m) throws Exception {
Category c= categoryDAO.findOne(id);
m.addAttribute("c", c);
return "editCategory";
}
}