package cn.com.qmth.stmms.ms.marking.service;

import cn.com.qmth.stmms.ms.core.domain.InspectTask;
import cn.com.qmth.stmms.ms.core.domain.Level;
import cn.com.qmth.stmms.ms.core.domain.Paper;
import cn.com.qmth.stmms.ms.core.repository.InspectTaskRepo;
import cn.com.qmth.stmms.ms.core.repository.LevelRepo;
import cn.com.qmth.stmms.ms.core.repository.PaperRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by yuanpan on 2017/11/22.
 */
@Service
public class InspectService {

    @Autowired
    private InspectTaskRepo inspectTaskRepo;

    @Autowired
    private PaperRepo paperRepo;

    @Autowired
    private LevelRepo levelRepo;


    @Transactional
    public void inspect(InspectTask inspectTask) {

        inspectTaskRepo.save(inspectTask);

        Paper paper = inspectTask.getPaper();

        List<InspectTask> inspectTasks = inspectTaskRepo.findByPaperIdAndInspectRangeId(paper.getId(), inspectTask.getInspectRangeId());
        int unScoreCount = 0;
        double sum = 0;
        for (InspectTask task : inspectTasks) {

            if (task.getScore() == null) {
                unScoreCount++;
            } else {
                sum += task.getScore();
            }
        }
        if (unScoreCount < 1) {
            //计算平均分
            double avg = sum / inspectTasks.size();
            //计算平均分所在的档位
            Paper p = paperRepo.getOne(paper.getId());
            p.setInspectRange(inspectTask.getInspectRangeId());//也记录一下是哪一次的复评范围决定的最终分
            p.setInspectScore((double) Math.round(avg));
            p.setInspectLevel(getLevel(paper.getWorkId(), p.getInspectScore()));
            paperRepo.save(p);
        }
    }

    public String getLevel(Long workId, double score) {
        List<Level> levels = levelRepo.findByWorkId(workId);
        for (Level l : levels) {
            if (l.getMaxScore() >= score && score >= l.getMinScore()) {
                return l.getCode();
            }
        }

        return null;
    }
}
