package com.ruoyi.oa.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.oa.domain.vo.OaExpressVo;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class YtRouteQueryUtil {
    // 请填写你自己的密钥、method、v
    private static final String SECRET = "TEST";
    private static final String METHOD = "123456"; // 示例
    private static final String VERSION = "v1"; // 示例
    private static final String API_URL = " https://openuat.yto56test.com:6443/open/track_query_adapter/v1/hpLkUl/TEST";

    // 圆通签名算法 param+method+v+secret，MD5后Base64
    public static String sign(String param, String method, String v, String secret) {
        String data = param + method + v;
        byte[] md5 = DigestUtils.md5(data + secret);
        return Base64.encodeBase64String(md5);
    }

    /**
     * 查询圆通轨迹
     * @param number 运单号
     * @return 查询结果JSON
     */
    public static String queryRoute(String number) {
        try {
            String timestamp = String.valueOf(System.currentTimeMillis());
            JSONObject paramObj = new JSONObject();
            paramObj.put("NUMBER", number);
            String param = paramObj.toJSONString();
            String sign = sign(param, METHOD, VERSION, SECRET);
            JSONObject req = new JSONObject();
            req.put("timestamp", timestamp);
            req.put("param", param);
            req.put("sign", sign);
            req.put("format", "JSON");
            req.put("method", METHOD);
            req.put("v", VERSION);
            String jsonParams = req.toJSONString();
            URL url = new URL(API_URL);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            OutputStream out = conn.getOutputStream();
            out.write(jsonParams.getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
            StringBuilder sbResult = new StringBuilder();
            if (200 == conn.getResponseCode()) {
                BufferedReader responseReader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
                String readLine;
                while ((readLine = responseReader.readLine()) != null) {
                    sbResult.append(readLine).append("\n");
                }
                responseReader.close();
            }
            return sbResult.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 解析圆通返回数据，转为OaExpressVo列表
     */
    public static OaExpressVo parseData(String result) {
        if (result == null || result.trim().isEmpty()) {
            return null;
        }
        try {
            if (result.trim().startsWith("{")) {
                JSONObject json = JSON.parseObject(result);
                if (json.containsKey("map")) return null; // 查询为空
            } else if (result.trim().startsWith("[")) {
                JSONArray arr = JSON.parseArray(result);
                if (arr.isEmpty()) return null;
                JSONObject last = arr.getJSONObject(arr.size() - 1);
                OaExpressVo vo = new OaExpressVo();
                vo.setExpressCode(last.getString("waybill_No"));
                vo.setLastUpdateTime(last.getDate("upload_Time"));
                vo.setLastStatus(last.getString("infoContent"));
                vo.setRemark(last.getString("processInfo"));
                return vo;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // main方法测试
    public static void main(String[] args) {
        String number = "YT2600227881409"; // 测试单号
        String result = queryRoute(number);
        System.out.println("圆通原始返回：" + result);
        OaExpressVo vo = parseData(result);
        if (vo != null) {
            System.out.println("解析后：" + vo);
        } else {
            System.out.println("解析后无数据");
        }
    }
} 