package com.ruoyi.logistics.util;
import com.ruoyi.common.core.utils.uuid.UUID;
import com.ruoyi.logistics.config.SFExpressConfig;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import static com.sf.csim.express.service.CallExpressServiceTools.getMsgDigest;

public class SFExpressHttpUtil {
    private String partnerID;
    private String checkWord;
    private String url;
    public SFExpressHttpUtil(String partnerID, String checkWord,String url) {
        this.partnerID = partnerID;
        this.checkWord = checkWord;
        this.url = url;

    }
    /**
     * 生成MD5数字签名
     */
    public String generateMsgDigest(String msgData) {
        try {
            String timeStamp = String.valueOf(System.currentTimeMillis());
          /*  String signStr = msgData + checkWord;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(signStr.getBytes(StandardCharsets.UTF_8));
            String md5Str = bytesToHex(digest);
            return Base64.getEncoder().encodeToString(md5Str.getBytes(StandardCharsets.UTF_8));
            */
            return  getMsgDigest(msgData,timeStamp,checkWord);
        } catch (Exception e) {
            throw new RuntimeException("生成签名失败", e);
        }
    }
/*

    private String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }*/

    /**
     * 发送API请求
     */
    public String sendRequest(String serviceCode, String msgData) {
        return sendRequest(serviceCode, msgData, null);
    }

    public String sendRequest(String serviceCode, String msgData, String requestId) {
        try {
            String requestID = requestId != null ? requestId : UUID.randomUUID().toString();
            long timestamp = System.currentTimeMillis();
            String msgDigest = generateMsgDigest(msgData);
            Map<String, String> params = new HashMap<>();
            params.put("partnerID", partnerID);
            params.put("requestID", requestID);
            params.put("serviceCode", serviceCode);
            params.put("timestamp", String.valueOf(timestamp));
            params.put("msgDigest", msgDigest);
            params.put("msgData", msgData);
            return doPost(url, params);
        } catch (Exception e) {
            throw new RuntimeException("调用顺丰API失败", e);
        }
    }

    private String doPost(String url, Map<String, String> params) throws IOException {
        HttpURLConnection connection = null;
        try {
            URL apiUrl = new URL(url);
            connection = (HttpURLConnection) apiUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setConnectTimeout(30000);
            connection.setReadTimeout(30000);
            connection.setDoOutput(true);
            connection.setDoInput(true);
            StringBuilder postData = new StringBuilder();
            for (Map.Entry<String, String> param : params.entrySet()) {
                if (postData.length() != 0) postData.append('&');
                postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                postData.append('=');
                postData.append(URLEncoder.encode(param.getValue(), "UTF-8"));
            }
            try (OutputStream os = connection.getOutputStream()) {
                byte[] postDataBytes = postData.toString().getBytes(StandardCharsets.UTF_8);
                os.write(postDataBytes);
                os.flush();
            }
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                try (BufferedReader in = new BufferedReader(
                        new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = in.readLine()) != null) {
                        response.append(line);
                    }
                    return response.toString();
                }
            } else {
                throw new IOException("HTTP请求失败，状态码: " + responseCode);
            }

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

}
