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

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

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
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.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.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.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.ExamStudentService;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

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

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private CampusService campusService;

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

    @RequestMapping
    public ModelAndView index(HttpServletRequest request) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ModelAndView view = new ModelAndView("modules/exam/checkAnswer");
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @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("/start")
    @ResponseBody
    public ModelAndView start(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ModelAndView view = new ModelAndView("modules/exam/checkAnswerEdit");
            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);
            }
            view.addObject("sheetServer", sheetServer);
            view.addObject("ids", StringUtils.join(ids, ","));
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/save")
    @ResponseBody
    public Object save(HttpServletRequest request, @RequestParam Integer studentId, @RequestParam String answers,
            @RequestParam(required = false) Boolean absent) {
        ExamStudent student = studentService.findById(studentId);
        if (student != null) {
            if (absent != null) {
                student.setAbsent(absent);
            }
            student.setAnswers(answers);
            student.setUploadTime(new Date());
            saveMarkLibrary(student);
            return studentService.save(student) != null;
        } 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", 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());

        Campus campus = campusService.findBySchoolAndName(student.getSchoolId(), student.getCampusName());
        result.accumulate("sheetUrls", PictureUrlBuilder.getSheetUrls(student.getExamId(), campus.getId(),
                student.getSubjectCode(), student.getExamNumber(), student.getSheetCount()));

        JSONArray array = new JSONArray();
        Map<Integer, String> titles = new HashMap<Integer, String>();
        List<ExamQuestion> questions = questionService.findByExamAndSubjectAndObjective(student.getExamId(),
                student.getSubjectCode(), true);
        List<String> answers = student.getAnswerList();
        if (questions.isEmpty()) {
            // 未设置客观题或无客观题
            int count = answers.size();
            for (int i = 0; i < count; i++) {
                JSONObject obj = new JSONObject();
                obj.accumulate("mainNumber", 1);
                obj.accumulate("subNumber", i + 1);
                obj.accumulate("answer", answers.get(i));
                obj.accumulate("exist", true);
                obj.accumulate("multi", true);
                array.add(obj);
            }
            titles.put(1, "客观题");
        } else {
            // 已设置客观题
            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("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);
        return result;
    }
}
