package com.nbclass.system.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nbclass.system.model.User;
import com.nbclass.util.CoreConst;

/**
 * 
 * @author Leon
 * @datetime 2019年4月1日 下午3:22:58
 */
public abstract class BaseController {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	private static ThreadLocal<Map<String,Object>> outPutMsg = new ThreadLocal<Map<String,Object>>();

	/**
	 * 获取request
	 * @return  HttpServletRequest
	 */
	protected HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
	}

	/**
	 * 获取Response
	 * @return HttpServletResponse
	 */
	protected HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
	}
	
	/**
	 * 获取session
	 * @return  HttpSession
	 */
	protected HttpSession getSession() {
		return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
	}
	
	protected ServletContext getServletContext() {
		return ContextLoader.getCurrentWebApplicationContext().getServletContext();
	}

	public void outPrint1() {
		outPrint1(null);
    }
	
	public void outPrint1(Object result) {
      outPrint1(result, true);
    }
	
	/**
	 * 输出，同时清空outPutMsg
	 * @param result
	 * @param respCode -- 是否返回响应状态吗，false：将直接输出result
	 */
	public void outPrint1(Object result, boolean respCode) {
        try {
        	HttpServletResponse response = getResponse();
        	response.setCharacterEncoding("utf-8");
        	response.setContentType("application/json");
        	
            PrintWriter out = response.getWriter();
        	if(respCode){
        		JSONObject obj = new JSONObject();
        		if(result == null){
            		// no msg
            	}else if(result instanceof String){
            		obj.put(CoreConst.MSG, result);
            	}else{
            		obj = (JSONObject) JSONObject.toJSON(result);
            	}
        		obj.put(CoreConst.STATUS, CoreConst.STATUS_SUCCESS);
        		out.print(obj.toString());
        	}else{
        		out.print(result.toString());
        	}
            getOutputMsg().clear();
        } catch (IOException e) {
        	logger.error("输出异常", e);
        }
    }
	
	/**
	 * 输出失败信息，同时清空outPutMsg
	 * @param result  void
	 */
	public void outPrintFail1(Object result) {
        try {
        	HttpServletResponse response = getResponse();
        	response.setCharacterEncoding("utf-8");
        	response.setContentType("application/json");
        	
        	JSONObject obj = new JSONObject();
        	if(result == null){
        		// no msg
        	}else if(result instanceof String){
        		obj.put(CoreConst.MSG, result);
        	}else{
        		obj = (JSONObject) JSONObject.toJSON(result);
        	}
        	obj.put(CoreConst.STATUS, CoreConst.STATUS_ERROR);
            PrintWriter out = response.getWriter();
            out.print(obj.toString());
            getOutputMsg().clear();
        } catch (IOException e) {
        	logger.error("输出异常", e);
        }
    }
	
	/**
	 * 线程绑定，其内容会在outPrint方法调用后清空
	 * @return  Map<String,Object>
	 */
	public Map<String,Object> getOutputMsg() {
		Map<String,Object> output = outPutMsg.get();
		if(output==null){
			output = new HashMap<String, Object>();
			outPutMsg.set(output);
		}
		return output;
	}

	public User getLoginUser(){
		User user = (User) SecurityUtils.getSubject().getPrincipal();
		return user;
	}

	/**
	 *
	 * @return
	 */
	public int getLoginUserId(){
		int userid = -1;
		User user = getLoginUser();
		if(user!=null && user.getId()!=null)userid=user.getId();
		return userid;
	}

	/**
	 * 对应企业微信的userId
	 * @return
	 */
	public String getLoginUserIdStr(){
		String userid = null;
		User user = getLoginUser();
		if(user!=null)userid=user.getUserId();
		return userid;
	}

	/**
	 * 是否是管理员角色
	 * @return
	 */
	public boolean isAdminRole(){
		boolean isAdmin = SecurityUtils.getSubject().hasRole("1"); //是否是管理员,admin的roleid为1
		return isAdmin;
	}
	
	/**
	 * 实体类转JSON
	 * 为什么这么转？
	 * 因为fastjson直接转会把_name转成name
	 * @param value
	 * @return
	 */
	public JSONObject toJSON(Object value){
		if(value == null)return null;
		JSONObject returnObj = new JSONObject();
		ObjectMapper mapper = new ObjectMapper();
    	try {
			String json = mapper.writeValueAsString(value);
			returnObj = JSONObject.parseObject(json);
		} catch(Exception e) {
			e.printStackTrace();
		}
    	return returnObj;
	}
	
	public static void main(String[] args) {
		Object result = null;
		result = "";
		JSONObject obj = (JSONObject) JSONObject.toJSON(result);
		obj.put(CoreConst.STATUS, CoreConst.STATUS_SUCCESS);
		System.out.println(obj);
	}
	
}
