package com.iformall.service.impl;

import com.iformall.common.IdWorker;
import com.iformall.domain.po.WxCUser;
import com.iformall.mapper.WxCUserMapper;
import com.iformall.mapper.WxCouponOrderMapper;
import com.iformall.mapper.WxScoreHistoryMapper;
import com.iformall.mapper.WxScoreRulesMapper;
import com.iformall.service.WxCUserTokenService;
import com.iformall.service.WxScoreRulesService;
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 WxCUserTokenServiceImpl implements WxCUserTokenService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private String tokenPrev = "weapp:token:";

    @Autowired
    WxCUserMapper wxCUserMapper;

    @Autowired
    @Qualifier("cuserTokenRedisTemplate")
    RedisTemplate<String, WxCUser> cUserTokenRedisTemplate;

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

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

        return user;
    }

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

        return ret;
    }

}
