package com.iformall.schedule;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.iformall.domain.po.WxAppinfo;
import com.iformall.mapper.WxAppinfoMapper;
import com.iformall.utils.MaUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class WeChatAccessTokenSchedule {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private boolean isFmOpen;

    @Autowired
    WxAppinfoMapper wxAppinfoMapper;


    @Scheduled(cron = "0 1 * * * ?") // 每小时第一分钟执行
    public void getAccessTokens() {

        logger.info("微信访问AccessToken获取定时任务启动");
        if(!isFmOpen) {

            WxAppinfo appinfoQ = new WxAppinfo();
            List<WxAppinfo> appList = wxAppinfoMapper.findList(appinfoQ);

            for (WxAppinfo appinfo : appList) {
                resetAccessToken(appinfo);
            }
        }

        logger.info("微信访问AccessToken获取定时任务结束");
    }

    public void resetAccessToken(WxAppinfo appinfo) {
        WxMaService wxMaService = MaUtil.getWeappService(appinfo);
        try {
            String accessToken = wxMaService.getAccessToken(true);
            WxAppinfo updateAppInfo = new WxAppinfo();
            updateAppInfo.setAccessToken(accessToken);
            updateAppInfo.setLastTokenTime(new Date());
            updateAppInfo.setExpiresIn(7200);
            wxAppinfoMapper.updateById(updateAppInfo);
        } catch (WxErrorException e) {
            logger.error(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage());
        }

    }

}