package com.njzscloud.supervisory.gps.jike.support;

import cn.hutool.extra.spring.SpringUtil;
import com.njzscloud.common.http.constant.HttpMethod;
import com.njzscloud.common.http.interceptor.RequestInterceptor;
import com.njzscloud.supervisory.config.JikeProperties;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 即刻物联请求拦截器 - 处理签名
 */
public class JikeRequestInterceptor implements RequestInterceptor {

    @Override
    public Object[] process(HttpMethod method, String url, Object[] args) {
        JikeProperties jikeProperties = SpringUtil.getBean(JikeProperties.class);
        String appId = jikeProperties.getAppId();
        String secret = jikeProperties.getSecretKey();

        // 获取时间戳
        long timestamp = System.currentTimeMillis();

        // 构建请求头
        Map<String, String> headers = new HashMap<>();
        headers.put("x-jk-appid", appId);
        headers.put("x-jk-timestamp", String.valueOf(timestamp));

        // 处理参数签名
        String paramMd5 = "";
        String bodyMd5 = "";

        if (args != null && args.length > 0) {
            Object param = args[0];
            if (param instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, String> params = (Map<String, String>) param;

                if (method == HttpMethod.GET) {
                    // GET请求: x-jk-param-signature = MD5(参数拼接)
                    paramMd5 = JikeSignUtil.buildParamSignature(params);
                    headers.put("x-jk-param-signature", paramMd5);
                } else if (method == HttpMethod.POST) {
                    // POST请求: 需要body签名
                    if (args.length > 1 && args[1] instanceof String) {
                        bodyMd5 = JikeSignUtil.md5Hex((String) args[1]);
                    }
                    headers.put("x-jk-body-signature", bodyMd5);
                    // POST带body时,body参与签名
                    paramMd5 = JikeSignUtil.buildPostParamSignature(params, bodyMd5);
                    headers.put("x-jk-param-signature", paramMd5);
                }
            }
        } else {
            // 无参数时
            headers.put("x-jk-param-signature", "");
            if (method == HttpMethod.POST) {
                headers.put("x-jk-body-signature", "");
            }
        }

        // 计算最终签名
        String finalSign = JikeSignUtil.buildFinalSignature(appId, bodyMd5, paramMd5, secret, timestamp);
        headers.put("x-jk-signature", finalSign);

        // 返回 headers 和原始参数
        Object[] result = new Object[args != null ? args.length + 1 : 2];
        result[0] = headers;
        for (int i = 0; i < (args != null ? args.length : 0); i++) {
            result[i + 1] = args[i];
        }

        return result;
    }
}
