package cn.com.qmth.stmms.mark;

import javax.servlet.http.HttpServletRequest;

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.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

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.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.mark.model.Task;
import cn.com.qmth.stmms.biz.mark.service.TaskService;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/admin/mark/leader")
public class MarkLeaderController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(MarkLeaderController.class);

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private TaskService taskService;

    @Autowired
    private ExamStudentService studentService;

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

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

    @Value("${card.server}")
    private String cardServer;

    @RequestMapping("/index")
    public ModelAndView index(HttpServletRequest request, @RequestParam(value = "studentId") Integer studentId) {
        ExamStudent student = studentService.findById(studentId);
        WebUser user = RequestUtils.getWebUser(request);
        Marker marker = new Marker();
        marker.setId(user.getId());
        marker.setName(user.getName());
        marker.setExamId(student.getExamId());
        marker.setSubjectCode(student.getSubjectCode());
        ModelAndView modelAndView = new ModelAndView("modules/mark/markLeader");
        preProcess(marker, studentId, modelAndView);
        return modelAndView;
    }

    /**
     * 进入评卷界面后的通用预处理
     * 
     * @param marker
     * @param modelAndView
     * @param modelAndView
     */
    private void preProcess(Marker marker, Integer studentId, ModelAndView modelAndView) {
        modelAndView.addObject("sliceServer", sliceServer);
        modelAndView.addObject("sheetServer", sheetServer);
        modelAndView.addObject("cardServer", cardServer);
        modelAndView.addObject("marker", marker);
        modelAndView.addObject("studentId", studentId);
        ExamStudent student = studentService.findById(studentId);
        modelAndView.addObject("subject", subjectService.find(student.getExamId(), student.getSubjectCode()));
    }

    @RequestMapping("/status")
    @ResponseBody
    public JSONObject status(HttpServletRequest request,
            @RequestParam(value = "studentId", required = false) Integer studentId) {
        JSONObject status = new JSONObject();
        if (studentId == null) {
            status.accumulate("valid", false);
            status.accumulate("totalCount", 1);
            status.accumulate("markedCount", 1);
        } else {
            ExamStudent student = studentService.findById(studentId);
            ExamSubject subject = subjectService.find(student.getExamId(), student.getSubjectCode());
            if (subject == null) {
                status.accumulate("valid", false);
                return status;
            }
            status.accumulate("valid", true);
        }
        return status;
    }

    @RequestMapping("/gettask")
    @ResponseBody
    public Task getTask(HttpServletRequest request,
            @RequestParam(value = "studentId", required = false) Integer studentId) {
        WebUser marker = RequestUtils.getWebUser(request);
        Task task = null;
        if (studentId == null) {
            task = new Task();
            task.setExist(false);
            task.setMessage("当前无评卷任务");
        } else {
            task = getTask(marker, studentId);
        }
        return task;
    }

    /**
     * 设置任务通用属性
     * 
     * @param task
     * @param marker
     * @param stage
     * @param count
     * @param bmList
     */
    private void setTaskParameter(Task task, WebUser marker) {
        task.setHeaderId(marker.getId());
    }

    private Task getTask(WebUser marker, Integer studentId) {
        Task task = taskService.build(studentId);
        setTaskParameter(task, marker);
        return task;
    }

    @RequestMapping(value = "/savetask", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject saveTask(HttpServletRequest request, @RequestBody Task task) {
        JSONObject result = new JSONObject();
        try {
            if (taskService.submitByStudent(task)) {
                result.accumulate("success", true);
                result.accumulate("status", status(request, null));
            } else {
                result.accumulate("success", false);
            }
        } catch (Exception e) {
            log.error("MarkController-保存任务出错", e);
            result.accumulate("success", false);
        }
        return result;
    }

}
