package net.lab1024.sa.admin.module.business.wms.base.customer.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.customer.domain.entity.CustomerEntity;
import net.lab1024.sa.admin.module.business.wms.base.customer.dao.CustomerDao;

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 2025-03-25 10:42:33
 * copyright 友仓
 */
@Service
@Slf4j
@CacheConfig(cacheNames = AdminCacheConst.Base.CUSTOMER_ENTITY)
public class CustomerManager extends ServiceImpl<CustomerDao, CustomerEntity> {

    @Resource
    private CustomerDao customerDao;

    @Resource
    private CacheManager cacheManager;

    /**
     * 查询客户（带缓存）
     * 使用Spring Cache进行缓存管理
     */
    @Cacheable(key = "#customerId", unless = "#result == null")
    public CustomerEntity queryCustomer(Long customerId) {
        return customerDao.selectById(customerId);
    }

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

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

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

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

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