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

import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import cn.com.qmth.stmms.admin.utils.SessionExamUtils;
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.mark.model.PictureConfigItem;
import cn.com.qmth.stmms.common.controller.BaseController;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.ExamType;
import net.sf.json.JSONObject;

public class BaseExamController extends BaseController {

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

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamService examService;

    protected Integer getSessionExamId(HttpServletRequest request) {
        return SessionExamUtils.getExamId(request);
    }
    
    protected void errMessage(String message, HttpServletResponse response) {
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        PrintWriter writer = null;
        JSONObject obj = new JSONObject();
        obj.accumulate("message", message);
        try {
            writer = response.getWriter();
            writer.write(obj.toString());

        } catch (IOException e) {
			throw new RuntimeException(e);
		} finally {
            IOUtils.closeQuietly(writer);
        }
    }
    

    /**
     * 添加Flash消息
     *
     * @param messages
     *            消息
     */
    protected void addMessage(RedirectAttributes redirectAttributes, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
    }
    
    protected void addErrMessage(RedirectAttributes redirectAttributes,Throwable e, String... messages) {
        StringBuilder sb = new StringBuilder();
        for (String message : messages) {
            sb.append(message).append(messages.length > 1 ? "<br/>" : "");
        }
        redirectAttributes.addFlashAttribute("message", sb.toString());
        log.error(sb.toString(),e);
    }

    protected List<Exam> getExamList(WebUser wu, ExamType type) {
        return examService.findBySchoolIdAndTypeAndStatus(wu.getUser().getSchoolId(), type);
    }

    protected List<Exam> getExamList(WebUser wu) {
        return examService.findBySchoolId(wu.getUser().getSchoolId());
    }

    protected List<ExamSubject> getExamSubject(Integer examId, WebUser wu) {
        List<ExamSubject> list = new LinkedList<ExamSubject>();
        if (wu.isSchoolAdmin()) {
            list = subjectService.list(examId);
        } else if (wu.isSubjectHeader() || wu.isInspector() || wu.isSchoolViewer()) {
            list.addAll(subjectService.list(examId, wu.getSubjectCodeSet()));
        }
        return list;
    }

    protected boolean subjectCheck(String subjectCode, WebUser wu) {
        if (wu.isSubjectHeader() || wu.isInspector() || wu.isSchoolViewer()) {
            for (String code : wu.getSubjectCodeSet()) {
                if (code.equalsIgnoreCase(subjectCode)) {
                    return true;
                }
            }
            return false;
        } else {
            return true;
        }
    }

    protected String buildPictureConfig(String sheetConfig) {
        if (StringUtils.isNotBlank(sheetConfig)) {
            try {
                ObjectMapper mapper = new ObjectMapper();
                return mapper.writeValueAsString(PictureConfigItem.parse(sheetConfig));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return "";
    }

}
