package cn.com.qmth.stmms.api.controller;

import java.io.IOException;
import java.util.Date;

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.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
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.ResponseBody;

import cn.com.qmth.stmms.api.utils.ScanStudentParameter;
import cn.com.qmth.stmms.biz.api.auth.annotation.AuthValidate;
import cn.com.qmth.stmms.biz.api.auth.exception.ApiException;
import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.user.model.User;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller
@RequestMapping("/api/scan")
public class ScanController extends BaseApiController {

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

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamService examService;

    /**
     * 上传考生识别结果
     * 
     * @param request
     * @param examId
     * @param subjectId
     * @param scStudentParameter
     * @return
     * @throws IOException
     */
    @AuthValidate("adminUser")
    @RequestMapping(value = "/student/{examId}", method = RequestMethod.POST)
    @ResponseBody
    @Transactional
    public JSONArray saveStudent(HttpServletRequest request, HttpServletResponse response, @PathVariable Integer examId,
            @RequestBody ScanStudentParameter[] scStudentParameter) {
        User user = RequestUtils.getApiUser(request);
        JSONArray array = new JSONArray();

        Exam exam = examService.findById(examId);
        // 判断上传权限
        if (exam == null || !exam.getSchoolId().equals(user.getSchoolId())) {
            throw ApiException.EXAM_NOT_ACCESSIBLED;
        }

        if (scStudentParameter != null && scStudentParameter.length > 0) {
            for (ScanStudentParameter sc : scStudentParameter) {
                ExamStudent student = studentService.findByExamIdAndExamNumber(examId, sc.getExamNumber());
                if (student != null) {
                    student.setUpload(true);
                    student.setUploadTime(new Date());
                    student.setAbsent(sc.isAbsent());
                    student.setAnswers(
                            StringUtils.isEmpty(sc.getAnswers()) ? sc.getAnswers() : sc.getAnswers().toUpperCase());
                    student.setBatchCode(sc.getBatchCode());
                    student.setSliceCount(sc.getSliceCount());
                    student.setSheetCount(sc.getSheetCount());
                    // 同步更新评卷任务及客观题分数
                    saveMarkLibrary(student);

                    if (studentService.save(student) != null) {
                        JSONObject obj = new JSONObject();
                        obj.accumulate("examNumber", student.getExamNumber());
                        obj.accumulate("uploadTime", DateUtils.formatDateTime(student.getUploadTime()));
                        array.add(obj);
                    }
                }
            }
        }
        return array;
    }

}
