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

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.query.ExamSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.auth.annotation.AuthRequire;
import cn.com.qmth.stmms.common.enums.Auth;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.enums.UserType;
import cn.com.qmth.stmms.common.session.model.StmmsSession;
import cn.com.qmth.stmms.common.utils.Paginator;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin/exam")
public class ExamController extends BaseParameterController {

    protected static Logger log = LoggerFactory.getLogger(ExamController.class);

    @Autowired
    private ExamService examService;

    @RequestMapping(value = { "", "/list" })
    @AuthRequire(value = { Auth.EXAM_VIEW_SELF, Auth.EXAM_VIEW_CAMPUS }, isAny = true)
    public String examList(Model model, HttpServletRequest request, ExamSearchQuery query) {
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter("examId", null);
        request.removeAttribute("examId");
        User user = RequestUtils.getWebUser(request).getUser();
        if (user.getType() == UserType.ADMIN) {
            // 注释原因：原先一个学校只能有一个管理员，修改为一个学校可以有多个管理员，所以调整以学校ID为过滤条件
            // query.setCreatorId(user.getId());
            query.setSchoolId(user.getSchoolId());
        } else if (user.getType() == UserType.VIEWER || user.getType() == UserType.SCHOOLVIEWER) {
            query.setSchoolId(user.getSchoolId());
        }
        query.setOrderByCreateTimeDesc(true);
        query = examService.findByQuery(query);
        if (query.getCurrentCount() > 0) {
            model.addAttribute("examList", query.getResult());
            model.addAttribute("paginator",
                    new Paginator(query.getPageNumber(), query.getPageSize(), (int) query.getTotalCount()));
        }
        model.addAttribute("query", query);
        return "modules/exam/examList";
    }

    @RequestMapping("/form")
    // @AuthRequire({ Auth.EXAM_CREATE })
    public String add(Exam exam, Model model) {
        model.addAttribute("exam", exam);
        return "modules/exam/examForm";
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    // @AuthRequire({ Auth.EXAM_CREATE })
    public String save(HttpServletRequest request, Exam exam, RedirectAttributes redirectAttributes) {
        User user = RequestUtils.getWebUser(request).getUser();
        exam.setSchoolId(user.getSchoolId());
        exam.setCreatorId(user.getId());
        exam.setStatus(ExamStatus.START);
        exam = examService.save(exam);
        addMessage(redirectAttributes, "创建考试'" + exam.getName() + "'成功");
        return "redirect:/admin/exam";
    }

    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    // @AuthRequire({ Auth.EXAM_CREATE })
    public String examEdit(HttpServletRequest request, Exam exam) {
        User user = RequestUtils.getWebUser(request).getUser();
        Exam oldExam = examService.findById(exam.getId());
        if (oldExam != null && oldExam.getCreatorId().intValue() == user.getId().intValue()) {
            oldExam.setName(exam.getName());
            oldExam.setExamTime(exam.getExamTime());
            oldExam.setDescription(exam.getDescription());
            examService.save(oldExam);
        }
        return "redirect:/exam/list";
    }

    @RequestMapping("/view/{examId}")
    @AuthRequire({ Auth.EXAM_VIEW_SELF })
    public String view(Model model, HttpServletRequest request, @PathVariable Integer examId) {
        StmmsSession session = RequestUtils.getSession(request);
        session.setParameter("examId", examId.toString());

        User user = RequestUtils.getWebUser(request).getUser();
        if (user.getType() == UserType.ADMIN) {
            // 管理员可以进入考生管理
            return "redirect:/admin/exam-param/student";
        } else {
            // 其他查询员类型，直接去成绩查询
            return "redirect:/admin/exam/score";
        }

        /*
         * Exam exam = examService.findById(examId); long studentCount =
         * examStudentService.countByExamId(exam.getId()); long subjectCount =
         * examSubjectService.count(examId); long campusCount =
         * examStudentService.countCampusByExam(examId); long markerCount =
         * markerService.countByExam(exam.getId()); long scanCount =
         * examStudentService.countByExamIdAndUpload(examId, true); long
         * markedCount = libraryService.countByExamAndStatus(examId,
         * LibraryStatus.MARKED);
         * 
         * List<ExamInfoVO> voList = new ArrayList<ExamInfoVO>();
         * 
         * ExamInfoVO student = new ExamInfoVO(); student.setName("考生");
         * student.setAttr("共导入 " + studentCount + " 个考生");
         * student.setUrl("/admin/exam-param/student");
         * 
         * ExamInfoVO subject = new ExamInfoVO(); subject.setName("科目");
         * subject.setAttr("共导入 " + subjectCount + " 个科目");
         * subject.setUrl("/admin/exam-param/paper");
         * 
         * ExamInfoVO campus = new ExamInfoVO(); campus.setName("学习中心");
         * campus.setAttr("共导入 " + campusCount + " 个学习中心");
         * campus.setUrl("/admin/exam-param/student");
         * 
         * ExamInfoVO marker = new ExamInfoVO(); marker.setName("评卷员");
         * marker.setAttr("已创建 " + markerCount + " 个评卷员");
         * marker.setUrl("/admin/exam-param/marker");
         * 
         * ExamInfoVO scan = new ExamInfoVO(); scan.setName("扫描进度");
         * scan.setAttr("已扫描 " + scanCount + " 个考生");
         * scan.setUrl("/admin/exam/scan");
         * 
         * ExamInfoVO mark = new ExamInfoVO(); mark.setName("评卷进度");
         * mark.setAttr("已评完 " + markedCount + " 个考生");
         * mark.setUrl("/admin/exam/mark");
         * 
         * // ExamInfoVO objective = new ExamInfoVO(); //
         * objective.setName("客观题"); // objective.setAttr("已设置 " +
         * objectiveCount + " 个科目"); //
         * objective.setUrl("/admin/exam-param/objective"); // // ExamInfoVO
         * subjective = new ExamInfoVO(); // subjective.setName("主观题"); //
         * subjective.setAttr("已设置 " + subjectiveCount + " 个科目"); //
         * subjective.setUrl("/admin/exam-param/subjective");
         * 
         * voList.add(student); voList.add(subject); voList.add(campus);
         * voList.add(marker); voList.add(scan); voList.add(mark); //
         * voList.add(objective); // voList.add(subjective);
         * model.addAttribute("exam", exam); model.addAttribute("list", voList);
         * return "modules/exam/examInfo";
         */
    }

    @RequestMapping("/analysisinfo")
    @AuthRequire({ Auth.EXAM_VIEW_SELF })
    public String analysisInfo(Model model, HttpServletRequest request) {
        String examId = RequestUtils.getSession(request).getParameter("examId");

        Exam exam = examService.findById(Integer.parseInt(examId));
        model.addAttribute("exam", exam);
        return "modules/exam/analysisInfo";
    }

    @RequestMapping("/getexaminfo")
    @ResponseBody
    public Exam getExamInfo(HttpServletRequest request) {
        String examId = RequestUtils.getSession(request).getParameter("examId");
        Exam exam = examService.findById(Integer.parseInt(examId));
        return exam;
    }

    @RequestMapping("/finish")
    @Transactional
    @ResponseBody
    public void finished(HttpServletRequest request) {
        String examId = RequestUtils.getSession(request).getParameter("examId");
        Exam exam = examService.findById(Integer.parseInt(examId));
        exam.setStatus(ExamStatus.ENDED);
        examService.save(exam);
    }

}
