package com.common.service.impl;


import com.common.entity.DeviceDevice;
import com.common.mapper.DeviceDeviceMapper;
import com.common.service.DeviceDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import com.haobang.util.SafeCacheUtil;

@CacheConfig(cacheNames = "device")
@Service
public class DeviceDeviceServiceImpl implements DeviceDeviceService {

    @Autowired
    private DeviceDeviceMapper deviceDeviceMapper;


    @Autowired
    private SafeCacheUtil safeCacheUtil;

    /**
     * 使用安全的缓存方法
     */
    @Cacheable(  key = "'device:id:' +#id")
    @Override
    public DeviceDevice getByIdSafely(Integer id) {
        String cacheKey = "device:id:" + id;
        return safeCacheUtil.getSafe(cacheKey, DeviceDevice.class,
                () -> deviceDeviceMapper.selectById(id));
    }

    /**
     * 使用安全的列表缓存方法
     */
    @Cacheable(  key = "'device:ip:' + #ip")
    @Override
    public List<DeviceDevice> getByIpSafely(String ip) {
        String cacheKey = "device:ip:" + ip;
        return safeCacheUtil.getSafeList(cacheKey, DeviceDevice.class,
                () -> deviceDeviceMapper.selectByIp(ip));
    }

    @Cacheable(  key = "'device:id:' +#id")
    @Override
    public DeviceDevice getById(Integer id) {
        System.out.println("exec deviceDeviceMapper.selectById :" + id.toString());
        return deviceDeviceMapper.selectById(id);
    }

    @Override
    public List<DeviceDevice> getAll() {
        return deviceDeviceMapper.selectAll();
    }

    @Cacheable(  key = "'device:ip:' + #ip")
    @Override
    public List<DeviceDevice> getByIp(String ip) {

        return deviceDeviceMapper.selectByIp(ip);
    }

    @Override
    public List<DeviceDevice> getByNameLike(String name) {
        return deviceDeviceMapper.selectByNameLike(name);
    }

    @Override
    public List<DeviceDevice> getByCondition(DeviceDevice condition) {
        return deviceDeviceMapper.selectByCondition(condition);
    }

    @Override
    public List<DeviceDevice> getByMap(Map<String, Object> params) {
        return deviceDeviceMapper.selectByMap(params);
    }

    @Override
    public List<DeviceDevice> getByPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        return deviceDeviceMapper.selectByPage(offset, pageSize);
    }

    @Override
    public Long getCount() {
        return deviceDeviceMapper.count();
    }

    @Override
    public List<DeviceDevice> getMonitoringDevices() {
        return deviceDeviceMapper.selectMonitoringDevices();
    }

    @Override
    public List<DeviceDevice> getActiveDevices() {
        return deviceDeviceMapper.selectActiveDevices();
    }
}