package com.common.service.impl;



import com.common.entity.DeviceUnknown;
import com.common.mapper.DeviceUnknownMapper;
import com.common.service.DeviceUnknownService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.cache.CacheManager;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.Cacheable;
import java.time.LocalDateTime;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

@Slf4j
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "deviceunknown")
public class DeviceUnknownServiceImpl implements DeviceUnknownService {

    private final DeviceUnknownMapper deviceUnknownMapper;
    @Autowired
    private CacheManager cacheManager;

    @Override
    @Transactional
    public Long createDevice(DeviceUnknown device) {
        // 设置默认值
        if (device.getCreatedAt() == null) {
            device.setCreatedAt(LocalDateTime.now());
        }
        if (device.getNetworkProtocol() == null) {
            device.setNetworkProtocol("TCP");
        }
        if (device.getSourceMethod() == null) {
            device.setSourceMethod("SYSTEM");
        }

        try {
            int result = deviceUnknownMapper.insert(device);
            if (result > 0) {
                log.info("设备记录创建成功，ID: {}", device.getId());
                //清除缓存IP:XXXX
                clearDeviceCache(device.getDeviceIp());
                List<DeviceUnknown>  devlist=this.getDevicesByIp(device.getDeviceIp());
                return device.getId();
            }
            return null;
        } catch (Exception e) {
            log.error("创建设备记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("创建设备记录失败", e);
        }
    }
    /**
     * 清除缓存
     */
    public void clearDeviceCache(String deviceIp) {
        Cache cache = cacheManager.getCache("deviceunknown");
        if (cache != null) {
            System.out.println("清除缓存"+"ip:" + deviceIp);
            cache.evict("ip:" + deviceIp);
        }
    }

    @Override
    @Transactional
    public int batchCreateDevices(List<DeviceUnknown> devices) {
        if (CollectionUtils.isEmpty(devices)) {
            return 0;
        }

        // 设置默认值
        devices.forEach(device -> {
            if (device.getCreatedAt() == null) {
                device.setCreatedAt(LocalDateTime.now());
            }
            if (device.getNetworkProtocol() == null) {
                device.setNetworkProtocol("TCP");
            }
            if (device.getSourceMethod() == null) {
                device.setSourceMethod("SYSTEM");
            }
        });

        try {
            int result = deviceUnknownMapper.batchInsert(devices);
            log.info("批量插入设备记录成功，数量: {}", result);
            return result;
        } catch (Exception e) {
            log.error("批量插入设备记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("批量插入设备记录失败", e);
        }
    }

    @Override
    public DeviceUnknown getDeviceById(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("设备ID不能为空");
        }

        try {
            return deviceUnknownMapper.selectById(id);
        } catch (Exception e) {
            log.error("查询设备记录失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            throw new RuntimeException("查询设备记录失败", e);
        }
    }
    @Cacheable(  key = "'ip:' +#deviceIp")
    @Override
    public List<DeviceUnknown> getDevicesByIp(String deviceIp) {
        if (deviceIp == null || deviceIp.trim().isEmpty()) {
            throw new IllegalArgumentException("设备IP不能为空");
        }
        try {
            return deviceUnknownMapper.selectByIp(deviceIp);
        } catch (Exception e) {
            log.error("根据IP查询设备记录失败，IP: {}, 错误: {}", deviceIp, e.getMessage(), e);
            throw new RuntimeException("根据IP查询设备记录失败", e);
        }
    }

    @Override
    public List<DeviceUnknown> getDevicesByOrganizationId(Integer organizationId) {
        if (organizationId == null || organizationId <= 0) {
            throw new IllegalArgumentException("组织ID不能为空");
        }

        try {
            return deviceUnknownMapper.selectByOrganizationId(organizationId);
        } catch (Exception e) {
            log.error("根据组织ID查询设备记录失败，组织ID: {}, 错误: {}", organizationId, e.getMessage(), e);
            throw new RuntimeException("根据组织ID查询设备记录失败", e);
        }
    }

    @Override
    public List<DeviceUnknown> getAllDevices() {
        try {
            return deviceUnknownMapper.selectAll();
        } catch (Exception e) {
            log.error("查询所有设备记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("查询所有设备记录失败", e);
        }
    }

    @Override
    public List<DeviceUnknown> getDevicesByPage(int pageNum, int pageSize) {
        if (pageNum <= 0) {
            pageNum = 1;
        }
        if (pageSize <= 0) {
            pageSize = 10;
        }

        int offset = (pageNum - 1) * pageSize;

        try {
            return deviceUnknownMapper.selectPage(offset, pageSize);
        } catch (Exception e) {
            log.error("分页查询设备记录失败，页码: {}, 页大小: {}, 错误: {}",
                    pageNum, pageSize, e.getMessage(), e);
            throw new RuntimeException("分页查询设备记录失败", e);
        }
    }

    @Override
    public List<DeviceUnknown> searchDevices(DeviceUnknown device) {
        try {
            return deviceUnknownMapper.selectByCondition(device);
        } catch (Exception e) {
            log.error("条件查询设备记录失败: {}", e.getMessage(), e);
            throw new RuntimeException("条件查询设备记录失败", e);
        }
    }

    @Override
    @Transactional
    public boolean updateDevice(DeviceUnknown device) {
        if (device == null || device.getId() == null) {
            throw new IllegalArgumentException("设备信息或ID不能为空");
        }
        try {
            int result = deviceUnknownMapper.updateById(device);
            if (result > 0) {
                log.info("更新设备记录成功，ID: {}", device.getId());
                return true;
            }
            log.warn("未找到要更新的设备记录，ID: {}", device.getId());
            return false;
        } catch (Exception e) {
            log.error("更新设备记录失败，ID: {}, 错误: {}", device.getId(), e.getMessage(), e);
            throw new RuntimeException("更新设备记录失败", e);
        }
    }

    @Override
    @Transactional
    public boolean updateLastTime(Long id, LocalDateTime lastTime) {
        if (id == null || lastTime == null) {
            throw new IllegalArgumentException("设备ID和最后发现时间不能为空");
        }

        try {
            int result = deviceUnknownMapper.updateLastTime(id, lastTime);
            if (result > 0) {
                log.info("更新设备最后发现时间成功，ID: {}", id);
                return true;
            }
            log.warn("未找到要更新最后发现时间的设备记录，ID: {}", id);
            return false;
        } catch (Exception e) {
            log.error("更新设备最后发现时间失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            throw new RuntimeException("更新设备最后发现时间失败", e);
        }
    }

    @Override
    @Transactional
    public boolean deleteDevice(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("设备ID不能为空");
        }

        try {
            int result = deviceUnknownMapper.deleteById(id);
            if (result > 0) {
                log.info("删除设备记录成功，ID: {}", id);
                return true;
            }
            log.warn("未找到要删除的设备记录，ID: {}", id);
            return false;
        } catch (Exception e) {
            log.error("删除设备记录失败，ID: {}, 错误: {}", id, e.getMessage(), e);
            throw new RuntimeException("删除设备记录失败", e);
        }
    }

    @Override
    @Transactional
    public int deleteDevicesByOrganizationId(Integer organizationId) {
        if (organizationId == null || organizationId <= 0) {
            throw new IllegalArgumentException("组织ID不能为空");
        }

        try {
            int result = deviceUnknownMapper.deleteByOrganizationId(organizationId);
            log.info("根据组织ID删除设备记录成功，组织ID: {}, 删除数量: {}", organizationId, result);
            return result;
        } catch (Exception e) {
            log.error("根据组织ID删除设备记录失败，组织ID: {}, 错误: {}",
                    organizationId, e.getMessage(), e);
            throw new RuntimeException("根据组织ID删除设备记录失败", e);
        }
    }

    @Override
    public long getTotalCount() {
        try {
            Long count = deviceUnknownMapper.count();
            return count != null ? count : 0L;
        } catch (Exception e) {
            log.error("统计设备总数失败: {}", e.getMessage(), e);
            throw new RuntimeException("统计设备总数失败", e);
        }
    }

    @Override
    public long getCountByCondition(DeviceUnknown device) {
        try {
            Long count = deviceUnknownMapper.countByCondition(device);
            return count != null ? count : 0L;
        } catch (Exception e) {
            log.error("条件统计设备数量失败: {}", e.getMessage(), e);
            throw new RuntimeException("条件统计设备数量失败", e);
        }
    }
}