package cn.com.qmth.stmms.biz.exam.service.impl;

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

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

import cn.com.qmth.stmms.biz.exam.dao.MarkLevelDao;
import cn.com.qmth.stmms.biz.exam.model.MarkLevel;
import cn.com.qmth.stmms.biz.exam.model.MarkStep;
import cn.com.qmth.stmms.biz.exam.service.MarkLevelService;
import cn.com.qmth.stmms.biz.exam.service.MarkStepService;

@Service
public class MarkLevelServiceImpl implements MarkLevelService {

    @Autowired
    private MarkLevelDao markLevelDao;

    @Autowired
    private MarkStepService markStepService;

    @Transactional
    public MarkLevel save(MarkLevel markLevel) {
        return markLevelDao.save(markLevel);
    }

    @Transactional
    public void delete(MarkLevel markLevel) {
        markLevelDao.delete(markLevel);
    }

    public List<MarkLevel> findByStep(MarkStep step) {
        if (step != null) {
            List<MarkLevel> mList = markLevelDao.findByBlockIdAndStepNumber(step.getBlockId(),
                    step.getNumber());
            for (MarkLevel markLevel : mList) {
                buildScoreList(markLevel);
            }
            return mList;
        }
        return null;
    }

    public List<MarkLevel> findByBlockIdAndStepNumber(int blockId, int stepNumber) {
        return markLevelDao.findByBlockIdAndStepNumber(blockId, stepNumber);
    }

    @Transactional
    public void deleteByBlockIdAndStepNumber(int blockId, int stepNumber) {
        markLevelDao.deleteByBlockIdAndStepNumber(blockId, stepNumber);
    }

    @Transactional
    public void deleteByBlockId(int blockId) {
        markLevelDao.deleteByBlockId(blockId);
    }

    private MarkLevel buildScoreList(MarkLevel markLevel) {
        List<MarkStep> mList = markStepService.findByBlockId(markLevel.getBlockId());
        double[] scoreArray = null;
        List<Double> scoreList = new ArrayList<Double>();
        for (MarkStep markStep : mList) {
            if (markStep.getNumber().intValue() == markLevel.getStepNumber().intValue()) {
                scoreArray = markStep.getScoreArray();
                double min = markLevel.getMin();
                double max = markLevel.getMax();
                for (int i = 0; i < scoreArray.length; i++) {
                    if (scoreArray[i] >= min && scoreArray[i] <= max) {
                        scoreList.add(scoreArray[i]);
                    }
                }
                double[] score = new double[scoreList.size()];
                for (int i = 0; i < scoreList.size(); i++) {
                    score[i] = scoreList.get(i);
                }
                markLevel.setScoreList(score);
            }
        }
        return markLevel;
    }
}
