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

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

import javax.servlet.http.HttpServletRequest;

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.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.model.ExamSubjectPaper;
import cn.com.qmth.stmms.biz.exam.model.ExamSubjectPaperDTO;
import cn.com.qmth.stmms.biz.exam.service.ExamQuestionService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectPaperService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectPaperSearchQuery;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller("examSubjectPaperController")
@RequestMapping("/admin/exam-param/subjectPaper")
public class ExamSubjectPaperController extends BaseParameterController {

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private ExamSubjectPaperService examSubjectPaperService;

    @Value("${card.server}")
    private String cardServer;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, ExamSubjectSearchQuery query,
            @RequestParam(required = false) Boolean upload) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            query.setExamId(examId);
            if (upload != null) {
                if (upload.booleanValue()) {
                    query.setLibraryCountGt(0);
                } else {
                    query.setLibraryCountEqual(0);
                }
            }
            query = subjectService.findByQuery(query);
            model.addAttribute("query", query);
            model.addAttribute("upload", upload);
            model.addAttribute("subjectList", getExamSubject(examId));
            model.addAttribute("levelList", subjectService.listLevel(examId));
            model.addAttribute("categoryList", subjectService.listCategory(examId));
            model.addAttribute("cardServer", cardServer);
            return "modules/exam/param/subjectPaperList";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    @RequestMapping("/detail")
    public String detail(Model model, HttpServletRequest request, @RequestParam String subjectCode,
            @RequestParam(required = false) Boolean objective) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ExamSubject subject = subjectService.find(examId, subjectCode);
            if (subject != null) {
                List<ExamQuestion> list = new LinkedList<ExamQuestion>();
                if (objective == null || objective.booleanValue() == true) {
                    list.addAll(questionService.findByExamAndSubjectAndObjective(examId, subjectCode, true));
                }
                if (objective == null || objective.booleanValue() == false) {
                    list.addAll(questionService.findByExamAndSubjectAndObjective(examId, subjectCode, false));
                }
                model.addAttribute("questionList", list);
                model.addAttribute("subject", subject);
                model.addAttribute("objective", objective);
                model.addAttribute("subjectPaper", "1");
                return "modules/exam/param/paperDetail";
            } else {
                return "redirect:/admin/exam-param/subjectPaper";
            }
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    // 试卷题型
    @RequestMapping(value = "/examQuestionTypeEdit")
    public String examQuestionTypeEdit(Model model, HttpServletRequest request, ExamSubjectPaperSearchQuery query,
            @RequestParam(required = false) String subjectCode) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ExamSubject subject = subjectService.find(examId, subjectCode);
            // 通过考试ID获取该考试批次下所有的科目名称及科目代码
            model.addAttribute("subjectCode", subjectCode);
            model.addAttribute("subjectName", subject.getName());
            query.setExamId(examId);
            query.setCode(subjectCode);
            query = examSubjectPaperService.findByQuery(query);
            String objectiveNumber = examSubjectPaperService.getMainNumbersByExamIdAndCodeAndType(examId, subjectCode,
                    true);
            String subjectiveNumber = examSubjectPaperService.getMainNumbersByExamIdAndCodeAndType(examId, subjectCode,
                    false);
            model.addAttribute("query", query);
            model.addAttribute("objectiveNumber", objectiveNumber);
            model.addAttribute("subjectiveNumber", subjectiveNumber);
        }
        return "modules/exam/param/subjectPaperForm";
    }

    // 新增 或 修改
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public String saveSubjectPaper(ExamSubjectPaper examPaper, HttpServletRequest request) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            examPaper.setExamId(examId);

            // 后商定根据页面保存的情况，需要去eb_exam_question表中将起对应的数据删除。
            boolean objective = examPaper.getObjective() == 1 ? true : false;
            Long count = examSubjectPaperService.getExamSubjectPaperCountBy(examId, examPaper.getCode(),
                    examPaper.getObjective());
            if (count == 0) {
                // 当通过页面维护一个科目的客观题或主观题时，第一次进来需要删除eb_exam_question表中对应的数据
                questionService.deleteByExamAndSubjectAndObjective(examId, examPaper.getCode(), objective);
            }
            if (examPaper.getId() != null) {// 表示修改情况，将eb_exam_question表中对应的数据删除
                questionService.deleteByExamIdAndSubjectCodeAndObjectiveAndMainNumber(examPaper.getExamId(),
                        examPaper.getCode(), objective, examPaper.getMainNumber());
            }
            examSubjectPaperService.save(examPaper);
            return "redirect:/admin/exam-param/subjectPaper/examQuestionTypeEdit?subjectCode=" + examPaper.getCode();
        }
        return null;
    }

    // 删除
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject deleteMarker(@RequestParam Integer id, @RequestParam boolean objective) {
        JSONObject obj = new JSONObject();
        // 将question表中的数据也一并删除
        ExamSubjectPaper examSubjectPaper = examSubjectPaperService.getExamSubjectPaperById(id);
        if (examSubjectPaper != null) {

            double score = questionService.scoreByExamIdAndSubjectCodeAndMainNumberAndObjective(
                    examSubjectPaper.getExamId(), examSubjectPaper.getCode(), examSubjectPaper.getMainNumber(),
                    objective);

            questionService.deleteByExamIdAndSubjectCodeAndObjectiveAndMainNumber(examSubjectPaper.getExamId(),
                    examSubjectPaper.getCode(), objective, examSubjectPaper.getMainNumber());
            // 并更新subject表中的分数
            ExamSubject subject = subjectService.find(examSubjectPaper.getExamId(), examSubjectPaper.getCode());
            // double score = examSubjectPaper.getTotalScore();
            subject.setTotalScore(subject.getTotalScore() - score);
            if (objective) {
                subject.setObjectiveScore(subject.getObjectiveScore() - score);
            } else {
                subject.setSubjectiveScore(subject.getSubjectiveScore() - score);
            }
            subjectService.save(subject);
            examSubjectPaperService.deleteById(id);
            obj.accumulate("success", true);
        } else {
            obj.accumulate("success", false);
            obj.accumulate("msg", "删除失败！");
        }
        return obj;
    }

    // 详细编辑 每个科目下的试卷结构(标准答案和分数)
    @RequestMapping(value = "/editPaperDetail")
    public String editPaperDetail(Model model, HttpServletRequest request, @RequestParam Integer id,
            @RequestParam String subjectCode, @RequestParam String objective) {
        int examId = getSessionExamId(request);
        if (examId > 0) {
            ExamSubject subject = subjectService.find(examId, subjectCode);
            List<ExamSubjectPaperDTO> ExamSubjectPaperDTOList = examSubjectPaperService.getExamSubjectPaper(id);
            model.addAttribute("ExamSubjectPaperDTOList", ExamSubjectPaperDTOList);
            model.addAttribute("subjectCode", subjectCode);
            model.addAttribute("subjectName", subject.getName());
            model.addAttribute("examSubjectPaperId", id);
            model.addAttribute("objective", objective);
            return "modules/exam/param/editSubjectPaperDetail";
        } else {
            return "redirect:/admin/exam/list";
        }
    }

    // 保存 详细 题型中的分数和查考答案等信息
    @RequestMapping(value = "/detailSave", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject detailSave(HttpServletRequest request) {
        JSONObject obj = new JSONObject();
        String jsonString = request.getParameter("jsonString");
        JSONObject jsonObject = JSONObject.fromObject(jsonString);
        String subjectCode = (String) jsonObject.get("subjectCode");
        int examSubjectPaperId = Integer.parseInt(jsonObject.get("examSubjectPaperId").toString());
        String tempObjective = (String) jsonObject.get("objective");
        boolean objective = "1".equals(tempObjective) ? true : false;// true 表示
                                                                     // 客观题
                                                                     // false 表示
                                                                     // 主观题
        int examId = getSessionExamId(request);
        ExamSubjectPaper examSubjectPaper = examSubjectPaperService.getExamSubjectPaperById(examSubjectPaperId);
        if (examSubjectPaper != null) {
            ExamSubject subject = subjectService.find(examId, subjectCode);
            if (subject != null) {
                // 此次编辑的题型所有的分数
                double questionTypeScroe = 0;
                List<ExamQuestion> list = new ArrayList<ExamQuestion>();
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                for (int i = 0; i < jsonArray.size(); i++) {
                    ExamQuestion examQuestion = new ExamQuestion();
                    JSONObject jo = jsonArray.getJSONObject(i);
                    int subNumber = Integer.parseInt(jo.getString("subNumber"));
                    String answer = jo.getString("answer");
                    double score = Double.parseDouble(jo.getString("score"));
                    examQuestion.setExamId(examId);
                    examQuestion.setSubjectCode(subjectCode);
                    examQuestion.setMainNumber(examSubjectPaper.getMainNumber());
                    examQuestion.setSubNumber(subNumber);
                    examQuestion.setObjective(objective);
                    examQuestion.setMainTitle(examSubjectPaper.getQuestionTypeName());
                    examQuestion.setAnswer(answer);
                    examQuestion.setTotalScore(score);
                    examQuestion.setIntervalScore(examSubjectPaper.getIntervalScore());
                    examQuestion.setFullCount(0);
                    examQuestion.setTotalCount(0);
                    examQuestion.setZeroCount(0);
                    questionTypeScroe = questionTypeScroe + score;
                    list.add(examQuestion);
                }
                if (questionTypeScroe != examSubjectPaper.getTotalScore()) {
                    obj.accumulate("success", false);
                    obj.accumulate("msg", "各项分数总和(" + examSubjectPaper.getTotalScore() + ")不等于单项题型设置的总分");
                    return obj;
                }
                // 删除question表中关于本次大题号的所有信息
                questionService.deleteByExamIdAndSubjectCodeAndObjectiveAndMainNumber(examId, subjectCode, objective,
                        examSubjectPaper.getMainNumber());
                // 获取在question表中除去本次编辑的大题号以外的分数
                double oldScore = questionService.scoreByExamIdAndSubjectCode(examId, subjectCode);
                // 批量保存question表中本次大题号的所有信息
                questionService.batchSave(list);
                // 获取（主观题或客观题）题型下所有的分数
                double objectiveScore = questionService.scoreByExamIdAndSubjectCodeAndObjective(examId, subjectCode,
                        objective);
                // 总分 = 本次分数 + 非本次分数
                subject.setTotalScore(oldScore + questionTypeScroe);
                subject.setScore(objectiveScore, objective);
                subjectService.save(subject);
                obj.accumulate("success", true);
                obj.accumulate("msg", "保存成功！");
            }
        }
        return obj;
    }

}
