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

import java.text.DecimalFormat;
import java.util.LinkedList;
import java.util.List;

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

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

import cn.com.qmth.stmms.admin.dto.MarkGroupDTO;
import cn.com.qmth.stmms.admin.dto.MarkerInfoDTO;
import cn.com.qmth.stmms.admin.vo.SubjectLibraryVO;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.model.MarkGroup;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.utils.ExportExcel;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller("markInfoController")
@RequestMapping("/admin/exam/mark")
public class MarkController extends BaseExamController {

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

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private MarkGroupService groupService;

    /**
     * 评卷进度
     * 
     * @param request
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = { "", "/subject" })
    public String subjectList(HttpServletRequest request, Model model, ExamSubjectSearchQuery query) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        query.setExamId(examId);
        // query.setUploadCountGt(0);
        subjectFilter(query, wu);
        query = subjectService.findByQuery(query);

        List<SubjectLibraryVO> list = new LinkedList<SubjectLibraryVO>();
        for (ExamSubject subject : query.getResult()) {
            SubjectLibraryVO vo = new SubjectLibraryVO();
            vo.setSubject(subject);
            vo.setStudentCount(subject.getUploadCount());
            vo.setGroupCount(groupService.countByExamAndSubject(examId, subject.getCode()));
            list.add(vo);
        }

        double total = (double) groupService.sumLibraryCount(examId);
        double finish = (double) groupService.sumMarkedCount(examId);
        double percent = total > 0 ? (finish * 100 / total) : 0;
        model.addAttribute("percent", new DecimalFormat("###.#").format(percent));
        model.addAttribute("resultList", list);
        model.addAttribute("query", query);
        model.addAttribute("subjectList", getExamSubject(examId, wu));
        model.addAttribute("levelList", subjectService.listLevel(examId));
        model.addAttribute("categoryList", subjectService.listCategory(examId));
        return "modules/exam/markInfo";
    }

    @RequestMapping(value = "/export-progress", method = RequestMethod.POST)
    public String exportProgress(HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        List<MarkGroupDTO> result = new LinkedList<MarkGroupDTO>();
        List<MarkGroup> list = wu.isSubjectHeader()
                ? groupService.findByExamAndSubject(examId, wu.getUser().getSubjectCode())
                : groupService.findByExam(examId);
        for (MarkGroup group : list) {
            group.setMarkerCount(
                    markerService.countByExamAndSubjectAndGroup(examId, group.getSubjectCode(), group.getNumber()));
            MarkGroupDTO dto = new MarkGroupDTO(subjectService.find(examId, group.getSubjectCode()), group);
            result.add(dto);
        }

        try {
            String fileName = "整体评卷进度.xlsx";
            new ExportExcel("整体评卷进度", MarkGroupDTO.class).setDataList(result).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出整体评卷进度失败！" + e.getMessage());
            return "redirect:/admin/exam/mark";
        }
    }

    @RequestMapping(value = "/export-marker", method = RequestMethod.POST)
    public String exportMarker(HttpServletRequest request, HttpServletResponse response,
            RedirectAttributes redirectAttributes) {
        WebUser wu = RequestUtils.getWebUser(request);
        int examId = getSessionExamId(request);
        List<MarkerInfoDTO> result = new LinkedList<MarkerInfoDTO>();
        List<Marker> list = wu.isSubjectHeader() ? markerService.getMarkCount(examId, wu.getUser().getSubjectCode())
                : markerService.getMarkCount(examId);
        for (Marker marker : list) {
            MarkerInfoDTO dto = new MarkerInfoDTO(marker,
                    subjectService.find(marker.getExamId(), marker.getSubjectCode()),
                    groupService.findOne(examId, marker.getSubjectCode(), marker.getGroupNumber()));
            result.add(dto);
        }

        try {
            String fileName = "评卷员工作量.xlsx";
            new ExportExcel("评卷员工作量", MarkerInfoDTO.class).setDataList(result).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            addMessage(redirectAttributes, "导出评卷员工作量失败！" + e.getMessage());
            return "redirect:/admin/exam/mark";
        }
    }

}
