package com.ruoyi.yunxin.interceptor;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.ruoyi.yunxin.config.YunxinProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class GlodonTokenInterceptor implements Interceptor {

    @Autowired
    private YunxinProperties yunxinProperties;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        String nonce = UUID.fastUUID().toString();
        String curTime = DateUtil.currentSeconds() + "";
        request.addHeader("AppKey",yunxinProperties.getAppKey());
        request.addHeader("Nonce", nonce);
        request.addHeader("CurTime", curTime);
        request.addHeader("CheckSum", yunxinProperties.getAppSecret()+nonce+curTime);
        return true;
    }

    @Override
    public void onSuccess(Object data, ForestRequest request, ForestResponse response) {
        log.info("onSuccess URI:{},QueryValues:{},耗时:{}ms,Param:{},RespStatus:{},Response:{}",
                request.getURI(),
                JSON.toJSONString(request.getQueryValues()),
                response.getTimeAsMillisecond(),
                JSONObject.toJSONString(request.getArguments()),
                response.getStatusCode(),
                response.getContent());
    }

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        log.info("onError URI:{},QueryValues:{},耗时:{}ms,Param:{},RespStatus:{},Response:{}",
                request.getURI(),
                JSON.toJSONString(request.getQueryValues()),
                response.getTimeAsMillisecond(),
                JSONObject.toJSONString(request.getArguments()),
                response.getStatusCode(),
                response.getContent());
    }

}
