package com.xydl.cac.service.impl;

import com.xydl.cac.entity.Unit;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.model.StaticVariable;
import com.xydl.cac.repository.UnitRepository;
import com.xydl.cac.service.UnitService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
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 UnitServiceImpl implements UnitService {

    @Resource
    UnitRepository repository;

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

    @Override
    @CacheEvict(cacheNames = {"typePoint"}, allEntries = true)
    public Unit add(Unit item) throws Exception {
        item.setId(null);
        List<Unit> list = repository.findByField(item.getField());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该字段已存在");
        }
        StaticVariable.unit_Cache.clear();
        return repository.save(item);
    }

    @Override
    @CacheEvict(cacheNames = {"typePoint"}, allEntries = true)
    public void update(Unit item) throws Exception {
        repository.save(item);
        StaticVariable.unit_Cache.clear();
    }

    @Override
    @CacheEvict(cacheNames = {"typePoint"}, allEntries = true)
    public void delete(Integer id) {
        repository.deleteById(id);
        StaticVariable.unit_Cache.clear();
    }

    @Override
    public String findUnitInCache(String field) {
        if (StaticVariable.unit_Cache.size() < 1) {
            List<Unit> list = repository.findAll();
            for (Unit item : list) {
                StaticVariable.unit_Cache.put(item.getField().toLowerCase(), item.getUnit());
            }
        }
        return StaticVariable.unit_Cache.get(field.toLowerCase());
    }
}
