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

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.MarkStepDao;
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 MarkStepServiceImpl implements MarkStepService {

    @Autowired
    private MarkStepDao markStepDao;

    @Autowired
    private MarkLevelService markLevelService;

    @Transactional
    public MarkStep save(MarkStep step) {
        step.setHasLevel(step.getMarkLevelList() != null && step.getMarkLevelList().size() > 0);
        if (step.getMarkLevelList() != null) {
            markLevelService.deleteByBlockIdAndStepNumber(step.getBlockId(), step.getNumber());
            int number = 0;
            for (MarkLevel level : step.getMarkLevelList()) {
                level.setBlockId(step.getBlockId());
                level.setStepNumber(step.getNumber());
                level.setNumber(++number);
                markLevelService.save(level);
            }
        }
        return markStepDao.save(step);
    }

    public MarkStep findById(int id) {
        MarkStep markStep = markStepDao.findOne(id);
        return buildMarkStep(markStep);
    }

    @Transactional
    public void deleteById(int id) {
        markStepDao.delete(id);
    }

    @Transactional
    public void delete(MarkStep markStep) {
        markStepDao.delete(markStep);
    }

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

    public List<MarkStep> findByBlockId(int blockId) {
        return findByBlockId(blockId, false);
    }

    public List<MarkStep> findByBlockId(int blockId, boolean withLevel) {
        List<MarkStep> list = markStepDao.findByBlockId(blockId);
        if (withLevel && list != null) {
            for (MarkStep step : list) {
                if (step.isHasLevel()) {
                    step.setMarkLevelList(markLevelService.findByStep(step));
                }
            }
        }
        return list;
    }

    private MarkStep buildMarkStep(MarkStep markStep) {
        List<MarkLevel> markLevelList = markLevelService.findByStep(markStep);
        markStep.setMarkLevelList(markLevelList);
        return markStep;
    }
}
