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

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
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 MarkInterceptor extends CommonInterceptor {

    @Autowired
    private MarkerService markerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String uri = RequestUtils.getURI(request);
        Marker marker = buildMarker(RequestUtils.getWebUser(request));
        if (marker != null) {
            if (uri.endsWith("mark/reset") || uri.endsWith("mark/subject-select")) {
                return true;
            } else if (marker.getLastLoginTime() == null) {
                // 首次登录，强制重置密码及姓名
                return redirect(request, response, "/mark/reset");
            } else if (StringUtils.isBlank(marker.getSubjectCode())) {
                // 通用帐号未选择科目，首先选择强制选择评卷科目
                return redirect(request, response, "/mark/subject-select");
            }
            return true;
        }
        return sessionExpire(request, response, "/mark-login");
    }

    private Marker buildMarker(WebUser wu) {
        Marker marker = null;
        if (wu != null && wu.isType(UserType.MARKER)) {
            marker = wu.getMarker();
            if (marker == null) {
                marker = markerService.findById(wu.getId());
                if (marker != null) {
                    wu.setDataObject(marker);
                    wu.setName(marker.getName());
                }
            }
        }
        return marker;
    }
}
