package com.qxgmat.service.inline;

import com.github.pagehelper.Page;
import com.nuliji.tools.AbstractService;
import com.nuliji.tools.exception.ParameterException;
import com.nuliji.tools.exception.SystemException;
import com.qxgmat.data.dao.ExerciseStructMapper;
import com.qxgmat.data.dao.entity.ExerciseStruct;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.List;

@Service
public class ExerciseStructService extends AbstractService {
    private static final Logger logger = LoggerFactory.getLogger(ExerciseStructService.class);

    @Resource
    private ExerciseStructMapper exerciseStructMapper;

    @Cacheable(value = "exercise_struct")
    public List<ExerciseStruct> all(){
        return select(exerciseStructMapper);
    }

    @CacheEvict(value="exercise_struct",allEntries=true)
    public ExerciseStruct add(ExerciseStruct struct){
        if(struct.getParentId() > 0){
            ExerciseStruct parent = get(struct.getParentId());
            struct.setLevel(parent.getLevel()+1);
        }else{
            struct.setLevel(1);
        }
        int result = insert(exerciseStructMapper, struct);
        struct = one(exerciseStructMapper, struct.getId());
        if(struct == null){
            throw new SystemException("添加失败");
        }
        return struct;
    }

    @CacheEvict(value="exercise_struct",allEntries=true)
    public ExerciseStruct edit(ExerciseStruct struct){
        ExerciseStruct in = one(exerciseStructMapper, struct.getId());
        if(in == null){
            throw new ParameterException("层级不存在");
        }
        if (struct.getParentId() > 0){
            ExerciseStruct parent = get(struct.getParentId());
            struct.setLevel(parent.getLevel()+1);
        }else{
            struct.setLevel(1);
        }
        int result = update(exerciseStructMapper, struct);
        return struct;
    }

    public boolean delete(Number id){
        ExerciseStruct in = one(exerciseStructMapper, id);
        if(in == null){
            throw new ParameterException("层级不存在");
        }
        int result = delete(exerciseStructMapper, id);
        return result > 0;
    }

    public ExerciseStruct get(Number id){
        ExerciseStruct in = one(exerciseStructMapper, id);

        if(in == null){
            throw new ParameterException("层级不存在");
        }
        return in;
    }

    public Page<ExerciseStruct> select(int page, int pageSize){
        return select(exerciseStructMapper, page, pageSize);
    }

    public List<ExerciseStruct> select(Collection ids){
        return select(exerciseStructMapper, ids);
    }

}
