package com.njzscloud.supervisory.gps.tuqiang.jimi.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.supervisory.gps.tuqiang.jimi.OauthTokenGetParam;
import com.njzscloud.supervisory.gps.tuqiang.jimi.OauthTokenGetResult;
import com.njzscloud.supervisory.gps.tuqiang.jimi.OauthTokenRefreshParam;
import com.njzscloud.supervisory.gps.tuqiang.jimi.OauthTokenRefreshResult;
import com.njzscloud.supervisory.gps.tuqiang.jimi.support.JimiApi;
import com.njzscloud.supervisory.gps.tuqiang.jimi.support.JimiParam;

import java.util.Date;

public class JimiUtil {
    private static final JimiApi API = SpringUtil.getBean(JimiApi.class);

    private static String accessToken = "";
    private static String refreshToken = "";
    private static long tokenCreateTime = 0;

    public static <T> T request(JimiParam<T> jimiParam) {
        auth();
        jimiParam.setAccess_token(accessToken);
        return API.doRequest(jimiParam);
    }

    private static void auth() {
        if (tokenCreateTime == 0) {
            OauthTokenGetResult oauthTokenGetResult = API.doRequest(new OauthTokenGetParam());
            if (!oauthTokenGetResult.isSucc()) {
                accessToken = "";
                refreshToken = "";
                tokenCreateTime = 0;
                return;
            }
            accessToken = oauthTokenGetResult.getResult().getAccessToken();
            refreshToken = oauthTokenGetResult.getResult().getRefreshToken();
            tokenCreateTime = DateUtil.parse(oauthTokenGetResult.getResult().getTime()).getTime() / 1000;
            return;
        }

        if (tokenCreateTime < new Date().getTime() / 1000 + 60) {
            OauthTokenRefreshResult oauthTokenRefreshResult = API.doRequest(new OauthTokenRefreshParam()
                    .setAccess_token(accessToken)
                    .setRefresh_token(refreshToken)
            );
            if (!oauthTokenRefreshResult.isSucc()) {
                accessToken = "";
                refreshToken = "";
                tokenCreateTime = 0;
            }
            accessToken = oauthTokenRefreshResult.getResult().getAccessToken();
            refreshToken = oauthTokenRefreshResult.getResult().getRefreshToken();
            tokenCreateTime = DateUtil.parse(oauthTokenRefreshResult.getResult().getTime()).getTime() / 1000;
            return;
        }

    }
}
