package com.ssj.framework.core.common.controller;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.Direction;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * 
 * 类名称：BaseController<br>
 * 类描述： Controller基类<br>
 * @version v1.0
 *
 */
public abstract class BaseController {

    protected Logger logger = LoggerFactory.getLogger("aijia");

    @Autowired
    protected HttpServletRequest request;

    @Autowired
    protected HttpServletResponse response;



    /**
     * 初始化分页查询参数Page
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    protected Pageable initPage(Integer pageNo, Integer pageSize) {
        // @RequestParam在处理不存在的参数时，赋值为null，基本类型无法为null，改为包装类型
        if (pageNo == null) {
            pageNo = 0;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        pageNo = pageNo == 0 ? 0 : pageNo - 1;
        pageSize = pageSize == 0 ? 10 : pageSize;
        Pageable page = new PageRequest(pageNo, pageSize);
        return page;
    }

    /**
     * 初始化分页查询参数Page
     *
     * @param pageNo
     * @param pageSize
     * @param direction
     * @param properties
     * @return
     */
    protected Pageable initPage(Integer pageNo, Integer pageSize, Direction direction, String... properties) {
        if (pageNo == null) {
            pageNo = 0;
        }
        if (pageSize == null) {
            pageSize = 0;
        }
        pageNo = pageNo == 0 ? 0 : pageNo - 1;
        pageSize = pageSize == 0 ? 10 : pageSize;
        Pageable page = new PageRequest(pageNo, pageSize, direction, properties);
        return page;
    }

    protected Map<String, Object> getPageResultMap(Page page) {
        Map<String, Object> resultMap = new HashMap<>();
        if (page != null) {
            resultMap.put("pages", page.getTotalPages());
            resultMap.put("pageNo", page.getNumber() + 1);
            resultMap.put("pageSize", page.getSize());
            resultMap.put("list", page.getContent());
        }
        return resultMap;
    }

}
