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.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 {
        API = SpringUtil.getBean(WechatApi.class);
    }

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

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