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

import java.text.SimpleDateFormat;
import java.util.Date;

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

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.Exam;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
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.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 extends BaseController{

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

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

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

    protected static final String LOGIN_VIEW = "modules/sys/login";

    private static final String LOGIN_TYPE_KEY = "loginType";

    @Autowired
    private UserService userService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private ExamSubjectService examSubjectService;

    @Autowired
    private ExamService examService;

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

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

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

    /**
     * 登录
     * 
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/admin-login", method = RequestMethod.POST)
    public ModelAndView adminLogin(User user, HttpServletRequest request, HttpServletResponse response) {
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute("message");
        User u = userService.findByLoginNameAndStatus(user.getLoginName());
        if (u != null) {
            return adminLogin(u, user.getPassword(), request);
        } else {
            if ("aopeng".equals(appIndex)) {
                ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                aPview.addObject("message", "无此用户");
                return aPview;
            }
            ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
            modelAndView.addObject("message", "无此用户");
            return modelAndView;
        }
    }

    @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(LOGIN_VIEW);
        view.addObject("indexLogo", indexLogo);
        view.addObject("showType", "admin-login");
        return view;
    }

    /**
     * 登录
     * 
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView adminLogin(User user, @RequestParam(required = false) String showType,
            HttpServletRequest request, HttpServletResponse response) {
        StmmsSession session = RequestUtils.getSession(request);
        String loginType = session.getParameter(LOGIN_TYPE_KEY);
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute("message");
        // 管理员
        if ("admin-login".equals(showType)) {
            User u = userService.findByLoginNameAndStatus(user.getLoginName());
            if (u != null) {
                return adminLogin(u, user.getPassword(), request);
            } else {
                if ("aopeng".equals(appIndex)) {
                    ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                    aPview.addObject("message", "无此用户");
                    return aPview;
                }
                ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
                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) {
                return markerLogin(request, marker, user.getPassword());
            }
            if(loginType!=null){
                httpSession.setAttribute("message", "帐号不存在");
                ModelAndView view = new ModelAndView("redirect:/mark-login");
                return view;
            }
            ModelAndView view = new ModelAndView(LOGIN_VIEW);
            view.addObject("message", "帐号不存在");
            view.addObject("showType", showType);
            view.addObject("indexLogo", indexLogo);
            view.addObject(LOGIN_TYPE_KEY, loginType);
            return view;
        } else {
            return new ModelAndView("redirect:/login");
        }

    }

    /**
     * 管理员登录
     * @param u
     * @param password
     * @param request
     * @param session
     * @return
     */
    private ModelAndView adminLogin(User u, String password, HttpServletRequest request) {
        if (u.getPassword().equals(Md5EncryptUtils.md5(password))) {
            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(LOGIN_VIEW);
                view.addObject("message", "无此类型的用户");
                view.addObject("showType", "admin-login");
                view.addObject("indexLogo", indexLogo);
                return view;
            }
        } else {
            if ("aopeng".equals(appIndex)) {
                ModelAndView aPview = new ModelAndView(AP_SYS_LOGIN_VIEW);
                aPview.addObject("message", "密码错误");
                return aPview;
            }
            ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
            modelAndView.addObject("message", "密码错误");
            modelAndView.addObject("showType", "admin-login");
            modelAndView.addObject("indexLogo", indexLogo);
            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) {
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter(LOGIN_TYPE_KEY, "mark-login");
        HttpSession httpSession = request.getSession();
        String message = (String) httpSession.getAttribute("message");
        if ("aopeng".equals(appIndex)) {
            ModelAndView aPview = new ModelAndView(AP_MARK_LOGIN_VIEW);
            aPview.addObject("message", StringUtils.trimToNull(message));
            httpSession.removeAttribute("message");
            return aPview;
        }
        ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
        modelAndView.addObject("message", StringUtils.trimToNull(message));
        httpSession.removeAttribute("message");
        modelAndView.addObject(LOGIN_TYPE_KEY, "mark-login");
        modelAndView.addObject("indexLogo", indexLogo);
        return modelAndView;
    }

    /**
     * 评卷员登录
     * 
     * @param marker
     * @param request
     * @param response
     * @return
     */
    public ModelAndView markerLogin(HttpServletRequest request, Marker marker, String password) {
        StmmsSession session = RequestUtils.getSession(request);
        HttpSession httpSession = request.getSession();
        String loginType = session.getParameter(LOGIN_TYPE_KEY);
        ModelAndView modelAndView = new ModelAndView(LOGIN_VIEW);
        modelAndView.addObject("indexLogo", indexLogo);
        modelAndView.addObject("showType", "mark-login");
        if(loginType!=null){
            modelAndView = new ModelAndView("redirect:/mark-login");
        }
        if (!marker.getPassword().equals(password)) {
            httpSession.setAttribute("message", "密码错误");
            modelAndView.addObject("message", "密码错误");
            return modelAndView;
        }
        if (marker.isEnable() == false) {
            httpSession.setAttribute("message", "帐号已禁用");
            modelAndView.addObject("message", "帐号已禁用");
            return modelAndView;
        }
        Exam exam = examService.findById(marker.getExamId());
        Date now = new Date();
        if ((exam.getStartTime() != null && now.before(exam.getStartTime()))
                || (exam.getEndTime() != null && now.after(exam.getEndTime()))) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String start = exam.getStartTime() == null ? "" : " 开始时间：" + sdf.format(exam.getStartTime());
            String end = exam.getEndTime() == null ? "" : " 结束时间：" + sdf.format(exam.getEndTime());
            httpSession.setAttribute("message", "不在评卷时间范围 " + start + " " + end);
            modelAndView.addObject("message", "不在评卷时间范围 " + start + " " + end);
            return modelAndView;
        }

        new WebUser(marker.getId(), UserType.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/subject-select");
        }
    }

    /**
     * 评卷员登出
     * 
     * @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");
    }
}
