package com.njzscloud.common.wechat;


import cn.hutool.core.lang.Assert;
import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.common.core.ex.Exceptions;
import com.njzscloud.common.http.HttpClientDecorator;
import com.njzscloud.common.wechat.param.Code2SessionParam;
import com.njzscloud.common.wechat.param.GetAccessTokenParam;
import com.njzscloud.common.wechat.result.Code2SessionResult;
import com.njzscloud.common.wechat.result.GetAccessTokenResult;

import java.util.Date;

public class WechatUtil {
    private static final WechatApi API;
    private static String accessToken = "";
    private static long tokenExpTime = 0;

    static {
        HttpClientDecorator decorator = SpringUtil.getBean(HttpClientDecorator.class);
        API = decorator.decorate(WechatApi.class);
    }

    public static Code2SessionResult code2Session(Code2SessionParam param) {
        auth();
        return API.code2Session(param.setAccess_token(accessToken));
    }

    private static void auth() {
        if (tokenExpTime <= new Date().getTime() / 1000 + 60) {
            GetAccessTokenResult getAccessTokenResult = API.getAccessToken(new GetAccessTokenParam());
            accessToken = getAccessTokenResult.getAccess_token();
            Integer expiresIn = getAccessTokenResult.getExpires_in();
            Assert.notBlank(accessToken, () -> Exceptions.error("微信登录失败"));
            Assert.notNull(expiresIn, () -> Exceptions.error("微信登录失败"));
            tokenExpTime = new Date().getTime() / 1000 + expiresIn;
        }
    }
}
