package org.hzhub.workflow.wecom;

import cn.hutool.core.util.XmlUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hzhub.workflow.service.IWecomApprovalService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;

/**
 * 企业微信审批回调
 * <p>接收审批状态变化通知，异步刷新本地数据</p>
 *
 * @author hzhub
 */
@Slf4j
@RestController
@RequestMapping("/wecom/callback")
@RequiredArgsConstructor
public class WecomCallbackController {

    private final IWecomApprovalService wecomApprovalService;
    private final WecomConfig wecomConfig;

    /**
     * 接收企业微信审批状态变化通知
     * <p>WeCom 推送 XML 格式的回调事件到该接口</p>
     */
    @PostMapping("/approval")
    public String receiveApprovalCallback(@RequestBody String xmlBody) {
        log.debug("收到企业微信审批回调: {}", xmlBody);
        try {
            Document doc = XmlUtil.parseXml(xmlBody);

            // 提取关键信息
            String spNo = getNodeText(doc, "sp_no");
            String event = getNodeText(doc, "Event");

            if (spNo != null && "change_approval".equals(event)) {
                log.info("收到审批状态变化通知, sp_no={}, 异步刷新详情", spNo);
                // 异步拉取最新详情
                asyncSyncDetail(spNo);
            }

            // 返回 success 告知企业微信接收成功
            return "success";
        } catch (Exception e) {
            log.error("处理企业微信审批回调异常", e);
            return "success"; // 仍然返回success，避免企业微信重试
        }
    }

    @Async
    public void asyncSyncDetail(String spNo) {
        try {
            wecomApprovalService.syncApprovalDetail(spNo);
        } catch (Exception e) {
            log.error("回调同步审批详情失败: {}", spNo, e);
        }
    }

    /**
     * 从 XML Document 中提取指定标签的文本内容
     */
    private String getNodeText(Document doc, String tagName) {
        var nodes = doc.getElementsByTagName(tagName);
        if (nodes.getLength() == 0) return null;
        return nodes.item(0).getTextContent();
    }

    /**
     * URL 验证（首次配置回调地址时企业微信会发送 GET 请求验证）
     */
    @GetMapping("/approval")
    public String verifyCallbackUrl(
        @RequestParam("msg_signature") String msgSignature,
        @RequestParam("timestamp") String timestamp,
        @RequestParam("nonce") String nonce,
        @RequestParam("echostr") String echostr) {
        log.info("企业微信回调URL验证: msgSignature={}, timestamp={}, nonce={}", msgSignature, timestamp, nonce);
        return echostr;
    }
}
