package com.ruoyi.jarvis.wecom;

import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 调用 wxSend 闲鱼自建应用文本推送，与 /wx/send/pdd 一致：Header vanToken + JSON（title、text、touser）。
 */
@Component
public class WxSendGoofishNotifyClient {

    private static final Logger log = LoggerFactory.getLogger(WxSendGoofishNotifyClient.class);

    /** 与企微 message/send 文本 content 上限对齐，预留余量 */
    private static final int CONTENT_MAX = 2000;

    @Value("${jarvis.wecom.wxsend-base-url:}")
    private String wxsendBaseUrl;

    /** 与 wxSend TokenUtil 校验一致，请求头 vanToken */
    @Value("${jarvis.wecom.wxsend-van-token:}")
    private String wxsendVanToken;

    /**
     * 接收通知的成员 UserID（企微管理后台可见），多个用英文逗号或 | 分隔；
     * 发往 wxSend 时会规范为 touser 的 user1|user2 形式。留空表示不推送。
     */
    @Value("${jarvis.wecom.goofish-notify-touser:}")
    private String goofishNotifyTouser;

    /**
     * 闲鱼订单事件通知 wxSend（由 wxSend 转企微应用消息）。
     *
     * @param orderNo   闲鱼订单号
     * @param eventType ORDER_SYNC / LOGISTICS_SYNC / SHIP
     * @param source    NOTIFY、LIST、DETAIL_REFRESH 等
     * @param message   已截断的说明文案
     */
    public void notifyGoofishEvent(String orderNo, String eventType, String source, String message) {
        if (!StringUtils.hasText(wxsendBaseUrl) || !StringUtils.hasText(wxsendVanToken)) {
            return;
        }
        String toUser = buildTouserParam(goofishNotifyTouser);
        if (!StringUtils.hasText(toUser)) {
            return;
        }
        String content = buildContent(orderNo, eventType, source, message);
        if (!StringUtils.hasText(content)) {
            return;
        }
        try {
            String base = normalizeBase(wxsendBaseUrl);
            String url = base + "/wx/send/goofish";
            postMessageReturnsOk(url, wxsendVanToken, "", content, toUser);
        } catch (Exception e) {
            log.warn("wxSend /wx/send/goofish 失败 orderNo={} err={}", orderNo, e.toString());
        }
    }

    /**
     * 京东物流扫描等：发往企微「闲鱼」自建应用，请求体与 PDD 推送一致（title + text + touser）。
     *
     * @param optionalToUser 非空时用与 logistics.push.touser.* 相同的成员 ID（逗号/| 亦可）；空则用 goofish-notify-touser
     * @param title          与 {@code LogisticsServiceImpl} 推 PDD 时的 title 一致，可为空
     * @param textBody       正文（对应 PDD 的 text）
     * @return wxSend 业务 code=200 为 true；未配置 token 或 touser 为空返回 false
     */
    public boolean pushGoofishAgentText(String optionalToUser, String title, String textBody) {
        if (!StringUtils.hasText(wxsendBaseUrl) || !StringUtils.hasText(wxsendVanToken)) {
            log.debug("wxSend 闲鱼应用物流推送跳过：未配置 wxsend-base-url 或 wxsend-van-token");
            return false;
        }
        String rawTouser = StringUtils.hasText(optionalToUser) ? optionalToUser : goofishNotifyTouser;
        String toUser = buildTouserParam(rawTouser);
        if (!StringUtils.hasText(toUser)) {
            log.warn("wxSend 闲鱼应用物流推送跳过：无接收人（请配置 jarvis.wecom.goofish-notify-touser 或 logistics.push.touser）");
            return false;
        }
        String t = title != null ? title : "";
        String body = textBody != null ? textBody : "";
        if (t.length() > CONTENT_MAX) {
            t = t.substring(0, CONTENT_MAX - 1) + "…";
            body = "";
        } else {
            int overhead = StringUtils.hasText(t) ? t.length() + 1 : 0;
            int maxBody = Math.max(0, CONTENT_MAX - overhead);
            if (body.length() > maxBody) {
                body = body.substring(0, Math.max(0, maxBody - 1)) + "…";
            }
        }
        try {
            String base = normalizeBase(wxsendBaseUrl);
            String url = base + "/wx/send/goofish";
            return postMessageReturnsOk(url, wxsendVanToken, t, body, toUser);
        } catch (Exception e) {
            log.warn("wxSend /wx/send/goofish 物流全文失败 err={}", e.toString());
            return false;
        }
    }

    private static String buildContent(String orderNo, String eventType, String source, String message) {
        StringBuilder sb = new StringBuilder();
        sb.append("【闲鱼订单】").append(orderNo != null ? orderNo : "-").append("\n");
        if (StringUtils.hasText(eventType)) {
            sb.append(eventType);
        }
        if (StringUtils.hasText(source)) {
            sb.append(" | ").append(source);
        }
        sb.append("\n");
        if (StringUtils.hasText(message)) {
            sb.append(message);
        }
        String s = sb.toString();
        if (s.length() > CONTENT_MAX) {
            return s.substring(0, CONTENT_MAX - 1) + "…";
        }
        return s;
    }

    /**
     * 逗号或 | 分隔的 UserID → 企微 API 要求的 user1|user2
     */
    private static String buildTouserParam(String raw) {
        if (!StringUtils.hasText(raw)) {
            return null;
        }
        String[] parts = raw.split("[,|]");
        List<String> ids = new ArrayList<>();
        for (String p : parts) {
            String t = p == null ? "" : p.trim();
            if (t.length() > 0) {
                ids.add(t);
            }
        }
        if (ids.isEmpty()) {
            return null;
        }
        return String.join("|", ids);
    }

    private static String normalizeBase(String base) {
        String b = base.trim();
        if (b.endsWith("/")) {
            return b.substring(0, b.length() - 1);
        }
        return b;
    }

    /**
     * 服务监控展示：闲鱼企微应用推送接口完整 URL（不发起请求）
     */
    public String getGoofishPushEndpointDisplay() {
        if (!StringUtils.hasText(wxsendBaseUrl)) {
            return "";
        }
        return normalizeBase(wxsendBaseUrl) + "/wx/send/goofish";
    }

    /**
     * 服务监控手动测试：经 wxSend 向企微「闲鱼」应用发一条文本。
     *
     * @return null 表示 HTTP 2xx 且 wxSend 返回 code=200；非空为可直接展示的失败原因
     */
    public String testGoofishNotify() {
        if (!StringUtils.hasText(wxsendBaseUrl)) {
            return "未配置 jarvis.wecom.wxsend-base-url";
        }
        if (!StringUtils.hasText(wxsendVanToken)) {
            return "未配置 jarvis.wecom.wxsend-van-token（须与 wxSend TokenUtil 一致）";
        }
        if (!StringUtils.hasText(goofishNotifyTouser)) {
            return "未配置 jarvis.wecom.goofish-notify-touser（接收人为空）";
        }
        String content = "【服务监控·闲鱼通知测试】RuoYi 手动触发 " + new java.util.Date();
        boolean ok = pushGoofishAgentText(null, "", content);
        if (ok) {
            return null;
        }
        return "推送未成功：请核对 wxSend 服务、vanToken、企微闲鱼应用及接收人，或查看服务端日志";
    }

    /**
     * POST {@code /wx/send/goofish}：body 与 {@code /wx/send/pdd} 相同字段名（title、text、touser）。
     */
    private boolean postMessageReturnsOk(String url, String vanToken, String title, String text, String touserPipeJoined)
        throws Exception {
        JSONObject body = new JSONObject();
        body.put("title", title != null ? title : "");
        body.put("text", text != null ? text : "");
        body.put("touser", touserPipeJoined);
        byte[] bytes = body.toJSONString().getBytes(StandardCharsets.UTF_8);
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setConnectTimeout(15000);
            conn.setReadTimeout(60000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("vanToken", vanToken);
            try (OutputStream os = conn.getOutputStream()) {
                os.write(bytes);
            }
            int httpCode = conn.getResponseCode();
            InputStream is = httpCode >= 200 && httpCode < 300 ? conn.getInputStream() : conn.getErrorStream();
            String resp = readAll(is);
            if (httpCode < 200 || httpCode >= 300) {
                log.warn("wxSend /wx/send/goofish HTTP {} body={}", httpCode, resp);
                return false;
            }
            Integer bizCode = null;
            try {
                JSONObject jo = JSONObject.parseObject(resp);
                if (jo != null) {
                    bizCode = jo.getInteger("code");
                }
            } catch (Exception parseEx) {
                log.debug("解析 wxSend 响应: {}", parseEx.toString());
            }
            if (bizCode != null && bizCode == 200) {
                log.debug("wxSend /wx/send/goofish OK resp={}", resp);
                return true;
            }
            log.warn("wxSend /wx/send/goofish 业务未成功 resp={}", resp);
            return false;
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    private static String readAll(InputStream is) throws java.io.IOException {
        if (is == null) {
            return "";
        }
        byte[] buf = new byte[4096];
        StringBuilder sb = new StringBuilder();
        int n;
        while ((n = is.read(buf)) >= 0) {
            sb.append(new String(buf, 0, n, StandardCharsets.UTF_8));
        }
        return sb.toString();
    }
}
