package com.xydl.cac.service.impl;

import com.xydl.cac.entity.N103Point;
import com.xydl.cac.entity.NPoint;
import com.xydl.cac.exception.BusinessException;
import com.xydl.cac.repository.N103PointRepository;
import com.xydl.cac.repository.NPointRepository;
import com.xydl.cac.service.NPointService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

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

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class NPointServiceImpl implements NPointService {

    @Resource
    NPointRepository repository;
    @Resource
    N103PointRepository n103PointRepository;

    @Override
    public List<NPoint> listAll(Integer sensorId) {
        List<NPoint> list = repository.findBySensorId(sensorId);
        return list;
    }

    @Override
    public Page<NPoint> list(int pageNum, int pageSize) {
        PageRequest request = PageRequest.of(pageNum - 1, pageSize);
        Page<NPoint> result = repository.findAll(request);
        return result;
    }

    @Override
    public NPoint add(NPoint item) throws Exception {
        List<NPoint> list = repository.findBySensorIdAndField(item.getSensorId(), item.getField());
        if (!CollectionUtils.isEmpty(list)) {
            throw new BusinessException("该监测装置的该字段已存在");
        }
        item.setId(null);
        return repository.save(item);
    }

    @Override
    public void update(NPoint item) throws Exception {
        repository.save(item);
    }

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

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

    @Override
    public void importOne(NPoint item) {
        repository.save(item);
        N103Point n103Point = item.getN103Point();
        if (n103Point != null) {
            n103Point.setNpointId(item.getId());
            n103PointRepository.save(n103Point);
        }
    }

    @Override
    public void clearAll(Integer sensorId, Integer sensor103Id) {
        repository.deleteBySensorId(sensorId);
        if (sensor103Id != null) {
            n103PointRepository.deleteBySensor103Id(sensor103Id);
        }
    }
}
