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

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

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.biz.user.service.UserService;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.interceptor.SessionInterceptor;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * Mark模块操作拦截器
 *
 * @author XKJ
 */
public class MarkInterceptor extends SessionInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private MarkerService markerService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        WebUser wu = buildUser(request);
        if (wu != null) {
            if (wu.getUser().getLastLoginTime() == null && request.getServletPath().startsWith("/mark/reset")) {
                // 首次登录，强制重置密码及姓名
                return true;
            } else if ((wu.getMarkerId() == null ||wu.getMarker() == null)&& !request.getServletPath().startsWith("/mark/subject")) {
                // 通用帐号未选择科目，首先选择强制选择评卷科目
                return redirect(request, response, "/mark/subject-select");
            } else if (request.getServletPath().startsWith("/mark/logout")) {
                return true;
            } else if (wu.getMarkerId() != null&& wu.getMarker() == null) {
                // 用户存在但评卷员解绑
                return sessionExpire(request, response, "/mark-login");
            } else if (request.getServletPath().startsWith("/mark/logout")) {
                return true;
            }
            return true;
        }
        if (request.getServletPath().startsWith("/mark/subject-select")
                || request.getServletPath().startsWith("/mark/index")
                || request.getServletPath().startsWith("/mark/reset")
                || request.getServletPath().startsWith("/mark/logout")) {
            return sessionExpire(request, response, "/mark-login");
        }
        return sessionExpireAjax(request, response, "/mark-login");
    }

    private WebUser buildUser(HttpServletRequest request) {
        WebUser wu = WebUser.buildFromSession(RequestUtils.getSession(request), userService);
        if (wu != null && wu.getRole().equals(Role.MARKER)) {
            if (wu.getMarkerId() != null) {
                Marker marker = markerService.findById(wu.getMarkerId());
                if (marker != null) {
                    wu.setMarker(marker);
                }
            }
            RequestUtils.setWebUser(request, wu);
            return wu;
        }
        return null;
    }
}
