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;

import java.security.MessageDigest;

@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", getCheckSum(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());
    }

    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

}
