package com.jianshui.api.config;

import cn.hutool.core.util.XmlUtil;
import org.w3c.dom.*;

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();
                // 修改CDATA标签位置
                addCDataToLeafNodes(dataNode);
//                CDATASection cdata = dataNode.getOwnerDocument().createCDATASection(XmlUtil.toStr(dataNode,"GBK",false,false));
//                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;
    }

    /**
    * @Author: kk
    * @Description: CDATA类
    * @DateTime: 2023/6/5 19:12
    * @Params:
    * @Return
    */

    public static void addCDataToLeafNodes(Node node) {
        NodeList childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node childNode = childNodes.item(i);
            if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                addCDataToLeafNodes(childNode);
            }
            else if (childNode.getNodeType() == Node.TEXT_NODE) {
                CDATASection cdata = childNode.getOwnerDocument().createCDATASection(childNode.getNodeValue());
                node.removeChild(childNode);
                node.appendChild(cdata);
            }
        }
    }


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

    @Override
    public void close(MessageContext context) {

    }
}
