package com.xydl.cac.service.impl;

import com.xydl.cac.entity.Lx;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.LxRepository;
import com.xydl.cac.service.LxService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class LxServiceImpl implements LxService {

    @Resource
    LxRepository repository;

    @Override
    public List<Lx> listAll() {
        return repository.findAll();
    }

    @Override
    public Lx add(Lx item) throws Exception {
        item.setId(null);
        List<Lx> list = repository.findByMc(item.getMc());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该名称已被使用");
        }
        return repository.save(item);
    }

    @Override
    public void update(Lx item) throws Exception {
        List<Lx> list = repository.findByMcAndIdIsNot(item.getMc(), item.getId());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该名称已被使用");
        }
        repository.save(item);
    }

    @Override
    public void delete(Integer id) {
        repository.deleteById(id);
    }
}
