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

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

/**
 * 调用 E10 消息中心 sendMsg，用于 BMC 通知（非统一待办）。
 */
public class WeaverSendMsgClient {
    private static final Logger logger = Logger.getLogger(WeaverSendMsgClient.class);

    private final WeaverTodoConfig config;
    private final WeaverOpenApiTokenManager tokenManager;

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

    /**
     * 调用 sendMsg，返回对方原始响应 JSON（写入 OAMsgCallLog.ResponseResult）。
     */
    public String push(JSONObject payload, String traceId) throws Exception {
        String tid = traceId == null ? "-" : traceId;
        logger.info("[WEAVER-TOREAD][" + tid + "] HTTP sendMsg BEGIN title="
                + payload.getString("title")
                + " eventId=" + payload.get("eventId")
                + " moduleId=" + payload.get("moduleId"));
        String token = tokenManager.getAccessToken();
        String url = config.getOpenapiHost() + config.getSendMsgPath() + "?access_token=" + token;
        String bodyStr = payload.toJSONString();
        logger.info("[WEAVER-TOREAD][" + tid + "] HTTP sendMsg URL(host+path)="
                + config.getOpenapiHost() + config.getSendMsgPath()
                + " body=" + bodyStr);
        String resp = WeaverHttpHelper.postJson(url, bodyStr, 15000, 45000);
        boolean ok = isSuccess(resp);
        logger.info("[WEAVER-TOREAD][" + tid + "] HTTP sendMsg END ok=" + ok + " resp=" + resp);
        if (!ok) {
            logger.warn("[WEAVER-TOREAD][" + tid + "] HTTP sendMsg FAILED");
        }
        return resp == null ? "" : resp;
    }

    public static boolean isSuccess(String resp) {
        try {
            JSONObject root = JSONObject.parseObject(resp);
            if (root == null) {
                return false;
            }
            Object code = root.get("code");
            if (code == null || !"200".equals(String.valueOf(code))) {
                return false;
            }
            Object status = root.get("status");
            if (status == null) {
                return true;
            }
            if (status instanceof Boolean) {
                return ((Boolean) status).booleanValue();
            }
            String s = String.valueOf(status);
            return "true".equalsIgnoreCase(s) || "1".equals(s) || "成功".equals(s);
        } catch (Exception e) {
            logger.error("[WEAVER-TOREAD] 解析 sendMsg 响应失败", e);
            return false;
        }
    }
}
