package ink.wgink.module.wechat.startup;

import ink.wgink.module.wechat.manager.MiniappManager;
import ink.wgink.module.wechat.manager.OfficialAccountAccessTokenManager;
import ink.wgink.module.wechat.manager.pay.v3.PayManager;
import ink.wgink.module.wechat.service.pay.v3.certificates.ICertificateService;
import ink.wgink.properties.wechat.miniapp.MiniappProperties;
import ink.wgink.properties.wechat.official.account.OfficialAccountProperties;
import ink.wgink.properties.wechat.pay.v3.PayProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

/**
 * When you feel like quitting. Think about why you started
 * 当你想要放弃的时候，想想当初你为何开始
 *
 * @ClassName: WechatStartUp
 * @Description: 微信启动
 * @Author: wanggeng
 * @Date: 2021/4/28 6:40 上午
 * @Version: 1.0
 */
@Component
public class WechatStartUp implements ApplicationRunner {
    private static final Logger LOG = LoggerFactory.getLogger(WechatStartUp.class);
    @Autowired
    private MiniappProperties miniAppProperties;
    @Autowired
    private OfficialAccountProperties officialAccountProperties;
    @Autowired
    private PayProperties payProperties;
    @Autowired
    private ICertificateService certificateService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        refreshOfficialAccountAccessToken();
        removeTimeoutMiniAppUser();
        // 支付
        PayManager payManager = PayManager.getInstance();
        payManager.setCertificateService(certificateService);
        payManager.setPayProperties(payProperties);
        refreshCertificate();
    }

    @Scheduled(cron = "0 0/5 * * * ?")
    public void refreshOfficialAccountAccessToken() {
        if (!officialAccountProperties.getActivate()) {
            return;
        }
        OfficialAccountAccessTokenManager.getInstance().refreshAccessToken(officialAccountProperties);
    }

    /**
     * 删除小程序超时用户，每10分钟执行一次
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void removeTimeoutMiniAppUser() {
        if (!miniAppProperties.getActive()) {
            return;
        }
        MiniappManager.getInstance().removeTimeout();
    }

    /**
     * 刷新证书，0小时开始，每6小时执行一次
     */
    @Scheduled(cron = "0 0 0/6 * * ?")
    public void refreshCertificate() throws Exception {
        if (!payProperties.getActive()) {
            return;
        }
        PayManager.getInstance().refreshPlatformCertificate();
    }

}
