package com.qmth.exam.reserve.cache.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qmth.exam.reserve.bean.category.CategoryCacheBean;
import com.qmth.exam.reserve.cache.CacheConstants;
import com.qmth.exam.reserve.cache.RedisClient;
import com.qmth.exam.reserve.dao.CategoryDao;
import com.qmth.exam.reserve.entity.CategoryEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class CategoryCacheService implements CacheConstants {

    private static final Logger log = LoggerFactory.getLogger(CategoryCacheService.class);

    @Autowired
    private RedisClient redisClient;

    @Autowired
    private CategoryDao categoryDao;

    /**
     * 获取某个分类缓存
     */
    public CategoryCacheBean getCategoryById(Long categoryId) {
        String cacheKey = String.format(CACHE_CATEGORY, categoryId);
        CategoryCacheBean value = redisClient.get(cacheKey, CategoryCacheBean.class);
        if (value != null) {
            return value;
        }

        value = this.findInfoById(categoryId);
        if (value == null) {
            return null;
        }

        redisClient.set(cacheKey, value, 10, TimeUnit.MINUTES);
        log.info("SET cacheKey:{}", cacheKey);

        return value;
    }

    public void clearCategoryByIdCache(Long categoryId) {
        String cacheKey = String.format(CACHE_CATEGORY, categoryId);
        redisClient.delete(cacheKey);
        log.warn("DELETE cacheKey:{}", cacheKey);
    }

    private CategoryCacheBean findInfoById(Long categoryId) {
        LambdaQueryWrapper<CategoryEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(CategoryEntity::getId, CategoryEntity::getCode, CategoryEntity::getName,
                CategoryEntity::getLevel, CategoryEntity::getEnable, CategoryEntity::getParentId);
        wrapper.eq(CategoryEntity::getId, categoryId);
        CategoryEntity category = categoryDao.selectOne(wrapper);
        if (category == null) {
            return null;
        }

        CategoryCacheBean bean = new CategoryCacheBean();
        bean.setId(category.getId());
        bean.setCode(category.getCode());
        bean.setName(category.getName());
        bean.setLevel(category.getLevel());
        bean.setEnable(category.getEnable());
        bean.setParentId(category.getParentId());
        return bean;
    }

}
