package com.lightinit.hsdatashow.handler;
import com.lightinit.hsdatashow.common.WebUtilsPro;
import com.lightinit.hsdatashow.entity.Admin;
import com.lightinit.hsdatashow.model.ResultState;
import com.lightinit.hsdatashow.model.ResultStateCode;
import com.lightinit.hsdatashow.service.IAdminService;
import com.lightinit.hsdatashow.service.IRoleService;
import com.lightinit.hsdatashow.service.IShiroPermissionsService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

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

/**
 * Created by Mr.Yao on 2016/1/25.
 */
public class AuthInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IAdminService adminService;
    @Autowired
    private IShiroPermissionsService shiroPermissionsService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String relativeUrl = request.getRequestURI();
        Subject subject = SecurityUtils.getSubject();
        boolean isPermitted = subject.isPermitted(relativeUrl);
        if (!isPermitted){
            logger.debug("无权访问");
            if (WebUtilsPro.isAjaxRequest(request)){
                ResultState resultState = new ResultState();
                resultState.setStateCode(ResultStateCode.NO_PERMISSION);
                resultState.setMsg("无权访问");
                WebUtilsPro.writeJson(response, resultState);
            }else {
                response.sendRedirect("/403.html");
            }
        }
        return isPermitted;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (null == modelAndView)
            return;
        Subject user = SecurityUtils.getSubject();
        if (null == user)
            return;
        Object objectUserName = user.getPrincipal();
        String UserShowName="游客";
        if (null != objectUserName) {
            String currentUsername = (String) user.getPrincipal();
            if(StringUtils.isEmpty(currentUsername)){
                return;
            }else {
                Admin mUser = adminService.SelectOne(currentUsername);
                if(mUser!=null){
                    UserShowName=mUser.getShowname();
                }
            }
        }
        modelAndView.addObject("showname", UserShowName);
    }
}
