package com.pj.current.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.pj.current.config.WxConfig;
import com.pj.utils.cache.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class TokenTask implements Runnable {
    @Resource
    WxConfig wxConfig;

    @Override
    public void run() {
        String tokenKey = wxConfig.getAccessTokenKey();
        String ticketKey = wxConfig.getJsApiTicketKey();
        String tokenUrl = wxConfig.getAccessTokenUrl();
        String resp = HttpUtil.get(tokenUrl);
        JSONObject result = JSONUtil.parseObj(resp);
        String accessToken = result.getStr("access_token");
        if (StrUtil.isEmpty(accessToken)) {
            log.error("get access token fail:{}", resp);
            return;
        }
        RedisUtil.set(tokenKey, accessToken);
        String jsUrl = wxConfig.getJsApiTokenUrl().replaceAll("ACCESS_TOKEN", accessToken);
        String jsResp = HttpUtil.get(jsUrl);
        JSONObject jsResult = JSONUtil.parseObj(jsResp);
        String ticket = jsResult.getStr("ticket");
        if (StrUtil.isEmpty(ticket)) {
            log.error("=======ticket=====fail======");
            return;
        }
        RedisUtil.set(ticketKey, accessToken);
    }
}
