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

import java.text.DecimalFormat;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

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

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.model.MarkGroup;
import cn.com.qmth.stmms.biz.exam.model.Marker;
import cn.com.qmth.stmms.biz.exam.service.ExamStudentService;
import cn.com.qmth.stmms.biz.exam.service.MarkGroupService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.lock.LockService;
import cn.com.qmth.stmms.biz.mark.model.TrialHistory;
import cn.com.qmth.stmms.biz.mark.model.TrialLibrary;
import cn.com.qmth.stmms.biz.mark.query.TrialLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkService;
import cn.com.qmth.stmms.biz.mark.service.TrialService;
import cn.com.qmth.stmms.common.auth.annotation.RoleRequire;
import cn.com.qmth.stmms.common.domain.WebUser;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.enums.LockType;
import cn.com.qmth.stmms.common.enums.MarkStatus;
import cn.com.qmth.stmms.common.enums.Role;
import cn.com.qmth.stmms.common.utils.DateUtils;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;
import cn.com.qmth.stmms.common.utils.RequestUtils;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Controller("trialController")
@RequestMapping("/admin/exam/trial")
public class TrialController extends BaseExamController {

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

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private TrialService trialService;

    @Autowired
    private MarkService markService;

    @Autowired
    private MarkerService markerService;

    @Autowired
    private LockService lockService;

    @Value("${slice.image.server}")
    private String sliceServer;

    @RequestMapping
    public String list(Model model, HttpServletRequest request, TrialLibrarySearchQuery query,
            @RequestParam(required = false) LibraryStatus status) {
        int examId = getSessionExamId(request);
        WebUser wu = RequestUtils.getWebUser(request);
        List<ExamSubject> subjectList = getExamSubject(examId, wu);
        if (subjectList.isEmpty()) {
            return "redirect:/admin/exam/mark";
        }
        query.setExamId(examId);
        if (query.getSubjectCode() == null && !subjectList.isEmpty()) {
            query.setSubjectCode(subjectList.get(0).getCode());
        }
        subjectFilter(query, wu);
        List<MarkGroup> groupList = groupService.findByExamAndSubjectAndStatus(examId, query.getSubjectCode(),
                MarkStatus.TRIAL);
        if (!groupList.isEmpty()) {
            if (query.getGroupNumber() == null) {
                query.setGroupNumber(groupList.get(0).getNumber());
            }
            query.orderById();
            query = trialService.findLibrary(query);
            for (TrialLibrary library : query.getResult()) {
                library.setMarkCount(trialService.countHistory(library.getId()));
            }
            model.addAttribute("group",
                    groupService.findOne(query.getExamId(), query.getSubjectCode(), query.getGroupNumber()));
        }
        model.addAttribute("query", query);
        model.addAttribute("subjectList", getExamSubject(examId, wu));
        model.addAttribute("groupList", groupList);
        return "modules/exam/trialList";
    }

    @RequestMapping(value = "/reset", method = RequestMethod.POST)
    @ResponseBody
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER })
    public JSONObject reset(HttpServletRequest request, @RequestParam Integer libraryId) {
        JSONObject obj = new JSONObject();
        int examId = getSessionExamId(request);
        TrialLibrary library = trialService.findLibrary(libraryId);
        if (library != null) {
            if (library.getExamId().equals(examId)
                    && subjectCheck(library.getSubjectCode(), RequestUtils.getWebUser(request))) {
                try {
                    lockService.watch(LockType.GROUP, library.getExamId(), library.getSubjectCode(),
                            library.getGroupNumber());
                    lockService.waitlock(LockType.TRIAL_LIBRARY, library.getId());
                    if (markService.resetLibrary(library)) {
                        obj.accumulate("success", true);
                    } else {
                        obj.accumulate("success", false);
                        obj.accumulate("message", "无法打回该评卷任务");
                    }
                } catch (Exception e) {
                    log.error("back trial library error", e);
                    obj.accumulate("success", false);
                    obj.accumulate("message", "无法打回该评卷任务");
                } finally {
                    lockService.unlock(LockType.TRIAL_LIBRARY, library.getId());
                    lockService.unwatch(LockType.GROUP, library.getExamId(), library.getSubjectCode(),
                            library.getGroupNumber());
                }
            } else {
                obj.accumulate("success", false);
                obj.accumulate("message", "没有操作该评卷任务的权限");
            }
        } else {
            obj.accumulate("success", false);
            obj.accumulate("message", "该评卷任务不存在");
        }
        return obj;
    }

    @RequestMapping(value = "/detail")
    @ResponseBody
    @RoleRequire({ Role.SCHOOL_ADMIN, Role.SUBJECT_HEADER })
    public JSONObject detail(HttpServletRequest request, @RequestParam Integer libraryId) {
        JSONObject obj = new JSONObject();
        TrialLibrary library = trialService.findLibrary(libraryId);
        if (library != null) {
            ExamStudent student = studentService.findById(library.getStudentId());
            MarkGroup group = groupService.findOne(library.getExamId(), library.getSubjectCode(),
                    library.getGroupNumber());
            if (group != null && student != null) {
                obj.accumulate("success", true);
                // 裁切图配置
                obj.accumulate("imageServer", sliceServer);
                obj.accumulate("urls", PictureUrlBuilder.getSliceUrls(library.getExamId(), library.getCampusId(),
                        library.getSubjectCode(), library.getExamNumber(), student.getSliceCount()));
                obj.accumulate("pictureConfig", group.getPictureConfigList());
                // 评卷记录集合
                JSONArray array = new JSONArray();
                List<TrialHistory> list = trialService.findHistory(libraryId);
                DecimalFormat format = new DecimalFormat("###.##");
                for (TrialHistory history : list) {
                    Marker marker = markerService.findById(history.getMarkerId());
                    JSONObject item = new JSONObject();
                    item.accumulate("loginName", marker != null ? marker.getLoginName() : "");
                    item.accumulate("name", marker != null ? marker.getName() : "");
                    item.accumulate("score", format.format(history.getMarkerScore()));
                    item.accumulate("time", DateUtils.formatDateTime(history.getMarkerTime()));
                    array.add(item);
                }
                obj.accumulate("historyList", array);
            }
        }
        return obj;
    }

}
