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

import java.util.Date;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.MarkGroup;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
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.MarkStatus;
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 MarkGroupService groupService;

    @Value("${index.logo}")
    private String indexLogo;

    private static final String LOGIN_TYPE_KEY = "loginType";

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

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(HttpServletRequest request) {
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter(LOGIN_TYPE_KEY,null);
        ModelAndView view = new ModelAndView("modules/sys/login");
        view.addObject("indexLogo", indexLogo);
        view.addObject("showType", "admin-login");
        return view;
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(User user, @RequestParam(required = false) String showType, HttpServletRequest request,
            HttpServletResponse response) {
        StmmsSession session = RequestUtils.getSession(request);
        String loginType = session.getParameter(LOGIN_TYPE_KEY);
        if ("admin-login".equals(showType)) {
            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);

                    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/login");
                        view.addObject("message", "用户没有访问权限");
                        view.addObject("showType", showType);
                        view.addObject("indexLogo", indexLogo);
                        return view;
                    }
                } else {
                    ModelAndView modelAndView = new ModelAndView("modules/sys/login");
                    modelAndView.addObject("message", "密码错误");
                    modelAndView.addObject("showType", showType);
                    modelAndView.addObject("indexLogo", indexLogo);
                    return modelAndView;
                }
            } else {
                ModelAndView modelAndView = new ModelAndView("modules/sys/login");
                modelAndView.addObject("message", "无此用户");
                modelAndView.addObject("showType", showType);
                modelAndView.addObject("indexLogo", indexLogo);
                return modelAndView;
            }
        } else if("mark-login".equals(showType)||"mark-login".equals(loginType)){
            Marker marker = markerService.findByLoginName(user.getLoginName());
            if (marker != null) {
                ModelAndView modelAndView = new ModelAndView("modules/sys/login");
                if (!marker.getPassword().equals(user.getPassword())) {
                    modelAndView.addObject("message", "密码错误");
                    modelAndView.addObject("showType", showType);
                    modelAndView.addObject("indexLogo", indexLogo);
                    return modelAndView;
                }
                if (marker.isEnable() == false) {
                    modelAndView.addObject("message", "帐号已禁用");
                    modelAndView.addObject("showType", showType);
                    modelAndView.addObject("indexLogo", indexLogo);
                    return modelAndView;
                }
                MarkGroup group = groupService.findOne(marker.getExamId(), marker.getSubjectCode(),
                        marker.getGroupNumber());
                if (group == null) {
                    modelAndView.addObject("message", "大题不存在");
                    modelAndView.addObject("showType", showType);
                    modelAndView.addObject("indexLogo", indexLogo);
                    return modelAndView;
                }
                if (group.getStatus() == MarkStatus.FINISH) {
                    modelAndView.addObject("message", "评卷已结束");
                    modelAndView.addObject("showType", showType);
                    modelAndView.addObject("indexLogo", indexLogo);
                    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");
            }

            ModelAndView view = new ModelAndView("modules/sys/login");
            view.addObject("message", "帐号不存在");
            view.addObject("showType", showType);
            view.addObject("indexLogo", indexLogo);
            return view;
        } else{
        	return new ModelAndView("redirect:/login");
        }
    }

    @RequestMapping(value = "/mark-login", method = RequestMethod.GET)
    public ModelAndView markIndex(HttpServletRequest request) {
    	StmmsSession session = RequestUtils.getSession(request);
    	session.setParameter(LOGIN_TYPE_KEY, "mark-login");
        ModelAndView view = new ModelAndView("modules/sys/login");
        view.addObject(LOGIN_TYPE_KEY, "mark-login");
        view.addObject("indexLogo", indexLogo);
        return view;
    }

    /**
     * 登出
     * 
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/logout")
    public ModelAndView adminLogout(HttpServletRequest request, HttpServletResponse response) {
        StmmsSession session = RequestUtils.getSession(request);
        String loginType = session.getParameter(LOGIN_TYPE_KEY);
        RequestUtils.getSession(request).setInvalid(true);
        if ("mark-login".equals(loginType)) {
            return new ModelAndView("redirect:/mark-login");
        } else {
            return new ModelAndView("redirect:/login");
        }
    }

    
}
