package net.lab1024.sa.admin.module.business.wms.base.stock.manager;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.constant.AdminCacheConst;
import net.lab1024.sa.admin.module.business.wms.base.stock.dao.StockDao;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.entity.StockEntity;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;

/**
 * 容器信息 Manager
 *
 * @author 霍锦
 * @since 2024-11-26 11:37:48
 * copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.STOCK_ENTITY)
public class StockManager extends ServiceImpl<StockDao, StockEntity> {

    @Resource
    private StockDao stockDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询容器（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#stockId", unless = "#result == null")
    public StockEntity queryStock(Long stockId) {
        return stockDao.selectById(stockId);
    }

    /**
     * 更新容器（清除缓存）
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#entity.stockId")
    public void update(StockEntity entity) {
        super.updateById(entity);
    }

    /**
     * 删除容器（清理缓存）
     */
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(key = "#stockId")
    public void deleteById(Long stockId) {
        super.removeById(stockId);
    }

    /**
     * 批量更新容器（清理相关缓存）
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchUpdate(List<StockEntity> entities) {
        super.updateBatchById(entities);
        List<Long> stockIds = entities.stream().map(StockEntity::getStockId).filter(Objects::nonNull).distinct().toList();
        stockIds.forEach(this::clearCache);
    }

    /**
     * 批量删除容器（清理相关缓存）
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchDelete(List<Long> stockIds) {
        super.removeByIds(stockIds);
        stockIds.forEach(this::clearCache);
    }

    /**
     * 手工清理缓存
     */
    public void clearCache(Long stockId) {
        if (stockId != null) {
            Cache cache = cacheManager.getCache(AdminCacheConst.Base.STOCK_ENTITY);
            if (cache != null) {
                cache.evict(stockId);
            }
        }
    }
}
