package com.seer.teach.mp.app.scheduled;


import com.seer.teach.common.config.WxConfig;
import com.seer.teach.common.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import jakarta.annotation.PostConstruct;
import java.time.LocalDateTime;

/**
 * @Author: Captain
 * @Description: 微信AccessToken自动刷新任务
 * @Date: 2025-05-09 20:56
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class WxAccessTokenScheduledTask {

    private final RestTemplate restTemplate;

    private final RedisUtil redisUtil;

    @Value("${zs.task.refresh-wx-access-token.enabled:false}")
    private boolean enabled;

    /**
     * Author: Captain
     * Desc:   每110分种执行一次请求微信接口并替换WxTokenManager中的token
     * Params: []
     * Return: void
     * Time: 2025/5/9 20:57
     */
    @Scheduled(fixedRate = 6600000)
    public void runTask() {
        if (enabled) {
            try {
                log.info("begin update wechat access token time [{}]", LocalDateTime.now());
                String accessToken = restTemplate.getForEntity(WxConfig.GET_ACCESS_TOKEN_URL, WxAccessTokenApiResp.class).getBody().getAccess_token();
                log.info("begin update wechat access token success time [{}] value length [{}]", LocalDateTime.now(), accessToken.length());
                redisUtil.set(WxConfig.REDIS_ACCESS_KEY, accessToken);
                log.info("end update wechat access token success time [{}] value [{}]", LocalDateTime.now(), accessToken);
            }catch (Exception e){
                log.error("update wechat access token error time [{}]", LocalDateTime.now(), e);
            }
        }
    }

    @PostConstruct
    public void init() {
        log.info("[init WxAccessTokenScheduledTask]");
        runTask();
    }
}
