package com.ruoyi.oa.utils;

import com.yundasys.OpenApiHttpUtils;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.oa.domain.vo.OaExpressVo;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;

public class YdRouteQueryUtil {
    // 请根据实际环境切换key/secret
    private static final String APP_KEY = "004160"; // 生产环境
    private static final String APP_SECRET = "ac9ee46d749e44b98e7a9e38f3c8f8f3"; // 生产环境
    private static final String API_URL = "https://openapi.yundaex.com/openapi/outer/logictis/query";

    /**
     * 查询韵达轨迹
     * @param mailNo 运单号
     * @return 查询结果JSON
     */
    public static String queryRoute(String mailNo) {
        String jsonParams = "{\"mailno\":\"" + mailNo + "\"}";
        return OpenApiHttpUtils.doPostJson(API_URL, jsonParams, APP_KEY, APP_SECRET);
    }

    /**
     * 解析韵达返回数据，转为OaExpressVo
     */
    public static OaExpressVo parseData(String result) {
        if (result == null || result.trim().isEmpty()) {
            return null;
        }
        try {
            JSONObject json = JSON.parseObject(result);
            JSONObject data = json.getJSONObject("data");
            if (data == null) return null;
            JSONArray steps = data.getJSONArray("steps");
            if (steps == null || steps.isEmpty()) return null;
            JSONObject last = steps.getJSONObject(steps.size() - 1);
            OaExpressVo vo = new OaExpressVo();
            vo.setExpressCode(data.getString("mailno"));
            vo.setLastUpdateTime(last.getDate("time"));
            vo.setLastStatus(last.getString("action"));
            vo.setRemark(last.getString("description"));
            return vo;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // MD5签名算法（如需自定义签名，可用此方法）
    public static String md5(String str, String charset) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(str.getBytes(charset));
        byte[] result = md.digest();
        StringBuilder sb = new StringBuilder(32);
        for (byte b : result) {
            int val = b & 0xff;
            if (val <= 0xf) sb.append("0");
            sb.append(Integer.toHexString(val));
        }
        return sb.toString().toLowerCase();
    }

    // main方法测试
    public static void main(String[] args) {
        String mailNo = "464569453467736";
        String result = queryRoute(mailNo);
        System.out.println("韵达原始返回：" + result);
        OaExpressVo vo = parseData(result);
        System.out.println("解析后：" + vo);
    }
} 