package com.docus.server.archive.utils;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 使用JaxWsDynamicClientFactory 调用 webservice
 *
 * @author wyb
 */
public class JaxWsDynamicClientUtil {

    private static final JaxWsDynamicClientFactory CLIENT_FACTORY = JaxWsDynamicClientFactory.newInstance();
    private static final Map<String, Client> CLIENT_MAP = new ConcurrentHashMap<>();
    private static final Logger logger = LoggerFactory.getLogger(JaxWsDynamicClientUtil.class);

    public static String send(String wsdlUrl, String namespaceUri, String operationName, Object[] params) {
        logger.info("wsdlUrl：" + wsdlUrl + " ,namespaceUri: " + namespaceUri + " ，operationName：" + operationName + "，param:" + Arrays.toString(params));
        try {
            Client client = getClient(wsdlUrl);
            Object[] result;
            if (namespaceUri == null || namespaceUri.isEmpty()) {
                result = client.invoke(operationName, params);
            } else {
                QName qName = new QName(namespaceUri, operationName);
                result = client.invoke(qName, params);
            }
            logger.info("wsdlUrl：" + wsdlUrl + ",namespaceUri: " + namespaceUri + " ，operationName：" + operationName + "，param:" + Arrays.toString(params) + " 调用成功！");
            if (result == null || result[0] == null) {
                return null;
            }
            return String.valueOf(result[0]);
        } catch (Exception ex) {
            logger.error("wsdlUrl：" + wsdlUrl + ",namespaceUri: " + namespaceUri + " ，operationName：" + operationName + "，param:" + Arrays.toString(params) + " 调用失败了！_"+ex.getMessage(), ex);
            return null;
        }
    }

    public static Client getClient(String wsdlUrl) {
        if (CLIENT_MAP.get(wsdlUrl) == null) {
            synchronized (JaxWsDynamicClientUtil.class) {
                if (CLIENT_MAP.get(wsdlUrl) == null) {
                    Client client = CLIENT_FACTORY.createClient(wsdlUrl);
                    setClientParam(client);
                    CLIENT_MAP.put(wsdlUrl, client);
                }
            }
        }
        return CLIENT_MAP.get(wsdlUrl);
    }

    private static void setClientParam(Client client) {
        HTTPClientPolicy httpClientPolicy = new HTTPClientPolicy();
        httpClientPolicy.setConnectionTimeout(30 * 1000);
        httpClientPolicy.setAllowChunking(false);
        httpClientPolicy.setReceiveTimeout(30 * 1000);
        HTTPConduit clientConduit = (HTTPConduit) client.getConduit();
        clientConduit.setClient(httpClientPolicy);
    }
}
