package cn.com.qmth.stmms.subjectheader.interceptor;

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

import org.springframework.beans.factory.annotation.Autowired;

import cn.com.qmth.stmms.biz.subjectheader.model.SubjectHeader;
import cn.com.qmth.stmms.biz.subjectheader.service.SubjectHeaderService;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.interceptor.CommonInterceptor;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * SubjectHeader模块操作拦截器
 * 
 * @author XKJ
 * 
 */
public class SubjectHeaderInterceptor extends CommonInterceptor {

    @Autowired
    private SubjectHeaderService subjectHeaderService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        if (uri.endsWith("login")) {
            return true;
        }

        SubjectHeader sh = buildSubjectHeader(RequestUtils.getWebUser(request));
        if (sh != null) {
            return true;
        }
        return sessionExpire(request, response, "/mark-login");
    }

    private SubjectHeader buildSubjectHeader(WebUser wu) {
        SubjectHeader sh = null;
        if (wu != null && wu.isType(UserType.SUBJECTHEADER)) {
            sh = wu.getSubjectHeader();
            if (sh == null) {
                sh = subjectHeaderService.findById(wu.getId());
                if (sh != null) {
                    wu.setDataObject(sh);
                }
            }
        }
        return sh;
    }
}
