package cn.com.qmth.stmms.biz.mark.service.Impl;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.qmth.stmms.biz.campus.model.Campus;
import cn.com.qmth.stmms.biz.campus.service.CampusService;
import cn.com.qmth.stmms.biz.exam.model.ExamQuestion;
import cn.com.qmth.stmms.biz.exam.model.ExamStudent;
import cn.com.qmth.stmms.biz.exam.model.MarkGroup;
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.MarkGroupService;
import cn.com.qmth.stmms.biz.exam.service.MarkerService;
import cn.com.qmth.stmms.biz.mark.model.ArbitrateHistory;
import cn.com.qmth.stmms.biz.mark.model.ArbitrationDTO;
import cn.com.qmth.stmms.biz.mark.model.MarkLibrary;
import cn.com.qmth.stmms.biz.mark.model.MarkSpecialTag;
import cn.com.qmth.stmms.biz.mark.model.MarkStepDTO;
import cn.com.qmth.stmms.biz.mark.model.MarkTrack;
import cn.com.qmth.stmms.biz.mark.model.PictureConfigItem;
import cn.com.qmth.stmms.biz.mark.model.SpecialTagDTO;
import cn.com.qmth.stmms.biz.mark.model.Task;
import cn.com.qmth.stmms.biz.mark.model.TrackDTO;
import cn.com.qmth.stmms.biz.mark.query.MarkLibrarySearchQuery;
import cn.com.qmth.stmms.biz.mark.service.MarkLibraryService;
import cn.com.qmth.stmms.biz.mark.service.MarkSpecialTagService;
import cn.com.qmth.stmms.biz.mark.service.MarkTrackService;
import cn.com.qmth.stmms.biz.mark.service.TaskService;
import cn.com.qmth.stmms.common.enums.LibraryStatus;
import cn.com.qmth.stmms.common.utils.PictureUrlBuilder;

/**
 * 评卷任务服务实现
 * 
 * @author LS
 * 
 */
@Service("taskService")
public class TaskServiceImpl implements TaskService {

    private static Logger log = LoggerFactory.getLogger(TaskServiceImpl.class);

    @Autowired
    private MarkLibraryService libraryService;

    @Autowired
    private ExamStudentService studentService;

    @Autowired
    private ExamQuestionService questionService;

    @Autowired
    private MarkTrackService trackService;

    @Autowired
    private MarkGroupService groupService;

    @Autowired
    private MarkSpecialTagService markSpecialTagService;

    @Autowired
    private CampusService campusService;

    @Autowired
    private MarkerService markerService;

    @Override
    public List<Task> findByQuery(MarkLibrarySearchQuery query) {
        List<Task> list = new LinkedList<Task>();
        query = libraryService.findByQuery(query);
        if (query.getCurrentCount() > 0) {
            for (MarkLibrary library : query.getResult()) {
                list.add(build(library));
            }
        }
        return list;
    }

    @Override
    public Task build(ArbitrateHistory history, MarkGroup group) {
        ExamStudent student = studentService.findByExamIdAndExamNumber(history.getExamId(), history.getExamNumber());
        List<MarkLibrary> libraryList = libraryService.findByStudentAndGroup(student.getId(), group.getNumber());
        Integer campusId = libraryList.get(0).getCampusId();

        Task task = new Task();
        task.setExist(true);
        task.setStudentId(student.getExamNumber());
        task.setLibraryId(history.getId());
        task.setMarkStepList(buildMarkStep(group, null));
        task.setPictureUrls(PictureUrlBuilder.getSliceUrls(student.getExamId(), campusId, student.getSubjectCode(),
                student.getExamNumber(), student.getSliceCount()));
        task.setPictureConfig(group.getPictureConfigList());
        task.setSheetUrls(PictureUrlBuilder.getSheetUrls(student.getExamId(), campusId, student.getSubjectCode(),
                student.getExamNumber(), student.getSheetCount()));
        task.setAnswerUrl(PictureUrlBuilder.getAnswerUrl(student.getExamId(), student.getSubjectCode()));
        task.setPaperUrl(PictureUrlBuilder.getPaperUrl(student.getExamId(), student.getSubjectCode()));
        task.setObjectiveScore(student.getObjectiveScore() != null ? student.getObjectiveScore() : 0);
        // 构造仲裁信息
        List<ArbitrationDTO> list = new ArrayList<ArbitrationDTO>();
        for (MarkLibrary library : libraryList) {
            if (library.getStatus() != LibraryStatus.WAITING) {
                list.add(new ArbitrationDTO(library, markerService.findById(library.getMarkerId())));
            }
        }
        task.setArbitrationList(list);
        // 回评状态下的打分信息
        if (history.getTotalScore() != null) {
            task.setTotalScore(history.getTotalScore());
        }
        if (history.getScoreList() != null) {
            task.setScoreList(history.getScoreList());
        }
        return task;
    }

    @Override
    public Task build(MarkLibrary library) {
        ExamStudent student = studentService.findByExamIdAndExamNumber(library.getExamId(), library.getExamNumber());
        MarkGroup group = groupService.findOne(library.getExamId(), library.getSubjectCode(), library.getGroupNumber());
        Task task = new Task();
        task.setTagList(getMarkSpecialTagList(library.getId()));
        task.setExist(true);
        task.setStudentId(library.getExamNumber());
        task.setLibraryId(library.getId());
        task.setMarkStepList(buildMarkStep(group, library.getId()));
        task.setPictureUrls(PictureUrlBuilder.getSliceUrls(library.getExamId(), library.getCampusId(),
                library.getSubjectCode(), library.getExamNumber(), student.getSliceCount()));
        task.setPictureConfig(group.getPictureConfigList());
        task.setSheetUrls(PictureUrlBuilder.getSheetUrls(library.getExamId(), library.getCampusId(),
                library.getSubjectCode(), library.getExamNumber(), student.getSheetCount()));
        task.setAnswerUrl(PictureUrlBuilder.getAnswerUrl(library.getExamId(), library.getSubjectCode()));
        task.setPaperUrl(PictureUrlBuilder.getPaperUrl(library.getExamId(), library.getSubjectCode()));
        task.setObjectiveScore(student != null ? student.getObjectiveScore() : 0);
        task.setMarkTime(library.getMarkerTime());
        task.setTags(library.getTags());
        if (library.getMarkerId() != null) {
            task.setMarkId(library.getMarkerId());
        }
        if (library.getMarkerScore() != null) {
            task.setTotalScore(library.getMarkerScore());
        }
        if (library.getMarkerScoreList() != null) {
            task.setScoreList(library.getMarkerScoreList());
        }
        // if (library.getStatus() == LibraryStatus.BACKED &&
        // library.getMarkerId() != null) {
        // task.setBack(true);
        // }
        return task;
    }

    private List<MarkStepDTO> buildMarkStep(MarkGroup group, Integer libraryId) {
        List<MarkStepDTO> list = new LinkedList<MarkStepDTO>();
        List<ExamQuestion> sList = questionService.findByExamAndSubjectAndObjectiveAndMainNumber(group.getExamId(),
                group.getSubjectCode(), false, group.getNumber());
        int number = 0;
        for (ExamQuestion question : sList) {
            number++;

            MarkStepDTO step = new MarkStepDTO();
            step.setQuestionNumber(question.getQuestionNumber());
            step.setBlockId(question.getMainNumber());
            step.setNumber(number);
            step.setTitle(question.getMainTitle() + "-" + question.getSubNumber());
            step.setTotalScore(question.getTotalScore());
            step.setDefaultScore(0d);
            step.setHasLevel(false);
            step.setMax(question.getTotalScore());
            step.setMin(0d);
            step.setInterval(question.getIntervalScore());
            step.setScoreList(question.getScoreListArray());
            if (libraryId != null) {
                // 增加阅卷轨迹列表获取
                addTrack(step, question, trackService.findByLibraryId(libraryId));
            }
            list.add(step);
        }
        return list;
    }

    private void addTrack(MarkStepDTO step, ExamQuestion question, List<MarkTrack> trackList) {
        String questionNumber = question.getQuestionNumber();
        for (MarkTrack track : trackList) {
            if (track.getQuestionNumber().equals(questionNumber)) {
                step.addTrack(new TrackDTO(track));
            }
        }
    }

    public SpecialTagDTO[] getMarkSpecialTagList(Integer libraryId) {
        SpecialTagDTO[] specialTags = null;
        List<MarkSpecialTag> list = markSpecialTagService.findByLibraryId(libraryId);
        if (!list.isEmpty()) {
            specialTags = new SpecialTagDTO[list.size()];
            for (int i = 0; i < list.size(); i++) {
                SpecialTagDTO specialTagDTO = new SpecialTagDTO();
                specialTagDTO.setTagName(list.get(i).getTagName());
                specialTagDTO.setPositionX(list.get(i).getPositionX());
                specialTagDTO.setPositionY(list.get(i).getPositionY());
                specialTags[i] = specialTagDTO;
            }
        }
        return specialTags;
    }

    @Override
    public Task build(Integer studentId) {
        ExamStudent student = studentService.findById(studentId);
        Task task = new Task();
        task.setExist(true);
        task.setStudentId(student.getExamNumber());
        task.setLibraryId(studentId);
        task.setMarkStepList(buildMarkStep(student));
        Campus campus = campusService.findBySchoolAndName(student.getSchoolId(), student.getCampusName());
        task.setPictureUrls(PictureUrlBuilder.getSliceUrls(student.getExamId(), campus.getId(),
                student.getSubjectCode(), student.getExamNumber(), student.getSliceCount()));
        task.setPictureConfig(buildPictureConfig(student.getSliceCount()));
        task.setSheetUrls(PictureUrlBuilder.getSheetUrls(student.getExamId(), campus.getId(), student.getSubjectCode(),
                student.getExamNumber(), student.getSheetCount()));
        task.setAnswerUrl(PictureUrlBuilder.getAnswerUrl(student.getExamId(), student.getSubjectCode()));
        task.setPaperUrl(PictureUrlBuilder.getPaperUrl(student.getExamId(), student.getSubjectCode()));
        task.setObjectiveScore(student != null ? student.getObjectiveScore() : 0);
        task.setBack(true);

        return task;
    }

    private List<PictureConfigItem> buildPictureConfig(int picCount) {
        List<PictureConfigItem> list = new LinkedList<PictureConfigItem>();
        for (int i = 1; i <= picCount; i++) {
            list.add(new PictureConfigItem(String.valueOf(i)));
        }
        return list;
    }

    private List<MarkStepDTO> buildMarkStep(ExamStudent student) {
        List<MarkStepDTO> list = new LinkedList<MarkStepDTO>();
        List<ExamQuestion> sList = questionService.findByExamAndSubjectAndObjective(student.getExamId(),
                student.getSubjectCode(), false);
        int number = 0;
        for (ExamQuestion question : sList) {
            number++;

            MarkStepDTO step = new MarkStepDTO();
            step.setQuestionNumber(question.getQuestionNumber());
            step.setBlockId(question.getMainNumber());
            step.setNumber(number);
            step.setTitle(question.getMainTitle() + "-" + question.getSubNumber());
            step.setTotalScore(question.getTotalScore());
            step.setDefaultScore(0d);
            step.setHasLevel(false);
            step.setMax(question.getTotalScore());
            step.setMin(0d);
            step.setInterval(question.getIntervalScore());
            step.setScoreList(question.getScoreListArray());
            // 增加阅卷轨迹列表获取
            addTrack(step, question, trackService.findByStudentId(student.getId()));
            list.add(step);
        }
        return list;
    }

    @Transactional
    @Override
    public boolean submitByStudent(Task task) {
        if (task == null) {
            return false;
        }
        try {
            List<MarkLibrary> libraries = libraryService.findByStudentId(task.getLibraryId());
            int start = 0;
            int end = 0;
            for (int i = 0; i < libraries.size(); i++) {
                MarkLibrary library = libraries.get(i);
                Task stepTask = new Task();
                stepTask.setProblem(task.isProblem());
                stepTask.setBack(task.isBack());
                stepTask.setLibraryId(library.getId());
                stepTask.setHeaderId(task.getHeaderId());
                stepTask.setTags(task.getTags());
                List<ExamQuestion> sList = questionService.findByExamAndSubjectAndObjectiveAndMainNumber(
                        library.getExamId(), library.getSubjectCode(), false, library.getGroupNumber());
                if (start == end) {
                    end = end + sList.size() * 2 - 1;
                } else {
                    start = end + 1;
                    end = start + sList.size() * 2 - 1;
                }
                String scoreList = task.getScoreList().substring(start, end);
                stepTask.setHeaderScoreList(scoreList);
                String[] scores = scoreList.split(",");
                double totalScore = 0;
                for (String score : scores) {
                    totalScore = totalScore + Double.parseDouble(score);
                }
                stepTask.setHeaderScore(totalScore);
                // submitTask(stepTask);
            }
            return true;
        } catch (Exception e) {
            log.error("task submit faile", e);
            return false;
        }
    }

}
