package net.lab1024.sa.admin.module.business.wms.inventory.itemKey.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.domain.entity.ItemEntity;
import net.lab1024.sa.admin.module.business.wms.inventory.itemKey.domain.entity.ItemKeyEntity;
import net.lab1024.sa.admin.module.business.wms.inventory.itemKey.dao.ItemKeyDao;

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 霍锦
 * @Date 2024-12-05 21:38:40
 * @Copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.ItemKey.ITEM_KEY_ENTITY)
public class ItemKeyManager extends ServiceImpl<ItemKeyDao, ItemKeyEntity> {

    @Resource
    private ItemKeyDao itemKeyDao;

    @Resource
    private CacheManager cacheManager;

    @Cacheable(key = "#itemKeyId", unless = "#result == null")
    public ItemKeyEntity queryItemKey(Long itemKeyId) {
        return itemKeyDao.selectById(itemKeyId);
    }

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

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

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

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

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


}
