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

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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.ui.Model;
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 cn.com.qmth.stmms.biz.exam.model.CheckStudent;
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.query.CheckStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.CheckStudentService;
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.domain.WebUser;
import cn.com.qmth.stmms.common.enums.CheckType;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.utils.RequestUtils;

@Controller
@RequestMapping("/admin/exam/check/student")
public class CheckStudentController extends BaseExamController {

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private CheckStudentService checkStudentService;

    @Autowired
    private FileService fileService;

    @Logging(menu = "人工确认查询", type = LogType.QUERY)
    @RequestMapping
    public String index(Model model, HttpServletRequest request, CheckStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        List<CheckStudent> list = null;
        if (StringUtils.isNotBlank(query.getSubjectCode())) {
            list = checkStudentService.findByExamIdAndSubjectCodeAndCheckedAndType(examId, query.getSubjectCode(),
                    false, CheckType.MANUAL);
        } else {
            list = checkStudentService.findByExamIdAndCheckedAndType(examId, false, CheckType.MANUAL);
        }
        List<Integer> studentIds = new ArrayList<Integer>();
        for (CheckStudent c : list) {
            studentIds.add(c.getStudentId());
        }
        if (!list.isEmpty()) {
            ExamStudentSearchQuery sQuery = new ExamStudentSearchQuery();
            sQuery.setExamId(examId);
            sQuery.setPageNumber(query.getPageNumber());
            sQuery.setPageSize(query.getPageSize());
            sQuery.setSubjectCode(query.getSubjectCode());
            sQuery.setExamSite(query.getExamSite());
            sQuery.setStudentIds(studentIds);
            List<ExamStudent> studentList = studentService.findByQuery(sQuery).getResult();
            query.setTotalCount(sQuery.getTotalCount());
            query.setTotalPage(sQuery.getTotalPage());
            model.addAttribute("studentList", studentList);
        } else {
            model.addAttribute("studentList", new ArrayList<ExamStudent>());
        }
        model.addAttribute("typeList", CheckType.values());
        model.addAttribute("subjectList", getCheckSubject(examId, wu));
        model.addAttribute("query", query);
        return "modules/exam/checkStudent";
    }

    private List<ExamSubject> getCheckSubject(int examId, WebUser wu) {
        List<ExamSubject> list = new LinkedList<ExamSubject>();
        List<String> codes = checkStudentService.findCheckSubjectCode(examId);
        List<ExamSubject> subjects = getExamSubject(examId, wu);
        for (ExamSubject examSubject : subjects) {
            if (codes.contains(examSubject.getCode())) {
                list.add(examSubject);
            }
        }
        return list;
    }

    @RequestMapping(value = "/getSetting", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject getSetting(HttpServletRequest request, @RequestParam CheckType checkType,
            @RequestParam(required = false) String subjectCode, @RequestParam(required = false) String examSite) {
        int examId = getSessionExamId(request);
        JSONObject setting = new JSONObject();
        setting.accumulate("fileServer", fileService.getFileServer());
        List<CheckStudent> list = null;
        if (StringUtils.isNotBlank(subjectCode)) {
            list = checkStudentService.findByExamIdAndSubjectCodeAndCheckedAndType(examId, subjectCode, false,
                    CheckType.MANUAL);
        } else {
            list = checkStudentService.findByExamIdAndCheckedAndType(examId, false, CheckType.MANUAL);
        }
        List<Integer> studentIds = new ArrayList<Integer>();
        for (CheckStudent c : list) {
            studentIds.add(c.getStudentId());
        }
        if (StringUtils.isNotBlank(examSite) && !studentIds.isEmpty()) {
            ExamStudentSearchQuery sQuery = new ExamStudentSearchQuery();
            sQuery.setExamId(examId);
            sQuery.setPageSize(Integer.MAX_VALUE);
            sQuery.setSubjectCode(subjectCode);
            sQuery.setExamSite(examSite);
            sQuery.setStudentIds(studentIds);
            List<ExamStudent> studentList = studentService.findByQuery(sQuery).getResult();
            studentIds = new ArrayList<Integer>();
            for (ExamStudent examStudent : studentList) {
                studentIds.add(examStudent.getId());
            }
        }
        setting.accumulate("studentIds", studentIds);
        return setting;
    }

    @Logging(menu = "人工确认考生", type = LogType.UPDATE)
    @RequestMapping("/save")
    @ResponseBody
    public Object save(HttpServletRequest request, @RequestParam Integer studentId, @RequestParam String answers) {
        ExamStudent student = studentService.findById(studentId);
        answers = StringEscapeUtils.unescapeHtml(StringUtils.trimToEmpty(answers));
        CheckStudent cs = checkStudentService.findByStudentId(studentId);
        if (student != null && cs != null) {
            student.setAnswers(answers.toUpperCase());
            studentService.save(student);
            cs.setChecked(true);
            cs.setUpdateTime(new Date());
            checkStudentService.save(cs);
            return saveUploadStudent(student);
        } else {
            return false;
        }
    }

}
