package com.ruoyi.system.service.impl;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.system.domain.SysDevice;
import com.ruoyi.system.mapper.SysDeviceMapper;
import com.ruoyi.system.service.ISysDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 设备管理 Service 实现
 */
@Service
public class SysDeviceServiceImpl implements ISysDeviceService {

    @Autowired
    private SysDeviceMapper deviceMapper;

    @Override
    public SysDevice selectDeviceById(Long deviceId) {
        return deviceMapper.selectDeviceById(deviceId);
    }

    @Override
    public List<SysDevice> selectDeviceList(SysDevice device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public int insertDevice(SysDevice device) {
        checkSnUnique(device.getDeviceSn(), null);
        return deviceMapper.insertDevice(device);
    }

    @Override
    public int updateDevice(SysDevice device) {
        checkSnUnique(device.getDeviceSn(), device.getDeviceId());
        return deviceMapper.updateDevice(device);
    }

    @Override
    public int deleteDeviceById(Long deviceId) {
        return deviceMapper.deleteDeviceById(deviceId);
    }

    @Override
    public int deleteDeviceByIds(Long[] deviceIds) {
        return deviceMapper.deleteDeviceByIds(deviceIds);
    }

    private void checkSnUnique(String deviceSn, Long currentId) {
        if (StringUtils.isEmpty(deviceSn)) {
            throw new ServiceException("设备SN不能为空");
        }
        SysDevice old = deviceMapper.checkDeviceSnUnique(deviceSn);
        if (old == null) {
            return;
        }
        if (currentId != null && old.getDeviceId().equals(currentId)) {
            return;
        }
        throw new ServiceException("设备SN已存在，请更换");
    }
}
