package com.malk.mcli.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.helpers.IOUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.io.CachedOutputStream;
import org.apache.cxf.phase.AbstractPhaseInterceptor;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Slf4j
public class WsOutInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    public WsOutInterceptor(String phase) {
        super(phase);
    }

    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        try {
            // 从流中获取返回内容
            OutputStream os = message.getContent(OutputStream.class);
            CachedStream cs = new CachedStream();
            message.setContent(OutputStream.class, cs);
            message.getInterceptorChain().doIntercept(message);
            CachedOutputStream cachedOutputStream = (CachedOutputStream) message.getContent(OutputStream.class);
            InputStream in = cachedOutputStream.getInputStream();
            String output = IOUtils.toString(in, "UTF-8");
            // 修改内容为集成平台要求的格式
            output = output.replace("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">", "<soapenv:Envelope xmlns:soapenv=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">")
                    .replace("</soap:Envelope>", "</soapenv:Envelope>")
                    .replace("<soap:Body>", "<soapenv:Body>")
                    .replace("</soap:Body>", "</soapenv:Body>")
                    .replace("<ns2:getDataResponse xmlns:ns2=\"http://server.dandelion.com\">", "")
                    .replace("</ns2:getDataResponse>", "").replace("ns2:InvokeResponse", "InvokeResponse");
            ;
            log.info("ns2:InvokeResponse, {}", output);
            output = "<string xmlns=\"http://tempuri.org/\">{\"ResultCode\":\"0\",\"Message\":\"\",\"Schema\":{\"Code\":\"Student\",\"Items\":[]},\"Data\":{}}</string>";
            // 处理完后写回流中
            IOUtils.copy(new ByteArrayInputStream(output.getBytes()), os);
            cs.close();
            os.flush();
            message.setContent(OutputStream.class, os);
        } catch (Exception e) {
            System.out.println(String.format("解析报文异常: %s", e.getMessage()));
        }
    }

    private static class CachedStream extends CachedOutputStream {
        public CachedStream() {
            super();
        }

        @Override
        protected void doFlush() throws IOException {
            currentStream.flush();
        }

        @Override
        protected void doClose() throws IOException {
        }

        @Override
        protected void onWrite() throws IOException {
        }
    }
}
