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

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

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qmth.stmms.admin.exam.parameter.BaseParameterController;
import cn.com.qmth.stmms.biz.campus.model.Campus;
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.model.ExamSubject;
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.TagService;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.query.MarkLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;

@Controller("tagController")
@RequestMapping("/admin/exam/tag")
public class TagController extends BaseParameterController {

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

    @Autowired
    private CampusService campusService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private TagService tagService;

    @Value("${sheet.image.server}")
    private String imageServer;

    /**
     * 标记试卷处理
     * 
     * @param request
     * @param model
     * @param query
     * @return
     */
    @RequestMapping
    public String list(HttpServletRequest request, Model model, MarkLibrarySearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query.setTagNotNull(true);
            query.orderByExamNumber();
            if (query.getTagId() == 0) {
                query.setTagId(1);
            }
            query = libraryService.findByQuery(query);

            List<ExamStudent> list = new LinkedList<ExamStudent>();
            for (MarkLibrary library : query.getResult()) {
                ExamStudent student = studentService.findById(library.getStudentId());
                if(student != null){
                    student.setSheetUrls(PictureUrlBuilder.getSheetUrls(examId, library.getCampusId(),
                            student.getSubjectCode(), student.getExamNumber(), student.getSheetCount()));
                    student.setMarkTime(DateUtils.formatDateTime(library.getMarkerTime()));
                }
                list.add(student);
            }
            model.addAttribute("resultList", list);
            model.addAttribute("query", query);
            model.addAttribute("subjectList", getTagSubject(examId));
            model.addAttribute("campusList", getTagCampus(examId));
            model.addAttribute("tagList", tagService.findAll());
            model.addAttribute("imageServer", imageServer);
            return "modules/exam/tagInfo";
        }
        return "redirect:/admin/exam/list";
    }

    @RequestMapping("/back")
    @ResponseBody
    public Object back(HttpServletRequest request, @RequestParam Integer studentId) {
        JSONObject result = new JSONObject();
        MarkLibrary library = libraryService.findByStudentId(studentId);
        if (library != null) {
            libraryService.resetById(library.getId());
            subjectService.updateMarkedCount(library.getExamId(), library.getSubjectCode(),
                    (int) libraryService.countByExamAndSubjectAndStatus(library.getExamId(), library.getSubjectCode(),
                            LibraryStatus.MARKED));
            studentService.updateSubjectiveScore(studentId, 0D, null);
            result.accumulate("success", true);
        } else {
            result.accumulate("success", false);
            result.accumulate("message", "找不到对应的评卷任务");
        }
        return result;
    }

    private List<Campus> getTagCampus(int examId) {
        List<Campus> list = new LinkedList<Campus>();
        List<Integer> ids = libraryService.findTagCampusId(examId);
        for (Integer id : ids) {
            Campus campus = campusService.findById(id);
            if (campus != null) {
                list.add(campus);
            }
        }
        return list;
    }

    private List<ExamSubject> getTagSubject(int examId) {
        List<ExamSubject> list = new LinkedList<ExamSubject>();
        List<String> codes = libraryService.findTagSubjectCode(examId);
        for (String code : codes) {
            ExamSubject subject = subjectService.find(examId, code);
            if (subject != null) {
                list.add(subject);
            }
        }
        return list;
    }

}
