package com.bofeng.wx;

import com.bofeng.support.WeChatProperties;
import com.google.common.base.Strings;
import com.yvan.platform.Conv;
import com.yvan.platform.YvanUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpQrcodeService;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class QrCodeService {

    private static final String REDIS_SCENE_PREFIX = "wechat:scene:";

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private WxMpQrcodeService wxMpQrcodeService;

    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 生成带参临时二维码
     */
    public WxMpQrCodeTicket create(Object content) throws WxErrorException {
        final int sceneId = Conv.NI(stringRedisTemplate.opsForValue().increment(REDIS_SCENE_PREFIX + "id", 1));
        WxMpQrCodeTicket ticket = wxMpQrcodeService.qrCodeCreateTmpTicket(sceneId, weChatProperties.getTmpTicketExpireSeconds());
        stringRedisTemplate.opsForValue().set(REDIS_SCENE_PREFIX + ticket.getTicket(),
                YvanUtil.toJson(content), ticket.getExpireSeconds(), TimeUnit.SECONDS);
        return ticket;
    }

    /**
     * 获取二维码内附带的数据
     */
    public <T> T getContent(String ticket, Class<T> clazz) {
        String c = stringRedisTemplate.opsForValue().get(REDIS_SCENE_PREFIX + ticket);
        if (Strings.isNullOrEmpty(c)) {
            return null;
        }
        return YvanUtil.jsonToObj(c, clazz);
    }
}
