package com.jiayue.insu.inclientqn.service;

import com.jiayue.insu.inclientqn.entity.TokenInfo;
import com.jiayue.insu.inclientqn.mapper.TokenInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.ehcache.search.Attribute;
import net.sf.ehcache.search.Query;
import net.sf.ehcache.search.Result;
import net.sf.ehcache.search.Results;
import org.springframework.cache.ehcache.EhCacheCacheManager;

/**
 * token信息服务类
 *
 * @author xsl
 * @version 3.0
 */
@Service
public class TokenInfoService {
    @Autowired
    TokenInfoMapper tokenInfoMapper;
    @Autowired
    EhCacheCacheManager ehCacheCacheManager;

    public List<TokenInfo> queryTokenInfo(){
        Cache cache = ehCacheCacheManager.getCacheManager().getCache("sysinfo");
        Query query = cache.createQuery();
        //查询结果中包含Key和value
        query.includeKeys().includeValues();
        Attribute<String> keyName = cache.getSearchAttribute("key");
        query.addCriteria(keyName.ilike("*tokeninfo*"));
        Results results = query.execute();
        List<Result> resultList = results.all();

        List<TokenInfo> list = new ArrayList();
        if (resultList != null && !resultList.isEmpty()) {
            System.out.println("查询缓存tokeninfo");
            for (Result result : resultList) {
                TokenInfo e = (TokenInfo) result.getValue();
                list.add(e);
            }
            results.discard();
        } else {
            System.out.println("查询数据库tokeninfo");
            // 缓存没有值,查询数据库
            list = tokenInfoMapper.selectList(null);
            for (TokenInfo tokenInfo : list) {
                //将结果存入缓存
                cache.put(new Element("tokeninfo" + tokenInfo.getId(), tokenInfo));
            }
        }
        return list;
    }
}
