package net.lab1024.sa.admin.module.business.wms.base.area.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.area.domain.entity.AreaEntity;
import net.lab1024.sa.admin.module.business.wms.base.area.dao.AreaDao;

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 hj
 * @since 2025-03-11 11:12:36
 * copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.AREA_ENTITY)
public class AreaManager extends ServiceImpl<AreaDao, AreaEntity> {

    @Resource
    private AreaDao areaDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询库区（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#areaId", unless = "#result == null")
    public AreaEntity queryArea(Long areaId) {
        return areaDao.selectById(areaId);
    }

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

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

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

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

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