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

import cn.com.qmth.stmms.admin.dto.ExceptionStudentDTO;
import cn.com.qmth.stmms.admin.thread.ImageCheckThread;
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.model.ExamSubject;
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.biz.file.service.FileService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

@Controller
@RequestMapping("/admin/exam/check/image")
public class ImageCheckController extends BaseExamController {

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private FileService fileService;

    @Autowired
    private ExamService examService;

    @Qualifier("task-executor")
    @Autowired
    private AsyncTaskExecutor taskExecutor;

    private AtomicBoolean running = new AtomicBoolean(false);

    @Logging(menu = "图片检查", type = LogType.QUERY)
    @RequestMapping
    public ModelAndView list(HttpServletRequest request, ExamStudentSearchQuery query) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        List<ExamSubject> subjectList = getExamSubject(examId, wu);
        ModelAndView view = new ModelAndView("modules/exam/checkImage");
        query.setExamId(examId);
        query.setUpload(true);
        query.setAbsent(false);
        query.setException(true);
        query.orderByExamNumber();
        if (StringUtils.isBlank(query.getSubjectCode()) && !subjectList.isEmpty()) {
            query.setSubjectCode(subjectList.get(0).getCode());
        }
        query = studentService.findByQuery(query);

        view.addObject("query", query);
        view.addObject("subjectList", subjectList);
        view.addObject("campusList", studentService.findDistinctCampusName(examId));
        view.addObject("running", running.get());
        return view;
    }

    @RequestMapping("/run")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public ModelAndView checkImage(HttpServletRequest request) {
        Exam exam = examService.findById(getSessionExamId(request));
        if (running.compareAndSet(false, true)) {
            ImageCheckThread thread = new ImageCheckThread(exam, studentService, fileService, running);
            taskExecutor.submit(thread);
        }
        return new ModelAndView("redirect:/admin/exam/check/image");
    }

    @Logging(menu = "图片检查导出", type = LogType.EXPORT)
    @RequestMapping("/export")
    public String export(ExamStudentSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        List<ExceptionStudentDTO> list = new LinkedList<ExceptionStudentDTO>();
        query.setExamId(getSessionExamId(request));
        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 = "异常名单.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";
        }
    }
}
