package com.iformall.service.impl;

import com.iformall.common.IdWorker;
import com.iformall.domain.po.WxBuser;
import com.iformall.mapper.WxBuserMapper;
import com.iformall.service.WxBuserTokenService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class WxBuserTokenServiceImpl implements WxBuserTokenService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String tokenPrev = "weapp:b:token:";

    @Autowired
    WxBuserMapper wxBuserMapper;

    @Autowired
    @Qualifier("buserTokenRedisTemplate")
    RedisTemplate<String, WxBuser> bUserTokenRedisTemplate;

    @Override
    public WxBuser getByToken(String token) {
        logger.info("获取用户信息start ...");
        String key = tokenPrev + token;
        ValueOperations<String, WxBuser> operations = bUserTokenRedisTemplate.opsForValue();

        // 缓存
        boolean hasKey = bUserTokenRedisTemplate.hasKey(key);
        if (hasKey) {
            // 从缓存获取用户信息
            WxBuser user = operations.get(key);
            return user;
        }
        WxBuser user = wxBuserMapper.findByToken(token);
        // 插入缓存
        operations.set(key, user, 3600, TimeUnit.SECONDS);

        return user;
    }

    @Override
    public int saveOrUpdate(WxBuser user) {
        int ret = 0;
        Date curr = new Date();
        if (user.getId() == null) {
            final IdWorker idWorker = IdWorker.get();
            user.setId(idWorker.nextId());
            user.setLoginCount(1);
            user.setCreateDate(curr);
            user.setUpdateDate(curr);
            ret = wxBuserMapper.insert(user);
        } else {
            user.setUpdateDate(curr);
            ret = wxBuserMapper.updateById(user);
        }
        String key = tokenPrev + user.getToken();
        // 缓存已存在，删除
        boolean hasKey = bUserTokenRedisTemplate.hasKey(key);
        if (hasKey) {
            bUserTokenRedisTemplate.delete(key);
            logger.info("更新用户，从缓存中删除用户 token >> " + user.getToken());
        }

        return ret;
    }

}
