package com.qmth.qrzk.web.controller;

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

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

import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.qmth.qrzk.repository.constants.WebConstants;
import com.qmth.qrzk.repository.user.model.Role;
import com.qmth.qrzk.repository.user.model.User;

/**
 * 提供ajax-->controller响应支持类
 * @author 钟辉
 *
 */
public class BaseAjaxController extends MultiActionController{

	public void outJsonString(HttpServletResponse response,String json) {  
        response.setContentType("text/javascript;charset=UTF-8");
        response.setHeader("Cache-Control","no-store, max-age=0, no-cache, must-revalidate");    
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache"); 
        try {  
            PrintWriter out = response.getWriter();  
            out.write(json);
            out.close();
        } catch (IOException e) {  
            e.printStackTrace();  
        }
    }
	
	/**
	 * 获取当前session里面的个人用户信息
	 * @param session
	 * @return
	 */
	protected User getCurUser(HttpSession session) {
		return (User) session.getAttribute(WebConstants.WEB_SESSION_USER);
	}
	
	/**
	 * 获取当前session里面的个人选择的角色信息
	 * @param session
	 * @return
	 */
	protected Role getCurRole(HttpSession session) {
		return (Role) session.getAttribute(WebConstants.WEB_SESSION_ROLE);
	}
	
	protected Map<String,Object> successResult(String msg) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("flag", "success");
		map.put("result", true);
		map.put("msg", (msg == null)?"操作成功":msg);
		return map;
	}
	
	protected Map<String,Object> failedResult(String msg) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("flag", "failed");
		map.put("result", false);
		map.put("msg", (msg == null)?"操作失败":msg);
		return map;
	}
	
	protected Map<String,Object> failedResult(Throwable exp) {
		Map<String,Object> map = new HashMap<String, Object>();
		map.put("flag", "failed");
		map.put("result", false);
		map.put("msg", (exp == null)?"操作失败":exp.getMessage());
		return map;
	}
}
