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

import java.util.LinkedList;
import java.util.List;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.admin.dto.ExceptionQuestionDTO;
import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.admin.thread.ScoreCheckThread;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamQuestionSearchQuery;
import cn.com.qmth.stmms.common.enums.ExamStatus;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.ExportExcel;

@Controller
@RequestMapping("/admin/exam/check/score")
public class ScoreCheckController extends BaseParameterController {

    @Autowired
    private ExamService examService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private AsyncTaskExecutor taskExecutor;

    @RequestMapping
    public ModelAndView list(HttpServletRequest request, ExamQuestionSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            Exam exam = examService.findById(examId);
            ModelAndView view = new ModelAndView("modules/exam/checkScore");
            query.setExamId(examId);
            query.setTotalScoreGt(0d);
            query.setTotalCountGt(0);
            query.orderBySubjectAndNumber();
            if (query.getZeroRateGt() == null) {
                query.setZeroRateGt(1.0);
            }
            query = questionService.findByQuery(query);

            for (ExamQuestion q : query.getResult()) {
                q.setSubject((subjectService.find(q.getExamId(), q.getSubjectCode())));
            }

            view.addObject("query", query);
            view.addObject("subjectList", getExamSubject(examId));
            view.addObject("exam", exam);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/run")
    public ModelAndView checkScore(HttpServletRequest request) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            Exam exam = examService.findById(examId);
            if (exam != null && exam.getStatus() == ExamStatus.START) {
                exam.setStatus(ExamStatus.CHECKING);
                examService.save(exam);

                ScoreCheckThread thread = new ScoreCheckThread(examId, examService, studentService, questionService);
                taskExecutor.submit(thread);
            }
            return new ModelAndView("redirect:/admin/exam/check/score");
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/export")
    public String export(ExamQuestionSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            List<ExceptionQuestionDTO> list = new LinkedList<ExceptionQuestionDTO>();
            query.setExamId(examId);
            query.setTotalCountGt(0);
            query.orderBySubjectAndNumber();
            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            query = questionService.findByQuery(query);
            for (ExamQuestion question : query.getResult()) {
                ExceptionQuestionDTO dto = new ExceptionQuestionDTO(question, subjectService.find(question.getExamId(),
                        question.getSubjectCode()));
                list.add(dto);
            }
            String fileName = "异常试题_" + DateUtils.getDate("yyyyMMdd") + ".xlsx";
            try {
                new ExportExcel("异常试题", ExceptionQuestionDTO.class).setDataList(list).write(response, fileName)
                        .dispose();
                return null;
            } catch (Exception e) {
                addMessage(redirectAttributes, "导出失败！" + e.getMessage());
                return "redirect:/admin/exam/check/score";
            }
        } else {
            return "redirect:/admin/exam/list";
        }
    }
}
