package ink.wgink.common.base;

import ink.wgink.util.map.HashMapUtil;
import ink.wgink.util.request.RequestUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

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

/**
 * @ClassName: AbstractController
 * @Description: baseinfo controller
 * @Author: wenc
 * @Date: 2018/9/27 下午3:47
 * @Version: 1.0
 **/
@Controller
public class DefaultBaseController {

    protected static final Logger LOG = LoggerFactory.getLogger(DefaultBaseController.class);
    @Autowired
    protected HttpSession httpSession;
    @Autowired
    protected HttpServletRequest httpServletRequest;
    @Autowired
    protected HttpServletResponse httpServletResponse;

    /**
     * 获取请求参数
     *
     * @return
     */
    protected Map<String, Object> requestParams() {
        Map<String, Object> params = requestParams(RequestUtil.getRequest());
        String keywords = "keywords";
        if (params.get(keywords) != null && !StringUtils.isBlank(params.get(keywords).toString())) {
            try {
                params.replace(keywords, URLDecoder.decode(params.get(keywords).toString().trim(), "UTF-8"));
            } catch (Exception e) {
                LOG.error(e.getMessage(), e);
            }
        }
        String showLevel = "showLevel";
        if (params.get(showLevel) == null || StringUtils.isEmpty(params.get(showLevel).toString())) {
            params.put(showLevel, "0");
        }
        return params;
    }

    /**
     * 获取请求参数
     *
     * @return
     */
    protected Map<String, Object> requestParams(HttpServletRequest request) {
        Map<String, Object> params = HashMapUtil.requestParamsToMap(request);
        params.put("requestUri", request.getRequestURI());
        params.put("requestHost", request.getRemoteHost());
        params.put("requestPort", request.getLocalPort());
        return params;
    }

    /**
     * 获取参数
     *
     * @return
     */
    protected Map<String, Object> getParams() {
        return new HashMap<>(0);
    }

    /**
     * 获取session
     *
     * @return
     */
    protected HttpSession getHttpSession() {
        return httpSession;
    }
}
