package com.xydl.cac.service.impl;

import com.xydl.cac.entity.Modev;
import com.xydl.cac.entity.ModevType;
import com.xydl.cac.entity.Zsb;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.ModevRepository;
import com.xydl.cac.repository.ModevTypeRepository;
import com.xydl.cac.repository.ZsbRepository;
import com.xydl.cac.service.ModevService;
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.HashMap;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class ModevServiceImpl implements ModevService {

    @Resource
    ModevRepository repository;

    @Resource
    ModevTypeRepository modevTypeRepository;

    @Resource
    ZsbRepository zsbRepository;

    @Override
    public List<Modev> listAll(Integer zsbid) {
        List<Modev> byZsbid = repository.findByZsbid(zsbid);
        Optional<Zsb> byId = zsbRepository.findById(zsbid);
        List<ModevType> all = modevTypeRepository.findAll();
        HashMap<Integer,String> map = new HashMap();
        for (ModevType tit:all) {
            map.put(tit.getId(), tit.getMc());
        }
        for (Modev it : byZsbid) {
            it.setModevtname(map.get(it.getModevtid()));
            it.setZsbname(byId.get().getMc());
        }
        return byZsbid;
    }

    @Override
    public Modev add(Modev item) throws Exception {
        item.setId(null);
        List<Modev> byZsbidAndName = repository.findByZsbidAndName(item.getZsbid(), item.getName());
        if (!CollectionUtils.isEmpty(byZsbidAndName)) {
            throw new BusinessException("该监测装置已存在");
        }
        return repository.save(item);
    }

    @Override
    public void update(Modev item) throws Exception {
        List<Modev> byMc = repository.findByZsbidAndName(item.getZsbid(), item.getName());
        if (!CollectionUtils.isEmpty(byMc)) {
            for (Modev it : byMc) {
                if (it.getId().intValue() != item.getId().intValue()) {
                    throw new BusinessException("该监测装置类型已存在");
                }
            }
        }
        repository.save(item);
    }

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

    @Override
    public Modev detail(Integer id) throws Exception {
        Optional<Modev> optional = repository.findById(id);
        if (!optional.isPresent()) {
            throw new BusinessException("未找到该类型");
        }
        return optional.get();
    }

}
