package net.lab1024.sa.admin.module.business.wms.base.location.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.location.dao.LocationDao;
import net.lab1024.sa.admin.module.business.wms.base.location.domain.entity.LocationEntity;

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-18 14:17:31
 * copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.LOCATION_ENTITY)
public class LocationManager extends ServiceImpl<LocationDao, LocationEntity> {

    @Resource
    private LocationDao locationDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询库位（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#locationId", unless = "#result == null")
    public LocationEntity queryLocation(Long locationId) {
        return locationDao.selectById(locationId);
    }

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

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

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

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

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