package cn.iocoder.yudao.framework.common.base;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.ip.IPHelper;
import cn.iocoder.yudao.framework.common.util.ip.IPSearcher;
import org.lionsoul.ip2region.DataBlock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * Controller公共组件
 * @author douya
 * @email douya@gmail.com
 * @date 2017-03-23 15:22:06
 */
public abstract class AbstractController implements Serializable {
	private static final long serialVersionUID = -1206237575319606156L;

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	/**
	 * 通过response输出字符串(响应请求)
	 *
	 * @param encoding
	 * @param out
	 * @param response
	 */
	public void responseWrite(String encoding, String out, HttpServletResponse response) {
		PrintWriter pw = null;

		try {
			response.setCharacterEncoding(encoding);
			pw = response.getWriter();
			pw.write(out);
			response.flushBuffer();
		}
		catch (IOException e) {
			logger.error("响应异常:", e);
		}
		finally {
			if (null != pw) { pw.close(); }
		}
	}

	/**
	 * 通过response输出字符串(响应请求), 编码默认是UTF-8
	 *
	 * @param out
	 * @param response
	 */
	public void responseWrite(String out, HttpServletResponse response) {
		responseWrite(CharsetUtil.UTF_8, out, response);
	}


	/**
	 * @param request
	 * @return
	 * @throws
	 * @method parametersMap
	 * @description [方法描述]
	 * @author [zhuyongjie]
	 * @version 1.0
	 * @paras
	 * @date 2017/10/25 18:24
	 */
	public Map<String, String> parametersMap(HttpServletRequest request) {
		Map<String, String> map = new HashMap<>();
		Enumeration enums = request.getParameterNames();
		while (enums.hasMoreElements()) {
			String paramName = (String) enums.nextElement();
			String paramValue = request.getParameter(paramName);
			if (StrUtil.isNotBlank(paramValue)) {
				map.put(paramName, paramValue);
			}
		}
		return map;
	}

	/***
	 * 获取客户端IP
	 * @param request
	 * @return
	 */
	public String getIpAddr(HttpServletRequest request) {
		return IPHelper.getIpAddr(request);
	}

	/***
	 * 获取客户端IP区域
	 * @param request
	 * @return
	 */
	public DataBlock getIpRegin(HttpServletRequest request) {
		return IPSearcher.ipRegin(getIpAddr(request));
	}

	/**
	 * 取得HttpServletRequest对象
	 * @return HttpServletRequest对象
	 */
	public HttpServletRequest getRequest() {
		return request;
	}

	/**
	 * 取得Response对象
	 * @return
	 */
	public HttpServletResponse getResponse() {
		return response;
	}

	protected Logger logger = LoggerFactory.getLogger(getClass());
}
