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.beans.factory.annotation.Value;
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.ExceptionStudentDTO;
import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.admin.thread.ImageCheckThread;
import cn.com.qmth.stmms.admin.utils.UpyunConfig;
import cn.com.qmth.stmms.biz.campus.service.CampusService;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
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/image")
public class ImageCheckController extends BaseParameterController {

    @Autowired
    private ExamService examService;

    @Autowired
    private CampusService campusService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private UpyunConfig config;

    @Autowired
    private AsyncTaskExecutor taskExecutor;

    @Value("${file.root}")
    private String baseDir;

    @RequestMapping
    public ModelAndView list(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            Exam exam = examService.findById(examId);
            ModelAndView view = new ModelAndView("modules/exam/checkImage");
            query.setExamId(examId);
            query.setUpload(true);
            query.setAbsent(false);
            query.setException(true);
            query.orderByExamNumber();
            query = studentService.findByQuery(query);

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

    @RequestMapping("/run")
    public ModelAndView checkImage(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);

                ImageCheckThread thread = new ImageCheckThread(examId, config, baseDir, examService, studentService,
                        campusService);
                taskExecutor.submit(thread);
            }
            return new ModelAndView("redirect:/admin/exam/check/image");
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/export")
    public String export(ExamStudentSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            List<ExceptionStudentDTO> list = new LinkedList<ExceptionStudentDTO>();
            query.setExamId(examId);
            query.setUpload(true);
            query.setAbsent(false);
            query.setException(true);
            query.setPageNumber(1);
            query.setPageSize(Integer.MAX_VALUE);
            query = studentService.findByQuery(query);
            for (ExamStudent student : query.getResult()) {
                ExceptionStudentDTO dto = new ExceptionStudentDTO(student);
                list.add(dto);
            }
            String fileName = "异常名单_" + DateUtils.getDate("yyyyMMdd") + ".xlsx";
            try {
                new ExportExcel("异常名单", ExceptionStudentDTO.class).setDataList(list).write(response, fileName)
                        .dispose();
                return null;
            } catch (Exception e) {
                addMessage(redirectAttributes, "导出失败！" + e.getMessage());
                return "redirect:/admin/exam/check/image";
            }
        } else {
            return "redirect:/admin/exam/list";
        }
    }
}
