package com.lightinit.hsdatashow.controller;

import com.lightinit.hsdatashow.common.WebUtilsPro;
import com.lightinit.hsdatashow.json.pojo.ErrorEntity;
import com.lightinit.hsdatashow.json.pojo.LoginResult;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * Created by Mr.Yao on 2017/4/18.
 */
public abstract class BaseController
{
    /***
     * 登录异常返回信息
     * @param request 输入
     * @param response 输出
     * @return AJAX返回JSON数据格式 浏览器访问返回HTML格式
     */
    @ExceptionHandler({UnauthenticatedException.class,AuthenticationException.class})
    public String authenticationException(HttpServletRequest request, HttpServletResponse response){
        if(WebUtilsPro.isAjaxRequest(request)){
            LoginResult loginResult=new LoginResult();
            loginResult.setStatus(2008);
            loginResult.setMessage(ErrorEntity.getMsg(loginResult.getStatus()));
            writeJson(loginResult,response);
            return null;
        }else{
            return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/passport/login.htm";
        }
    }

    /***
     * 授权异常返回信息
     * @param request 输入
     * @param response 输出
     * @return AJAX返回JSON数据格式 浏览器访问返回HTML格式
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        if (WebUtilsPro.isAjaxRequest(request)) {
            LoginResult loginResult=new LoginResult();
            loginResult.setStatus(2009);
            loginResult.setMessage(ErrorEntity.getMsg(loginResult.getStatus()));
            writeJson(loginResult,response);
            return null;
        } else {
            return InternalResourceViewResolver.REDIRECT_URL_PREFIX+"/403.html";
        }
    }
    private void writeJson(LoginResult result,HttpServletResponse response){
        PrintWriter out=null;
        try{
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();
            ObjectMapper objectMapper = new ObjectMapper();
            out.write(objectMapper.writeValueAsString(result));
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(out!=null)
                out.close();
        }
    }
}
