package com.kingdee.eas.custom.weaverTodo.util;

import com.alibaba.fastjson.JSONObject;

import java.util.UUID;

/**
 * 待办推送对账用：traceId + 关键字段摘要 + 平台调用栈提示。
 */
public final class WeaverPushTrace {

    private WeaverPushTrace() {
    }

    public static String nextId() {
        return UUID.randomUUID().toString().replace("-", "").substring(0, 12);
    }

    public static String summarize(JSONObject payload) {
        if (payload == null) {
            return "payload=null";
        }
        return "syscode=" + payload.getString("syscode")
                + " flowid=" + payload.getString("flowid")
                + " receiver=" + payload.getString("receiver")
                + " isremark=" + payload.getString("isremark")
                + " viewtype=" + payload.getString("viewtype")
                + " requestStatus=" + payload.getString("requestStatus")
                + " workflowname=" + payload.getString("workflowname")
                + " nodename=" + payload.getString("nodename")
                + " receivets=" + payload.getString("receivets")
                + " requestname=" + cut(payload.getString("requestname"), 80);
    }

    public static String callerHint() {
        StackTraceElement[] stack = Thread.currentThread().getStackTrace();
        StringBuilder sb = new StringBuilder();
        int kept = 0;
        for (int i = 0; i < stack.length; i++) {
            StackTraceElement e = stack[i];
            String cn = e.getClassName();
            if (cn.startsWith("com.kingdee.eas.custom.weaverTodo")) {
                continue;
            }
            if (cn.startsWith("java.") || cn.startsWith("sun.") || cn.startsWith("jdk.")) {
                continue;
            }
            if (cn.startsWith("org.apache.log4j") || cn.startsWith("org.apache.logging")) {
                continue;
            }
            if (sb.length() > 0) {
                sb.append(" <- ");
            }
            sb.append(simpleName(cn)).append('.').append(e.getMethodName())
                    .append(':').append(e.getLineNumber());
            kept++;
            if (kept >= 8) {
                break;
            }
        }
        return sb.length() == 0 ? "(no-caller)" : sb.toString();
    }

    private static String simpleName(String cn) {
        int dot = cn.lastIndexOf('.');
        return dot >= 0 ? cn.substring(dot + 1) : cn;
    }

    private static String cut(String s, int max) {
        if (s == null) {
            return "";
        }
        return s.length() <= max ? s : s.substring(0, max) + "...";
    }
}
