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

import com.alibaba.fastjson.JSONObject;
import com.kingdee.eas.custom.weaverTodo.config.WeaverTodoConfig;
import com.kingdee.eas.custom.weaverTodo.util.WeaverPushTrace;
import org.apache.log4j.Logger;

/**
 * 调用 E10 接收统一待办：receiveRequestInfo。
 */
public class WeaverReceiveTodoClient {
    private static final Logger logger = Logger.getLogger(WeaverReceiveTodoClient.class);

    private final WeaverTodoConfig config;
    private final WeaverOpenApiTokenManager tokenManager;

    public WeaverReceiveTodoClient(WeaverTodoConfig config, WeaverOpenApiTokenManager tokenManager) {
        this.config = config;
        this.tokenManager = tokenManager;
    }

    public boolean push(JSONObject payload) throws Exception {
        return push(payload, "-");
    }

    public boolean push(JSONObject payload, String traceId) throws Exception {
        String tid = traceId == null ? "-" : traceId;
        String summary = WeaverPushTrace.summarize(payload);
        logger.info("[WEAVER-TODO][" + tid + "] HTTP push BEGIN " + summary);
        String token = tokenManager.getAccessToken();
        String url = config.getOpenapiHost() + config.getReceivePath() + "?access_token=" + token;
        String bodyStr = payload.toJSONString();
        // 完整 body 单独打，便于对照 isremark；token 已拼在 URL，勿原样外传
        logger.info("[WEAVER-TODO][" + tid + "] HTTP push URL(host+path)="
                + config.getOpenapiHost() + config.getReceivePath()
                + " body=" + bodyStr);
        String resp = WeaverHttpHelper.postJson(url, bodyStr, 15000, 45000);
        boolean ok = isSuccess(resp);
        logger.info("[WEAVER-TODO][" + tid + "] HTTP push END ok=" + ok
                + " " + summary
                + " resp=" + resp);
        if (!ok) {
            logger.warn("[WEAVER-TODO][" + tid + "] HTTP push FAILED，若泛微侧状态不对请先对这条 isremark/flowid/receiver");
        }
        return ok;
    }

    static boolean isSuccess(String resp) {
        try {
            JSONObject root = JSONObject.parseObject(resp);
            JSONObject message = root.getJSONObject("message");
            if (message == null) {
                return false;
            }
            if (!"200".equals(String.valueOf(message.get("errcode")))) {
                return false;
            }
            JSONObject data = root.getJSONObject("data");
            if (data == null) {
                return true;
            }
            return "1".equals(String.valueOf(data.get("operResult")));
        } catch (Exception e) {
            logger.error("[WEAVER-TODO] 解析统一待办响应失败", e);
            return false;
        }
    }
}
