package com.cm.common.base;

import com.cm.common.utils.HashMapUtil;
import com.cm.common.utils.RequestUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
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
 **/
@Component
public abstract class AbstractController {

    protected static final Logger LOG = LoggerFactory.getLogger(AbstractController.class);

    @Autowired
    private HttpSession httpSession;

    /**
     * 获取请求参数
     *
     * @return
     */
    protected Map<String, Object> requestParams() {
        Map<String, Object> params = requestParams(RequestUtil.getRequest());
        String keywords = "keywords";
        if (!StringUtils.isEmpty(params.get(keywords))) {
            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 (StringUtils.isEmpty(params.get(showLevel))) {
            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;
    }
}
