package cn.com.countrygarden.bi.main.service.impl;

import cn.com.countrygarden.bi.main.core.AbstractService;
import cn.com.countrygarden.bi.main.dao.AccessTokenMapper;
import cn.com.countrygarden.bi.main.model.AccessToken;
import cn.com.countrygarden.bi.main.model.AccessTokenConstant;
import cn.com.countrygarden.bi.main.service.AccessTokenService;
import cn.com.countrygarden.bi.main.util.RedisCacheUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class AccessTokenServiceImpl extends AbstractService<AccessToken> implements AccessTokenService {
    @Resource
    private AccessTokenMapper accessTokenMapper;


    public void insertOrUpdate(Map<String, String> accessToken) {
        accessTokenMapper.insertOrUpdate(accessToken);
    }

    public AccessToken getAccessToken(Map<String, String> accessToken) {
        return accessTokenMapper.getAccessToken(accessToken);
    }

    public void updateAccessToken(Map<String, String> accessToken) {
        accessTokenMapper.updateAccessToken(accessToken);
    }

    public AccessToken findByToken(String token){
        Map<String,String> parameter = new HashMap<String,String>();
        parameter.put("token",token);
        return (AccessToken)RedisCacheUtils.remeber(AccessTokenConstant.CACHEKEY,AccessTokenConstant.CACHETIME,
                parameter,AccessToken.class,p->{
                    Condition condition = new Condition(AccessToken.class);
                    condition.createCriteria().andEqualTo("accessToken",token);

                    List<AccessToken> tokens = accessTokenMapper.selectByCondition(condition);
                    if(tokens.size()>0){
                        return tokens.get(0);
                    }
                    return null;
                });
    }

    public AccessToken findByUserCode(String userCode){
        List<AccessToken>  tokens =accessTokenMapper.findByUserCode(userCode);
        if(tokens.size()>0){
            return tokens.get(0);
        }
        return null;
    }
}
