package com.sptg.permissions.biz.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.permissions.api.entity.Conf;
import com.sptg.permissions.biz.mapper.ConfMapper;
import com.sptg.permissions.biz.service.ConfServiceInterface;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * title: ConfServiceImpl
 * package: com.sptg.permissions.biz.security.impl
 * description:
 *
 *                  
 *                
 */
@Service
@RequiredArgsConstructor
public class ConfServiceImpl extends ServiceImpl<ConfMapper, Conf> implements ConfServiceInterface {

    /**
     * 菜单缓存名称
     */
    private static final String CONF_CACHE_NAME = "sptg:permissions:conf";

    private final RedisTemplate<String,String> redisTemplate;

    @Override
    public Conf selectEntityByToken(String token) {
        //  查询缓存
        HashOperations<String, String, String> hashOperations = this.redisTemplate.opsForHash();
        String json = hashOperations.get(CONF_CACHE_NAME, token);
        if (StringUtils.isEmpty(json)){
            //  查询数据库
            Wrapper<Conf> wrapper = new EntityWrapper<>();
            wrapper.eq("s_conf_token",token);
            Conf conf = this.selectOne(wrapper);
            if (null != conf){
                //  保存到缓存
                json = JsonUtils.objectToJson(conf);
                hashOperations.put(CONF_CACHE_NAME,token,json);
            }
            return conf;
        }
        return JsonUtils.jsonToPojo(json,Conf.class);
    }
}
