package com.jianshui.api.config;

import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.CDATASection;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Set;

/**
 * @Description
 * @Author 巩权林
 * @Date 2023/3/10 15:43
 **/
public class WebserviceResponseHandler implements SOAPHandler<SOAPMessageContext> {
    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        SOAPMessage message = context.getMessage();
        Boolean outbound = (Boolean) context.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);
        if (outbound) {
            // 处理传出的SOAP消息
            try {
                SOAPBody body = message.getSOAPBody();
                Node returnNode = body.getFirstChild().getFirstChild();
                Node dataNode = returnNode.getFirstChild();
                CDATASection cdata = dataNode.getOwnerDocument().createCDATASection(XmlUtil.toStr(dataNode));
                returnNode.removeChild(dataNode);
                returnNode.appendChild(cdata);
                // body.getFirstChild().removeChild(body.getFirstChild().getFirstChild());
                // CDATASection cdata = Data.getOwnerDocument().createCDATASection(XmlUtil.toStr(fp, "GBK", false, true));
                // body.setTextContent(XmlUtil.toStr(body.getFirstChild()));
                message.saveChanges();
            } catch (SOAPException e) {
                throw new RuntimeException(e);
            }
        } else {
            // 处理传入的SOAP消息
        }
        return true;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    @Override
    public void close(MessageContext context) {

    }
}
