package com.miyzh.service;

import com.alibaba.fastjson.JSONObject;
import com.miyzh.utils.JaxWsDynamicClientFactory;
import lombok.extern.slf4j.Slf4j;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.endpoint.Endpoint;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.service.model.BindingInfo;
import org.apache.cxf.service.model.BindingOperationInfo;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.springframework.stereotype.Service;

import javax.xml.namespace.QName;
import java.util.HashMap;
import java.util.Map;

/**
 * description: WsService
 * date: 2020/6/16 9:40
 * author: SZQ
 */
@Slf4j
@Service
public class WsClientService {

    public static String callWebSV(String wsdUrl, String operationName, String... params) throws Exception {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(wsdUrl);
        // 设置超时单位为毫秒
        HTTPConduit conduit = (HTTPConduit)client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(60 * 1000);
        policy.setAllowChunking(false);
        policy.setReceiveTimeout(60 * 1000);
        conduit.setClient(policy);
        //处理 WebService接口和实现类namespace不同的情况
        // CXF动态客户端在处理此问题时，会报No operation was found with the name的异常
        Endpoint endpoint = client.getEndpoint();
        QName opName = new QName(endpoint.getService().getName().getNamespaceURI(), operationName);
        BindingInfo bindingInfo = endpoint.getEndpointInfo().getBinding();
        if (bindingInfo.getOperation(opName) == null) {
            for (BindingOperationInfo operationInfo : bindingInfo.getOperations()) {
                if (operationName.equals(operationInfo.getName().getLocalPart())) {
                    opName = operationInfo.getName();
                    break;
                }
            }
        }
        //client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects;
        // invoke("方法名",参数1,参数2,参数3....);
        objects = client.invoke(opName, params);
        log.info(objects[0].toString());
        if (objects[0].toString().contains("<response>")) {
            Document doc = DocumentHelper.parseText(objects[0].toString());
            Map<String,Object> map = new HashMap<>();
            map.put("resultCode", doc.getRootElement().element("resultCode").getTextTrim());
            map.put("resultContent", doc.getRootElement().element("resultContent").getTextTrim());
            return new JSONObject(map).toJSONString();
        }
        return objects[0].toString();
    }


}
