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

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

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

import cn.com.qmth.stmms.biz.role.service.RoleAuthService;
import cn.com.qmth.stmms.biz.school.model.School;
import cn.com.qmth.stmms.biz.school.service.SchoolService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.biz.utils.RoleAuthUtil;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.hessian.HessianClientContext;
import cn.com.qmth.stmms.common.interceptor.CommonInterceptor;
import cn.com.qmth.stmms.common.utils.RequestUtils;

/**
 * Admin模块操作拦截器
 * 
 * @author LS
 * 
 */
public class AdminInterceptor extends CommonInterceptor {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleAuthService roleService;
    
    @Autowired
    private SchoolService schoolService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        return validateAdminUser(request, response);
    }

    private boolean validateAdminUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
        User user = buildUser(RequestUtils.getWebUser(request));
        if (user != null && (user.getType() == UserType.ADMIN || user.getType() == UserType.VIEWER|| user.getType() == UserType.SCHOOLVIEWER)) {
            HessianClientContext.setKey(user.getSchoolId());
            return true;
        }
        return sessionExpire(request, response, "/admin-login");
    }

    protected User buildUser(WebUser wu) {
        User user = null;
        if (wu != null) {
            user = wu.getUser();
            if (user == null) {
                user = userService.findById(wu.getId());
                if (user != null) {
                    user = RoleAuthUtil.buildRoleAuthByUser(user, roleService);
                    wu.setDataObject(user);
                    wu.setName(user.getName());
                    wu.setAuthMap(user.getAuthMap());
                    wu.setRoleMap(user.getRoleMap());
                    wu.setRoles(user.getRoles());
                    wu.setRoleDisplays(user.getRoleDisplays());
                    School school = schoolService.findById(user.getSchoolId());
                    if(school!=null){
                    	wu.setSchoolName(schoolService.findById(user.getSchoolId()).getName());
                    }
                    wu.setSchools(user.getSchools());
                }
            }
        }
        return user;
    }
}
