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

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

import javax.servlet.http.HttpServletRequest;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
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.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.file.service.FileService;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.enums.ExamType;
import cn.com.qmth.stmms.common.enums.LogType;

@Controller
@RequestMapping("/admin/exam/check/answer")
public class AnswerCheckController extends BaseExamController {

    private static final String PAPER_TYPES_REGEX = "[a-zA-Z#]";

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamService examService;

    @Autowired
    private FileService fileService;

    @Logging(menu = "识别结果检查", type = LogType.QUERY)
    @RequestMapping
    public ModelAndView index(HttpServletRequest request) {
        int examId = getSessionExamId(request);
        Exam exam = examService.findById(examId);
        ModelAndView view = new ModelAndView("modules/exam/checkAnswer");
        if (ExamType.MULTI_MEDIA.equals(exam.getType())) {
            view = new ModelAndView("modules/exam/permission");
        }
        return view;
    }

    @Logging(menu = "识别结果查询数量", type = LogType.QUERY)
    @RequestMapping("/count")
    @ResponseBody
    public long count(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query.setUpload(true);
            return studentService.countByQuery(query);
        } else {
            return 0;
        }
    }

    @RequestMapping("/getSetting")
    @ResponseBody
    public JSONObject getSetting(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        JSONObject setting = new JSONObject();
        setting.accumulate("fileServer", fileService.getFileServer());
        List<Integer> ids = new ArrayList<Integer>();
        query.setExamId(examId);
        query.setUpload(true);
        query.setPageNumber(1);
        query.setPageSize(1000);
        query = studentService.findByQuery(query);
        while (query.getCurrentCount() > 0) {
            for (ExamStudent student : query.getResult()) {
                ids.add(student.getId());
            }
            query.setPageNumber(query.getPageNumber() + 1);
            query = studentService.findByQuery(query);
        }
        setting.accumulate("studentIds", ids);
        return setting;
    }

    @Logging(menu = "识别结果修改", type = LogType.UPDATE)
    @RequestMapping("/save")
    @ResponseBody
    public Object save(HttpServletRequest request, @RequestParam Integer studentId, @RequestParam String answers,
            @RequestParam(required = false) Boolean absent, @RequestParam String paperType) {
        ExamStudent student = studentService.findById(studentId);
        answers = StringEscapeUtils.unescapeHtml(StringUtils.trimToNull(answers));
        if (student != null && student.isUpload()) {
            if (absent != null) {
                student.setAbsent(absent);
            }
            student.setAnswers(answers == null ? null : answers.toUpperCase());
            if (paperType.matches(PAPER_TYPES_REGEX)) {
                student.setPaperType(paperType);
            }
            return saveUploadStudent(student);
        } else {
            return false;
        }
    }

    @RequestMapping("/info")
    @ResponseBody
    public Object info(@RequestParam Integer studentId) {
        ExamStudent student = studentService.findById(studentId);
        JSONObject result = new JSONObject();
        result.accumulate("id", student.getId());
        result.accumulate("name", student.getName());
        result.accumulate("examNumber", student.getExamNumber());
        result.accumulate("studentCode", student.getStudentCode());
        result.accumulate("campusName", StringUtils.trimToEmpty(student.getCampusName()));
        result.accumulate("subjectCode", student.getSubjectCode());
        result.accumulate("subjectName", student.getSubjectName());
        result.accumulate("objectiveScore", student.getObjectiveScore() != null ? student.getObjectiveScore() : 0);
        result.accumulate("subjectiveScore", student.getSubjectiveScore() != null ? student.getSubjectiveScore() : 0);
        result.accumulate("upload", student.isUpload());
        result.accumulate("absent", student.isAbsent());
        result.accumulate("paperType", student.getPaperType());
        result.accumulate("sheetUrls",
                fileService.getSheetUris(student.getExamId(), student.getExamNumber(), 1, student.getSheetCount()));

        JSONArray array = new JSONArray();
        Map<Integer, String> titles = new HashMap<Integer, String>();
        List<ExamQuestion> questions = questionService.findByExamAndSubjectAndObjectiveAndPaperType(
                student.getExamId(), student.getSubjectCode(), true, student.getPaperType());
        List<String> answers = student.getAnswerList();
        int questionCount = questions.size();
        int answerCount = answers.size();

        // 已设置客观题
        int maxCount = Math.max(questionCount, answerCount);
        for (int i = 0; i < maxCount; i++) {
            ExamQuestion q = questionCount > i ? questions.get(i) : null;
            String answer = answerCount > i ? answers.get(i) : "#";
            JSONObject obj = new JSONObject();
            obj.accumulate("mainNumber", q != null ? q.getMainNumber() : 0);
            obj.accumulate("subNumber", q != null ? q.getSubNumber() : 0);
            obj.accumulate("answer", answer);
            obj.accumulate("exist", q != null && q.getTotalScore() > 0);
            obj.accumulate("type", q != null && q.getType() != null ? q.getType() : "");
            // obj.accumulate("multi",
            // q != null && (q.getMainTitle().contains("多选") ||
            // q.getMainTitle().contains("多项选择")));
            array.add(obj);
            if (q != null) {
                titles.put(q.getMainNumber(), q.getMainTitle());
            }
        }
        result.accumulate("answers", array);
        result.accumulate("titles", titles);
        result.accumulate("success", true);
        return result;
    }
}
