package net.lab1024.sa.admin.module.business.wms.base.address.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.address.domain.entity.AddressEntity;
import net.lab1024.sa.admin.module.business.wms.base.address.dao.AddressDao;
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 2024-12-26 15:35:23
 * copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.ADDRESS_ENTITY)
public class AddressManager extends ServiceImpl<AddressDao, AddressEntity> {

    @Resource
    private AddressDao addressDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询收货单位（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#addressId", unless = "#result == null")
    public AddressEntity queryAddress(Long addressId) {
        return addressDao.selectById(addressId);
    }

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

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

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

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

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