package cn.com.qmth.stmms.common.controller;

import java.beans.PropertyEditorSupport;
import java.util.Date;

import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomBooleanEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
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.user.model.User;
import cn.com.qmth.stmms.biz.user.service.UserService;
import cn.com.qmth.stmms.biz.utils.ScoreCalculateUtil;
import cn.com.qmth.stmms.biz.utils.ScoreInfo;
import cn.com.qmth.stmms.common.enums.ExamSubjectStatus;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.DateUtils;

public class BaseController {

    @Autowired
    private UserService userService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamSubjectService subjectService;

    @Autowired
    private ExamQuestionService questionService;

    protected boolean checkLoginName(User user) {
        User previous = userService.findByLoginName(user.getLoginName());
        if (previous == null || (user.getId() != null && previous.getId().equals(user.getId()))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 初始化数据绑定 1. 将所有传递进来的String进行HTML编码，防止XSS攻击 2. 将字段中Date类型转换为String类型
     */
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        // String类型转换，将所有传递进来的String进行HTML编码，防止XSS攻击
        binder.registerCustomEditor(String.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                setValue(text == null ? null : StringEscapeUtils.escapeHtml4(text.trim()));
            }

            @Override
            public String getAsText() {
                Object value = getValue();
                return value != null ? value.toString() : "";
            }
        });
        // Date 类型转换
        binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                setValue(DateUtils.parseDate(text));
            }
        });
        // ExamSubjectStatus 类型转换
        binder.registerCustomEditor(ExamSubjectStatus.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                try {
                    setValue(ExamSubjectStatus.findByValue(Integer.valueOf(text)));
                } catch (Exception e) {
                    setValue(null);
                }
            }
        });
        // LibraryStatus 类型转换
        binder.registerCustomEditor(LibraryStatus.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                try {
                    setValue(LibraryStatus.findByValue(Integer.valueOf(text)));
                } catch (Exception e) {
                    setValue(null);
                }
            }
        });
        // Role 类型转换
        binder.registerCustomEditor(Role.class, new PropertyEditorSupport() {

            @Override
            public void setAsText(String text) {
                try {
                    setValue(Role.findByValue(Integer.valueOf(text)));
                } catch (Exception e) {
                    setValue(null);
                }
            }
        });

        binder.registerCustomEditor(Boolean.class, new CustomBooleanEditor(true));
    }

    protected ExamStudent saveUploadStudent(ExamStudent student) {
        if (student.isAbsent()) {
            // 缺考则强制删除评卷任务
            // libraryService.deleteByStudent(student.getId());
        } else {
            // MarkLibrary library =
            // libraryService.findByStudentId(student.getId());
            // if (library == null) {
            // Campus campus =
            // campusSerivce.findBySchoolAndName(student.getSchoolId(),
            // student.getCampusName());
            //
            // library = new MarkLibrary();
            // library.setExamId(student.getExamId());
            // library.setSubjectCode(student.getSubjectCode());
            // library.setCampusId(campus.getId());
            // library.setStudentId(student.getId());
            // library.setExamNumber(student.getExamNumber());
            // library.setPicStart(1);
            // library.setPicCount(student.getSliceCount());
            // library.setStatus(LibraryStatus.WAITING);
            // } else {
            // library.setPicCount(student.getSliceCount());
            // }
            // calculateObjectiveScore(student);
            // libraryService.save(library);
        }
        calculateObjectiveScore(student);
        ExamStudent saved = studentService.save(student);
        subjectService.updateUploadCount(student.getExamId(), student.getSubjectCode());
        return saved;
    }

    private void calculateObjectiveScore(ExamStudent student) {
        ScoreCalculateUtil util = ScoreCalculateUtil.instance(student);

        ScoreInfo info = util.calculate(
                questionService.findByExamAndSubjectAndObjective(student.getExamId(), student.getSubjectCode(), true),
                null);

        student.setObjectiveScore(info.getObjectiveScore());
        student.setScoreList(info.getScoreList(), true);
    }
}
