package com.ruoyi.oa.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.zto.zop.ZopClient;
import com.zto.zop.ZopPublicRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

import static com.zto.zop.EncryptionType.MD5;
import com.ruoyi.oa.domain.vo.OaExpressVo;
import liquibase.pro.packaged.J;
import org.apache.commons.lang3.StringUtils;
import com.ruoyi.common.utils.DateUtils;
import org.aspectj.weaver.ast.Expr;

public class ZtoTrackQueryUtil {
    // 替换为你的appKey和appSecret
    private static final String APP_KEY = "1ebf01ae01cc81d78ba9a";
    private static final String APP_SECRET = "4bded7f302da7f7913b01810e3421b80";
    // 测试环境
//    private static final String API_URL = "https://japi-test.zto.com/zto.merchant.waybill.track.query";
    // 正式环境
     private static final String API_URL = "https://japi.zto.com/zto.merchant.waybill.track.query";

    /**
     * 查询中通物流轨迹
     *
     * @param billCode 运单号
     * @return 查询结果JSON
     */
    public static OaExpressVo queryTrack(String billCode,String phoneNumber) throws IOException {

        ZopClient client = new ZopClient(APP_KEY, APP_SECRET);
        ZopPublicRequest request = new ZopPublicRequest();
        request.setBody("{\"billCode\":\""+billCode+"\",\"mobilePhone\":\""+ StringUtils.right(phoneNumber, 4)+"\"}");
        request.setUrl(API_URL);
        request.setBase64(true);
        request.setEncryptionType(MD5);
        request.setTimestamp(null);
        String execute = client.execute(request);
        System.out.println(execute);
        return parseData(execute);
    }

    /**
     * 解析中通返回数据，封装为OaExpressVo
     */
    public static OaExpressVo parseData(String result) {
        if (StringUtils.isBlank(result)) {
            return null;
        }
        try {
            JSONObject json = JSON.parseObject(result);
            if (json == null || !"true".equalsIgnoreCase(String.valueOf(json.get("status")))) {
                return null;
            }
            // 取result数组
            if (!json.containsKey("result")) {
                return null;
            }
            // 只取第一个轨迹（如有多条）
            Object resultArr = json.get("result");
            if (!(resultArr instanceof java.util.List)) {
                return null;
            }
            JSONArray arr = json.getJSONArray("result");
            if (arr == null || arr.isEmpty()) {
                return null;
            }
            JSONObject first = arr.getJSONObject(arr.size() - 1); // 取最后一条为最新
            if (first == null) {
                return null;
            }
            String scanDate = first.getString("scanDate");
            String desc = first.getString("desc");
            OaExpressVo vo = new OaExpressVo();
            // scanDate为时间戳字符串
            if (StringUtils.isNotBlank(scanDate)) {
                try {
                    long time = Long.parseLong(scanDate);
                    vo.setAcceptTime(new java.util.Date(time));
                } catch (Exception e) {
                    vo.setAcceptTime(null);
                }
            }
            vo.setFirstStatusName(desc);
            return vo;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getPublicIp() {
        String ip = "";
        try {
            URL url = new URL("http://ifconfig.me/ip");
            BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
            ip = in.readLine();
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ip;
    }

    // main方法测试
    public static void main(String[] args) throws IOException {
        System.out.println("本机公网IP为: " + getPublicIp());
        String billCode = "78925013374727";
        OaExpressVo result = queryTrack(billCode,"2410");

        System.out.println(result);
    }
} 