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

import java.util.List;

import javax.servlet.http.HttpServletRequest;

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

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 org.springframework.web.servlet.mvc.support.RedirectAttributes;

import cn.com.qmth.stmms.biz.exam.model.Exam;
import cn.com.qmth.stmms.biz.exam.model.ExamSubject;
import cn.com.qmth.stmms.biz.exam.service.ExamService;
import cn.com.qmth.stmms.biz.exam.service.ExamSubjectService;
import cn.com.qmth.stmms.biz.exam.service.query.ExamSubjectSearchQuery;
import cn.com.qmth.stmms.biz.mark.model.PictureConfigItem;
import cn.com.qmth.stmms.common.annotation.Logging;
import cn.com.qmth.stmms.common.annotation.RoleRequire;
import cn.com.qmth.stmms.common.enums.LogType;
import cn.com.qmth.stmms.common.enums.Role;

@Controller
@RequestMapping("/admin/exam/subject")
public class SubjectController extends BaseExamController {

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamService examService;

    @RequestMapping("/list")
    @ResponseBody
    public JSONArray list(HttpServletRequest request, @RequestParam Integer examId) {
        List<ExamSubject> list = subjectService.list(examId);
        JSONArray array = new JSONArray();
        for (ExamSubject subject : list) {
            JSONObject obj = new JSONObject();
            obj.accumulate("code", subject.getCode());
            obj.accumulate("name", subject.getName());
            obj.accumulate("level", StringUtils.trimToEmpty(subject.getLevel()));
            obj.accumulate("category", StringUtils.trimToEmpty(subject.getCategory()));
            array.add(obj);
        }
        return array;
    }

    @RequestMapping("/edit")
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String edit(HttpServletRequest request, @RequestParam String code, Model model,
            RedirectAttributes redirectAttributes, ExamSubjectSearchQuery query,
            @RequestParam(required = false) String queryCode, @RequestParam(required = false) Boolean upload) {
        ExamSubject subject = subjectService.find(getSessionExamId(request), code);
        if (subject == null) {
            addMessage(redirectAttributes, "科目代码有误，科目不存在");
            return "redirect:/admin/exam/paper";
        }
        model.addAttribute("subject", subject);
        model.addAttribute("pictureConfig", buildPictureConfig(subject.getSheetConfig()));
        model.addAttribute("passScore", subject.getPassScore());
        model.addAttribute("excellentScore", subject.getExcellentScore());
        Exam exam = examService.findById(subject.getExamId());
        model.addAttribute("examType", exam.getType());
        query.setCode(queryCode);
        model.addAttribute("query", query);
        model.addAttribute("upload", upload);
        return "modules/exam/subjectEdit";
    }

    @Logging(menu = "科目设置", type = LogType.UPDATE)
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @RoleRequire(Role.SCHOOL_ADMIN)
    public String save(RedirectAttributes redirectAttributes,HttpServletRequest request, ExamSubject subject, Model model, @RequestParam String picList,
            @RequestParam(required = false) Double passScore, @RequestParam(required = false) Double excellentScore,
            ExamSubjectSearchQuery query, @RequestParam(required = false) String queryCode,
            @RequestParam(required = false) Boolean upload) {
    	String u = upload == null ? "" : upload.toString();
    	String t = query.getTotalScoreNotEqual() == null ? "" : query.getTotalScoreNotEqual().toString();
    	String url="redirect:/admin/exam/paper?code=" + queryCode + "&pageNumber=" + query.getPageNumber() + "&category="
                + query.getCategory() + "&level=" + query.getLevel() + "&upload=" + u + "&totalScoreNotEqual=" + t;
        ExamSubject previous = subjectService.find(getSessionExamId(request), subject.getCode());
        if(previous==null) {
        	addMessage(redirectAttributes, "科目代码有误，科目不存在");
        	return url;
        }
        if (previous != null && StringUtils.isNotBlank(picList)) {
            String sheetConfig = StringEscapeUtils.unescapeHtml(picList);
            JSONArray array = JSONArray.fromObject(sheetConfig);
            List<PictureConfigItem> list = JSONArray.toList(array, new PictureConfigItem(), new JsonConfig());
            previous.setSheetConfig(list == null ? null : StringUtils.join(list, PictureConfigItem.DB_ITEM_JOINER));
        }
        JSONObject sasConfig = new JSONObject();
        sasConfig.accumulate("passScore", passScore);
        sasConfig.accumulate("excellentScore", excellentScore);
        previous.setSasConfig(sasConfig.toString());
        previous.setEnableSplit(subject.getEnableSplit());
        previous.setAutoScroll(subject.getAutoScroll());
        previous.setDisplayQuestionName(subject.getDisplayQuestionName() == null ? false : subject
                .getDisplayQuestionName());
        subjectService.save(previous);
        model.addAttribute("message", "修改成功");
       
        return url;
    }
}
