package cn.com.qmth.stmms.common.controller;

import java.util.Date;

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

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.ExamSubjectStatus;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.utils.Md5EncryptUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request) {
        return new ModelAndView("index");
    }

    @RequestMapping(value = "/admin-login", method = RequestMethod.GET)
    public ModelAndView adminIndex(HttpServletRequest request) {
        // StmmsSession session = RequestUtils.getSession(request);
        // if (StringUtils.isNotBlank(session.getParameter("userId"))) {
        // return new ModelAndView("modules/sys/examIndex");
        // } else {
        return new ModelAndView("modules/sys/sysLogin");
        // }
    }

    /**
     * 登录
     * 
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin-login", method = RequestMethod.POST)
    public ModelAndView adminLogin(User user, HttpServletRequest request, HttpServletResponse response) {
        User u = userService.findByLoginName(user.getLoginName());
        if (u != null) {
            if (u.getPassword().equals(Md5EncryptUtils.md5(user.getPassword()))) {
                u.setLastLoginTime(new Date());
                u.setLastLoginIp(request.getRemoteAddr());
                userService.save(u);

                StmmsSession session = RequestUtils.getSession(request);
                new WebUser(u.getId(), u.getRole()).writeToSession(session);

                if (u.getRole() == Role.SYS_ADMIN || u.getRole() == Role.SCHOOL_ADMIN
                        || u.getRole() == Role.SUBJECT_HEADER || u.getRole() == Role.SCHOOL_VIEWER) {
                    ModelAndView modelAndView = new ModelAndView("redirect:admin/home");
                    return modelAndView;
                } else {
                    ModelAndView view = new ModelAndView("modules/sys/sysLogin");
                    view.addObject("message", "用户没有访问权限");
                    return view;
                }
            } else {
                ModelAndView modelAndView = new ModelAndView("modules/sys/sysLogin");
                modelAndView.addObject("message", "密码错误");
                return modelAndView;
            }
        } else {
            ModelAndView modelAndView = new ModelAndView("modules/sys/sysLogin");
            modelAndView.addObject("message", "无此用户");
            return modelAndView;
        }
    }

    /**
     * 登出
     * 
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/admin-logout")
    public ModelAndView adminLogout(HttpServletRequest request, HttpServletResponse response) {
        RequestUtils.getSession(request).setInvalid(true);
        return new ModelAndView("redirect:/admin-login");
    }

    /**
     * 评卷员登录初始化
     * 
     * @param request
     * @return
     */
    @RequestMapping(value = "/mark-login", method = RequestMethod.GET)
    public ModelAndView loginInit(HttpServletRequest request, @RequestParam(required = false) String message) {
        ModelAndView modelAndView = new ModelAndView("modules/sys/markLogin");
        modelAndView.addObject("message", StringUtils.trimToNull(message));
        return modelAndView;
    }

    /**
     * 评卷员登录
     * 
     * @param request
     * @param loginType
     * @param examId
     * @param code
     * @param password
     * @return
     */
    @RequestMapping(value = "/mark-login", method = RequestMethod.POST)
    public ModelAndView login(HttpServletRequest request, @RequestParam String loginName,
            @RequestParam String password) {
        Marker marker = markerService.findByLoginName(loginName);
        if (marker != null) {
            return markerLogin(request, marker, password);
        }

        ModelAndView view = new ModelAndView("modules/sys/markLogin");
        view.addObject("message", "帐号不存在");
        return view;
    }

    /**
     * 评卷员登录
     * 
     * @param marker
     * @param request
     * @param response
     * @return
     */
    public ModelAndView markerLogin(HttpServletRequest request, Marker marker, String password) {
        ModelAndView modelAndView = new ModelAndView("modules/sys/markLogin");
        if (!marker.getPassword().equals(password)) {
            modelAndView.addObject("message", "密码错误");
            return modelAndView;
        }
        if (marker.isEnable() == false) {
            modelAndView.addObject("message", "帐号已禁用");
            return modelAndView;
        }
        ExamSubject subject = examSubjectService.find(marker.getExamId(), marker.getSubjectCode());
        if (subject == null) {
            modelAndView.addObject("message", "科目不存在");
            return modelAndView;
        }
        if (subject.getStatus() == ExamSubjectStatus.PAUSE) {
            modelAndView.addObject("message", "当前科目暂停评卷");
            return modelAndView;
        }
        if (subject.getStatus() == ExamSubjectStatus.FINISH) {
            modelAndView.addObject("message", "当前科目评卷已结束");
            return modelAndView;
        }

        new WebUser(marker.getId(), Role.MARKER).writeToSession(RequestUtils.getSession(request));

        if (marker.getLastLoginTime() == null) {
            return new ModelAndView("redirect:/mark/reset");
        } else {
            marker.setLastLoginTime(new Date());
            marker.setLastLoginIp(request.getRemoteAddr());
            markerService.save(marker);
        }
        return new ModelAndView("redirect:/mark/index");
    }

    /**
     * 评卷员登出
     * 
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/mark-logout")
    public ModelAndView markerLogout(HttpServletRequest request, HttpServletResponse response) {
        RequestUtils.getSession(request).setInvalid(true);
        return new ModelAndView("redirect:/mark-login");
    }
}
