package net.lab1024.sa.admin.module.business.wms.base.item.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.item.dao.ItemDao;
import net.lab1024.sa.admin.module.business.wms.base.item.domain.entity.ItemEntity;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.lab1024.sa.admin.module.business.wms.base.stock.domain.vo.StockVO;
import org.springframework.cache.Cache;
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.Collection;
import java.util.Objects;

import org.springframework.cache.CacheManager;

/**
 * 物料信息
 *
 * @Author 霍锦
 * @Date 2024-11-25 17:08:18
 * @Copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.ITEM_ENTITY)
public class ItemManager extends ServiceImpl<ItemDao, ItemEntity> {

    @Resource
    private ItemDao itemDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询物料（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#itemId", unless = "#result == null")
    public ItemEntity queryItem(Long itemId) {
        return itemDao.selectById(itemId);
    }

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

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

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

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

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