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

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

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.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.ExamStudent;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.common.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;

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

    @Autowired
    private CampusService campusService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private UpyunConfig config;

    @Autowired
    private AsyncTaskExecutor taskExecutor;

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

    private AtomicBoolean running = new AtomicBoolean(false);

    @RequestMapping
    public ModelAndView list(HttpServletRequest request, ExamStudentSearchQuery query) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        ModelAndView view = new ModelAndView("modules/exam/checkImage");
        query.setExamId(examId);
        query.setUpload(true);
        query.setAbsent(false);
        query.setException(true);
        query.orderByExamNumber();
        subjectFilter(query, wu);
        query = studentService.findByQuery(query);

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

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

    @RequestMapping("/export")
    public String export(ExamStudentSearchQuery query, HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        WebUser wu = RequestUtils.getWebUser(request);
        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);
        subjectFilter(query, wu);
        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";
        }
    }
}
