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.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.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.UserType;
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 {

    protected static final String INDEX_VIEW = "modules/sys/index";

    protected static final String AP_INDEX_VIEW = "modules/sys/indexAp";

    protected static final String SYS_LOGIN_VIEW = "modules/sys/sysLogin";

    protected static final String AP_SYS_LOGIN_VIEW = "modules/sys/sysLoginAp";

    protected static final String MARK_LOGIN_VIEW = "modules/sys/markLogin";

    protected static final String AP_MARK_LOGIN_VIEW = "modules/sys/markLoginAp";

    @Autowired
    private UserService userService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @Value("${app.index}")
    private String appIndex;

    @RequestMapping(value = { "/", "", "/index" })
    public ModelAndView index(HttpServletRequest request) {
        if ("aopeng".equals(appIndex)) {
            return new ModelAndView(AP_INDEX_VIEW);
        }
        return new ModelAndView(INDEX_VIEW);
    }

    @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 {
        if ("aopeng".equals(appIndex)) {
            return new ModelAndView(AP_SYS_LOGIN_VIEW);
        }
        return new ModelAndView(SYS_LOGIN_VIEW);
        // }
    }

    /**
     * 登录
     * 
     * @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.findByLoginNameAndStatus(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.getType()).writeToSession(session);

                if (u.getType() == UserType.ADMIN || u.getType() == UserType.VIEWER
                        || u.getType() == UserType.SCHOOLVIEWER) {
                    if (u.getType() == UserType.VIEWER) {// 科组长
                        String examId = u.getLoginName().split("-")[0];
                        String subjectCode = u.getLoginName().split("-")[1];
                        session.setParameter("examId", examId);
                        session.setParameter("subjectCode", subjectCode);
                    }
                    ModelAndView modelAndView = new ModelAndView("redirect:admin/home");
                    return modelAndView;
                } else {
                    if ("aopeng".equals(appIndex)) {
                        ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                        aPview.addObject("message", "无此类型的用户");
                        return aPview;
                    }
                    ModelAndView view = new ModelAndView(SYS_LOGIN_VIEW);
                    view.addObject("message", "无此类型的用户");
                    return view;
                }
            } else {
                if ("aopeng".equals(appIndex)) {
                    ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                    aPview.addObject("message", "密码错误");
                    return aPview;
                }
                ModelAndView modelAndView = new ModelAndView(SYS_LOGIN_VIEW);
                modelAndView.addObject("message", "密码错误");
                return modelAndView;
            }
        } else {
            if ("aopeng".equals(appIndex)) {
                ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                aPview.addObject("message", "无此用户");
                return aPview;
            }
            ModelAndView modelAndView = new ModelAndView(SYS_LOGIN_VIEW);
            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) {

        if ("aopeng".equals(appIndex)) {
            ModelAndView aPview = new ModelAndView(AP_MARK_LOGIN_VIEW);
            aPview.addObject("message", StringUtils.trimToNull(message));
            return aPview;
        }
        ModelAndView modelAndView = new ModelAndView(MARK_LOGIN_VIEW);
        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);
        }

        // SubjectHeader header =
        // subjectHeaderService.findByLoginName(loginName);
        // if (header != null) {
        // return subjectHeaderLogin(request, header, password);
        // }
        if ("aopeng".equals(appIndex)) {
            ModelAndView aPview = new ModelAndView(AP_MARK_LOGIN_VIEW);
            aPview.addObject("message", "帐号不存在");
            return aPview;
        }
        ModelAndView view = new ModelAndView(MARK_LOGIN_VIEW);
        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(MARK_LOGIN_VIEW);
        ModelAndView modelAndViewForAP = new ModelAndView(AP_MARK_LOGIN_VIEW);
        if (!marker.getPassword().equals(password)) {
            if ("aopeng".equals(appIndex)) {
                modelAndViewForAP.addObject("message", "密码错误");
                return modelAndViewForAP;
            }
            modelAndView.addObject("message", "密码错误");
            return modelAndView;
        }
        if (marker.isEnable() == false) {
            if ("aopeng".equals(appIndex)) {
                modelAndViewForAP.addObject("message", "帐号已禁用");
                return modelAndViewForAP;
            }
            modelAndView.addObject("message", "帐号已禁用");
            return modelAndView;
        }
        if (!marker.isCommon()) {
            ExamSubject subject = examSubjectService.find(marker.getExamId(), marker.getSubjectCode());
            if (subject == null) {
                if ("aopeng".equals(appIndex)) {
                    modelAndViewForAP.addObject("message", "科目不存在");
                    return modelAndViewForAP;
                }
                modelAndView.addObject("message", "科目不存在");
                return modelAndView;
            }
            if (subject.getStatus() == ExamSubjectStatus.PAUSE) {
                if ("aopeng".equals(appIndex)) {
                    modelAndViewForAP.addObject("message", "当前科目暂停评卷");
                    return modelAndViewForAP;
                }
                modelAndView.addObject("message", "当前科目暂停评卷");
                return modelAndView;
            }
            if (subject.getStatus() == ExamSubjectStatus.FINISH) {
                if ("aopeng".equals(appIndex)) {
                    modelAndViewForAP.addObject("message", "当前科目评卷已结束");
                    return modelAndViewForAP;
                }
                modelAndView.addObject("message", "当前科目评卷已结束");
                return modelAndView;
            }
        }

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

        if (marker.getLastLoginTime() == null) {
            return new ModelAndView("redirect:/mark/reset");
        } else if (StringUtils.isBlank(marker.getSubjectCode())) {
            return new ModelAndView("redirect:/mark/subject-select");
        } 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");
    }
}
