package com.xydl.cac.service.impl;

import com.xydl.cac.entity.Bdz;
import com.xydl.cac.entity.Jg;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.StaticVariable;
import com.xydl.cac.repository.BdzRepository;
import com.xydl.cac.repository.JgRepository;
import com.xydl.cac.service.BdzService;
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 BdzServiceImpl implements BdzService {

    @Resource
    BdzRepository repository;
    @Resource
    JgRepository jgRepository;

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

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

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

    @Override
    public void delete(Integer id) throws Exception {
        List<Jg> jgList = jgRepository.findByBdzid(id);
        if (!CollectionUtils.isEmpty(jgList)) {
            throw new BusinessException("已被区域使用不能删除");
        }
        repository.deleteById(id);
    }
}
