package com.xunwang.ucenter.cron;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.xunwang.ucenter.entity.AppidAccessToken;
import com.xunwang.ucenter.service.AppidAccessTokenService;
import com.xunwang.ucenter.utils.HttpClientUtils;
import com.xunwang.ucenter.utils.WxConstantUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务，定时获取微信小程序accessToken
 */
@Component
@EnableAsync
@EnableScheduling
public class AccessTokenTask {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private AppidAccessTokenService accessTokenService;

    /**
     * 110分钟定时获取小程序accessToken
     */
    @Async
    @Scheduled(fixedRate = 6600000L)
    public void task() throws Exception {
        // 要访问的微信接口调用凭证
        String baseWxCertificateUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" + "&appid=%s" + "&secret=%s";
        String wxCertificateUrl = String.format(baseWxCertificateUrl, WxConstantUtils.APPID, WxConstantUtils.SECRET);
        String result = HttpClientUtils.get(wxCertificateUrl);

        // 解析结果
        Gson gson = new Gson();
        HashMap hashMap = gson.fromJson(result, HashMap.class);
        String access_token = (String) hashMap.get("access_token");

        // 更新数据库
        AppidAccessToken accessToken = new AppidAccessToken();
        // 获取120分钟后的时间
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        int hour = calendar.get(Calendar.HOUR);
        hour += 2;
        calendar.set(Calendar.HOUR, hour);
        Date time = calendar.getTime();

        String date = dateFormat.format(time);
        accessToken.setAccessToken(access_token).setExpireIn(date);
        accessTokenService.update(accessToken, new QueryWrapper<AppidAccessToken>().eq("type", "mp"));

        // 放入redis缓存中
        redisTemplate.opsForValue().set("access_token", access_token, 120, TimeUnit.MINUTES);

    }

    @Bean("taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setCorePoolSize(10);
        taskExecutor.setMaxPoolSize(50);
        taskExecutor.setQueueCapacity(200);
        taskExecutor.setKeepAliveSeconds(60);
        taskExecutor.setThreadNamePrefix("-");
        taskExecutor.setAwaitTerminationSeconds(60);
        return taskExecutor;
    }

}
