package com.xydl.cac.service.impl;

import com.xydl.cac.entity.ModevTypePoint;
import com.xydl.cac.entity.WarnRule;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.ModevTypePointRepository;
import com.xydl.cac.repository.WarnRuleRepository;
import com.xydl.cac.service.ModevTypePointService;
import com.xydl.cac.service.UnitService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
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 ModevTypePointServiceImpl implements ModevTypePointService {

    @Resource
    ModevTypePointRepository repository;
    @Resource
    UnitService unitService;
    @Resource
    WarnRuleRepository ruleRepository;

    @Override
    public List<ModevTypePoint> listAll(Integer modevtypeId) {
        List<ModevTypePoint> list = repository.findByModevtypeId(modevtypeId);
        for (ModevTypePoint point : list) {
            if (StringUtils.isNotBlank(point.getField())) {
                point.setUnit(unitService.findUnitInCache(point.getField()));
            }
        }
        return list;
    }

    @Override
    @Cacheable(value = "typePoint", key = "#modevtypeId")
    public List<ModevTypePoint> listAllCache(Integer modevtypeId) {
        List<ModevTypePoint> list = this.listAll(modevtypeId);
        return list;
    }

    @Override
    @CacheEvict(cacheNames = {"typePoint"}, allEntries = true)
    public ModevTypePoint add(ModevTypePoint item) throws Exception {
        item.setId(null);
        List<ModevTypePoint> list = repository.findByModevtypeIdAndField(item.getModevtypeId(), item.getField());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该监测装置类型的该字段已存在");
        }
        return repository.save(item);
    }

    @Override
    @CacheEvict(cacheNames = {"typePoint"}, allEntries = true)
    public void delete(Integer id) throws Exception {
        List<WarnRule> list = ruleRepository.findByModevtypePointId(id);
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该监测装置类型的该字段已配置告警规则，请先删除对应的规则后再来操作");
        }
        repository.deleteById(id);
    }
}
