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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang.StringUtils;
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.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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.MarkGroup;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.model.MarkSpecialTag;
import cn.com.qmth.stmms.biz.mark.model.MarkTrack;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.MarkSpecialTagService;
import cn.com.qmth.stmms.biz.mark.service.MarkTrackService;
import cn.com.qmth.stmms.biz.utils.OriginTag;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller("trackController")
@RequestMapping("/admin/exam/track")
public class MarkTrackController extends BaseExamController {

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

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

    @Autowired
    private MarkTrackService markTrackService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private CampusService campusService;

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private MarkSpecialTagService markSpecialTagService;
    
    @Autowired
    private ExamQuestionService questionService;

    @RequestMapping("/student/{studentId}")
    public ModelAndView view(@PathVariable Integer studentId) {
        ModelAndView view = new ModelAndView("modules/exam/studentTrack");
        view.addObject("imageServer", imageServer);
        ExamStudent student = studentService.findById(studentId);
        if (student != null && student.isUpload()) {
            Campus campus = campusService.findBySchoolAndName(student.getSchoolId(), student.getCampusName());
            List<String> sliceUrls = PictureUrlBuilder.getSliceUrls(student.getExamId(), campus.getId(),
                    student.getSubjectCode(), student.getExamNumber(), student.getSliceCount());
            view.addObject("urls", StringUtils.join(sliceUrls, ","));

            JSONArray result = new JSONArray();
            Map<MarkGroup, List<OriginTag>> maps = studentService.getSliceTags(student);
            for (Entry<MarkGroup, List<OriginTag>> entry : maps.entrySet()) {
                MarkGroup group = entry.getKey();
                JSONObject item = new JSONObject();
                item.accumulate("config", group.getPictureConfigList());
                item.accumulate("tags", entry.getValue());
                result.add(item);
            }
            view.addObject("tags", result.toString());
        }
        return view;
    }

    /**
     * 
     * @param request
     * @param model
     * @param query
     * @return
     */
    @ResponseBody
    @RequestMapping
    public HashMap<String, Object> list(Integer studentId) {
        List<MarkLibrary> librarys = libraryService.findByStudentId(studentId);
        ExamStudent examStudent = studentService.findById(studentId);
        Campus campus = campusService.findBySchoolAndName(examStudent.getSchoolId(), examStudent.getCampusName());
        List<Object> list = new ArrayList<Object>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        for (MarkLibrary library : librarys) {
            if (null != library.getTaskNumber() && library.getTaskNumber() == 2) {
                continue;
            }
            HashMap<String, Object> groups = set(library, examStudent, campus);
            list.add(groups);
        }
        map.put("list", list);
        map.put("imageServer", imageServer);
        return map;
    }

    @ResponseBody
    @RequestMapping("/byLibrary")
    public HashMap<String, Object> byLibrary(Integer libraryId) {
        MarkLibrary library = libraryService.findById(libraryId);
        ExamStudent examStudent = studentService.findById(library.getStudentId());
        Campus campus = campusService.findBySchoolAndName(examStudent.getSchoolId(), examStudent.getCampusName());
        List<Object> list = new ArrayList<Object>();
        HashMap<String, Object> map = new HashMap<String, Object>();
        HashMap<String, Object> groups = set(library, examStudent, campus);
        list.add(groups);
        map.put("list", list);
        map.put("imageServer", imageServer);
        return map;
    }

    private HashMap<String, Object> set(MarkLibrary library, ExamStudent examStudent, Campus campus) {
        HashMap<String, Object> groups = new HashMap<String, Object>();
        MarkGroup group = groupService.findOne(examStudent.getExamId(), examStudent.getSubjectCode(),
                library.getGroupNumber());
        group.setQuestionList(questionService.findByExamAndSubjectAndObjectiveAndGroupNumber(examStudent.getExamId(), examStudent.getSubjectCode(),
                    false, group.getNumber()));
        List<String> picUrls = PictureUrlBuilder.getSliceUrls(examStudent.getExamId(), campus.getId(),
                examStudent.getSubjectCode(), examStudent.getExamNumber(), examStudent.getSliceCount());
        List<MarkTrack> markTracks = markTrackService.findByLibraryId(library.getId());
        List<MarkSpecialTag> markSpecialTagList = markSpecialTagService.findByLibraryId(library.getId());
        groups.put("picUrls", picUrls);
        groups.put("pictureConfig", group.getPictureConfigList());
        groups.put("markTracks", markTracks);
        groups.put("groupTitle", group.getTitle());
        groups.put("groupNumber", group.getNumber());
        groups.put("markSpecialTagList", markSpecialTagList);
        return groups;
    }

}
