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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
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.StringUtils;
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.ui.Model;
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.admin.vo.ScanInfoVO;
import cn.com.qmth.stmms.biz.exam.model.ExamPackage;
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.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.query.ExamPackageSearchQuery;
import cn.com.qmth.stmms.biz.exam.query.ExamStudentSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.ExamPackageService;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import cn.com.qmth.stmms.common.enums.ScanCheck;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;

@Controller("scanInfoController")
@RequestMapping("/admin/exam/scan")
public class ScanController extends BaseParameterController {

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

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamPackageService packageService;

    @Autowired
    private ExamQuestionService questionService;

    @Value("${package.image.server}")
    private String packageServer;

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

    /**
     * 按科目统计扫描进度
     * 
     * @param request
     * @param model
     * @param query
     * @return
     */
    @RequestMapping(value = { "", "/subject" })
    public ModelAndView progress(HttpServletRequest request, Model model, ExamSubjectSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            List<ScanInfoVO> list = new LinkedList<ScanInfoVO>();
            query.setExamId(examId);
            query = subjectService.findByQuery(query);
            for (ExamSubject subject : query.getResult()) {
                ScanInfoVO vo = new ScanInfoVO();
                vo.setName(subject.getCode()
                        + "-"
                        + subject.getName()
                        + (StringUtils.isNotBlank(subject.getRemark()) ? ("-" + StringUtils.trimToEmpty(subject
                                .getRemark())) : ""));
                vo.setTotalCount(studentService.countByExamIdAndSubjectCode(examId, subject.getCode()));
                vo.setScanCount(studentService.countByExamIdAndSubjectCode(examId, subject.getCode(), true));
                int percent = vo.getTotalCount() > 0 ? (int) (vo.getScanCount() * 100.00 / vo.getTotalCount()) : 0;
                vo.setPercent(percent);
                list.add(vo);
            }

            ModelAndView view = new ModelAndView("modules/exam/scanInfo");
            view.addObject("subjectList", getExamSubject(examId));
            view.addObject("levelList", subjectService.listLevel(examId));
            view.addObject("categoryList", subjectService.listCategory(examId));
            view.addObject("infoList", list);
            view.addObject("query", query);
            view.addObject("type", "subject");
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    /**
     * 按学习中心统计扫描进度
     * 
     * @param request
     * @param subjectCode
     * @return
     */
    @RequestMapping("/campus")
    public ModelAndView campus(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            List<ScanInfoVO> list = new LinkedList<ScanInfoVO>();
            if (StringUtils.isBlank(query.getCampusName())) {
                query.setExamId(examId);
                query = studentService.findDistinctCampusName(query);
                for (ExamStudent s : query.getResult()) {
                    ScanInfoVO vo = new ScanInfoVO();
                    vo.setName(s.getCampusName());
                    vo.setTotalCount(studentService.countByExamIdAndCampusName(examId, s.getCampusName()));
                    vo.setScanCount(studentService.countByExamIdAndCampusName(examId, s.getCampusName(), true));
                    int percent = vo.getTotalCount() > 0 ? (int) (vo.getScanCount() * 100.00 / vo.getTotalCount()) : 0;
                    vo.setPercent(percent);
                    list.add(vo);
                }
            } else {
                ScanInfoVO vo = new ScanInfoVO();
                vo.setName(query.getCampusName());
                vo.setTotalCount(studentService.countByExamIdAndCampusName(examId, query.getCampusName()));
                vo.setScanCount(studentService.countByExamIdAndCampusName(examId, query.getCampusName(), true));
                int percent = vo.getTotalCount() > 0 ? (int) (vo.getScanCount() * 100.00 / vo.getTotalCount()) : 0;
                vo.setPercent(percent);
                list.add(vo);

                query.setTotalCount(1);
                query.setTotalPage(1);
                query.setCurrentCount(1);
            }

            ModelAndView view = new ModelAndView("modules/exam/scanInfo");
            view.addObject("campusList", studentService.findDistinctCampusName(examId));
            view.addObject("infoList", list);
            view.addObject("query", query);
            view.addObject("type", "campus");
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    /**
     * 统计签到表扫描进度
     * 
     * @param request
     * @return
     */
    @RequestMapping("/package")
    public ModelAndView packageProgress(HttpServletRequest request, ExamPackageSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query = packageService.findByQuery(query);
            for (ExamPackage ep : query.getResult()) {
                ep.setUrls(PictureUrlBuilder.getPackageUrls(examId, ep.getCode(), ep.getPicCount()));
            }
            ModelAndView view = new ModelAndView("modules/exam/scanPackage");
            view.addObject("packageList", query.getResult());
            view.addObject("query", query);
            view.addObject("packageServer", packageServer);
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    /**
     * 审核考生
     * 
     * @param request
     * @return
     */
    @RequestMapping("/student")
    public ModelAndView studentProcess(HttpServletRequest request, ExamStudentSearchQuery query) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            query.setUpload(false);
            query.setManualAbsent(false);
            if (query.getScanCheck() == null) {
                query.setScanCheck(ScanCheck.TODO);
            }
            query = studentService.findByQuery(query);
            ModelAndView view = new ModelAndView("modules/exam/scanStudent");
            view.addObject("studentList", query.getResult());
            view.addObject("query", query);
            view.addObject("campusList", studentService.findDistinctCampusName(examId));
            view.addObject("subjectList", getExamSubject(examId));
            view.addObject("scanCheckList", ScanCheck.values());
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/student/start")
    @ResponseBody
    public ModelAndView start(HttpServletRequest request, @RequestParam String campusName,
            @RequestParam ScanCheck scanCheck) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ModelAndView view = new ModelAndView("modules/exam/scanStudentEdit");
            List<Integer> ids = new ArrayList<Integer>();
            ExamStudentSearchQuery query = new ExamStudentSearchQuery();
            query.setExamId(examId);
            query.setUpload(false);
            query.setManualAbsent(false);
            query.setCampusName(campusName);
            query.setScanCheck(scanCheck);
            query.setPageSize(Integer.MAX_VALUE);
            query = studentService.findByQuery(query);
            for (ExamStudent student : query.getResult()) {
                ids.add(student.getId());
            }
            view.addObject("packageServer", packageServer);
            view.addObject("ids", StringUtils.join(ids, ","));
            return view;
        } else {
            return new ModelAndView("redirect:/admin/exam/list");
        }
    }

    @RequestMapping("/student/save")
    @ResponseBody
    public Object save(HttpServletRequest request, @RequestParam Integer studentId, @RequestParam String answers,
            @RequestParam ScanCheck scanCheck) {
        ExamStudent student = studentService.findById(studentId);
        if (student != null) {
            student.setAnswers(answers);
            student.setScanCheck(scanCheck);
            studentService.save(student);
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping("/student/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());

        if (StringUtils.isNotBlank(student.getPackageCode())) {
            ExamPackage ep = packageService.find(student.getExamId(), student.getPackageCode());
            if (ep != null && ep.getPicCount() > 0) {
                result.accumulate("packageUrls", PictureUrlBuilder.getPackageUrls(student.getExamId(), student.getPackageCode(),
                        ep.getPicCount()));
            }
        }

        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;
    }

}
