package com.xydl.cac.service.impl;

import com.xydl.cac.entity.IcdTransform;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.IcdTransformRepository;
import com.xydl.cac.service.IcdTransformService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class IcdTransformServiceImpl implements IcdTransformService {

    @Resource
    IcdTransformRepository transformRepository;


    @Override
    @CacheEvict(cacheNames = {"listTransform"}, allEntries = true)
    public IcdTransform addTransform(IcdTransform icdTransform) throws Exception {
        icdTransform.setId(null);
        List<IcdTransform> byRptFrom = transformRepository.findByRptFrom(icdTransform.getRptFrom());
        if (!byRptFrom.isEmpty()) {
            throw new BusinessException("From " + icdTransform.getRptFrom() + " 已经存在!");
        }
        List<IcdTransform> byRptTo = transformRepository.findByRptTo(icdTransform.getRptTo());
        if (!byRptTo.isEmpty()) {
            throw new BusinessException("To " + icdTransform.getRptTo() + " 已经存在!");
        }
        IcdTransform save = transformRepository.save(icdTransform);
        return save;
    }

    @Override
    @CacheEvict(cacheNames = {"listTransform"}, allEntries = true)
    public void deleteTransform(Integer id) throws Exception {
        Optional<IcdTransform> byId = transformRepository.findById(id);
        if (!byId.isPresent()) {
            throw new BusinessException("未找到该记录!");
        }
        transformRepository.deleteById(id);
    }

    @Override
    @CacheEvict(cacheNames = {"listTransform"}, allEntries = true)
    public void clearTransform() {
        transformRepository.deleteAll();
    }

    @Override
    @Cacheable(value = "listTransform")
    public List<IcdTransform> listTransform() {
        return transformRepository.findAll();
    }

}
