package com.nmgs.util;

import com.alibaba.fastjson.JSONObject;
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 java.util.Map;

public class WebServiceUtil {
    public static Logger logger = LoggerFactory.getLogger("PSAM");
//    public static Call LWZXCommonServicePsamAuthCall;

    public static String toWebService(String path, String methodName, String params) {
        // 创建动态客户端
        Client client = getClient(path);
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        //json的形式
        //JSONObject jsonMap = new JSONObject(params);
        if (params != null && !params.trim().equals("")) {
            try {
                Map<String, Object> map = com.alibaba.fastjson.JSONObject.parseObject(params);
            } catch (Exception e) {
               // LogUtil.error(params + "--jsonParams参数格式不正确，请确认是json的Key：Value格式！", WebServiceUtil.class);
                return params + "--jsonParams参数格式不正确，请确认是json的Key：Value格式！";
            }
            Object[] aaa = new Object[]{params};
            try {
                objects = client.invoke(methodName, aaa);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            try {
                objects = client.invoke(methodName);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }

    public static Map<String, Object> toWebService(String path, String WebServiceName, Map<String, Object> params) {
        // 创建动态客户端
        Client client = getClient(path);
        try {
            Object[] objects;
            //json的形式
            JSONObject jsonMap = new JSONObject(params);
            objects = client.invoke(WebServiceName, new Object[]{jsonMap.toString()});
            if (objects.length > 0) {
                return getResult(objects[0].toString());
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String toWebService(String path, String methodName, Object[] params) {
        // 创建动态客户端
        Client client = getClient(path);
        Object[] objects;
        try {
            objects = client.invoke(methodName, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }

    public static Object toWCFWebService(String path, String methodName, Object[] params) {
        // 创建动态客户端
        Client client = getClient(path);
        Object[] objects;
        try {
            objects = client.invoke(methodName, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0];
        } else {
            return null;
        }
    }

    public static String toWebService(String path, String methodName) {
        // 创建动态客户端
        Client client = getClient(path);
        Object[] objects;
        try {
            objects = client.invoke(methodName);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }

    public static String toWebService(String path, String methodName, Object[] params, int timeOut) {
        // 创建动态客户端
        Client client = getClient(path, timeOut);
        Object[] objects;
        try {
            objects = client.invoke(methodName, params);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }

   /* private static void trustAllHttpsCertficates() {
        TrustManager[] trustManagers = new TrustManager[1];
        TrustManager tm = new miTM();
        trustManagers[0] = tm;
        SSLContext sc = null;
        try {
            sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    }*/

   /* public String toHRWebService(String path, String methodName, Object[] params) {
        //跳过HTTPS访问接口
        trustAllHttpsCertficates();
        // 创建动态客户端
        Client client = getHRClient(path);
        Object[] objects;
        try {
            objects = client.invoke(methodName, params);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (objects.length > 0) {
            return objects[0].toString();
        } else {
            return null;
        }
    }*/

    public static Client getHRClient(String path) {
        // 创建动态客户端
        int CXF_CLIENT_CONNECT_TIMEOUT = 2 * 1000;
        int CXF_CLIENT_RECEIVE_TIMEOUT = 2 * 1000;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//        dcf.setJaxbContextProperties();
        Client client = dcf.createClient(path);
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        conduit.setClient(policy);
        return client;
    }

    public static Client getClient(String path) {
        // 创建动态客户端
        int CXF_CLIENT_CONNECT_TIMEOUT = 40 * 10000;
        int CXF_CLIENT_RECEIVE_TIMEOUT = 40 * 10000;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
//        dcf.setJaxbContextProperties();
        Client client = dcf.createClient(path);
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        conduit.setClient(policy);
        return client;
    }

    public static Client getClient(String path, int timeOut) {
        timeOut = timeOut * 1000;
        // 创建动态客户端
        int CXF_CLIENT_CONNECT_TIMEOUT = timeOut;
        int CXF_CLIENT_RECEIVE_TIMEOUT = timeOut;
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(path);
        HTTPConduit conduit = (HTTPConduit) client.getConduit();
        HTTPClientPolicy policy = new HTTPClientPolicy();
        policy.setConnectionTimeout(CXF_CLIENT_CONNECT_TIMEOUT);
        policy.setReceiveTimeout(CXF_CLIENT_RECEIVE_TIMEOUT);
        conduit.setClient(policy);
        return client;
    }
   /* public static String toCWebService(String url, String methodName, Map<String, Object> params) throws RemoteException, ServiceException {
        String result = "";
        if (!url.contains("?wsdl")) {
            url += "?wsdl";
        }
        String namespace = "http://tempuri.org/";
        String soapActionURI = "http://tempuri.org/" + methodName;
        Service service = new Service();
        Call call = (Call) service.createCall();
        call.setTargetEndpointAddress(url);
        call.setUseSOAPAction(true);
        call.setSOAPActionURI(soapActionURI);
        call.setOperationName(new QName(namespace, methodName));
        call.setTimeout(5000);
        call.setReturnType(XMLType.XSD_STRING);
        call.removeAllParameters();
        logger.info("开始写入参数---PSAM_ 1");
        Object[] str = new Object[params.size()];
        int i = 0;
        for (String key : params.keySet()) {
            call.addParameter(new QName("http://tempuri.org/", key), XMLType.XSD_STRING, ParameterMode.IN);
            str[i] = params.get(key).toString();
            i++;
        }
        //对传入的参数进行赋值操作
        //开始调用服务
        logger.info("参数写入完成,LWZXCommonServiceUrl：" + url + "开始请求---PSAM_ 1");
        Long startTime = new Date().getTime();
        Object obj = call.invoke(str);
        result = (String) obj;
        Long endTime = new Date().getTime();
        logger.info("LWZXCommonServiceUrl：" + url + "请求时间：" + (endTime - startTime) + "ms---PSAM_ 1");
        return result;
    }*/

    /*public static String getMyWebService(String url, String methodName, Map<String, Object> params) throws RemoteException, ServiceException {
        Logger myLogger = LoggerFactory.getLogger("ImgListNo");
        String result = "";
        myLogger.info("servicePsamAuthCall，开始创建接口链接" + url);
        if (!url.contains("?wsdl")) {
            url += "?wsdl";
        }
        String namespace = "http://tempuri.org/";
        String soapActionURI = "http://tempuri.org/" + methodName;
        Service service = new Service();
        Call servicePsamAuthCall = (Call) service.createCall();
        servicePsamAuthCall.setTargetEndpointAddress(url);
        servicePsamAuthCall.setUseSOAPAction(true);
        servicePsamAuthCall.setSOAPActionURI(soapActionURI);
        servicePsamAuthCall.setOperationName(new QName(namespace, methodName));
        servicePsamAuthCall.setReturnType(XMLType.XSD_STRING);
        servicePsamAuthCall.removeAllParameters();
        servicePsamAuthCall.setTimeout(30000);
        myLogger.info("开始写入参数");
        Object[] str = new Object[params.size()];
        int i = 0;
        for (String key : params.keySet()) {
            servicePsamAuthCall.addParameter(new QName("http://tempuri.org/", key), XMLType.XSD_STRING, ParameterMode.IN);
            str[i] = params.get(key).toString();
            System.out.println(key+"="+str[i]);
            i++;
        }
        //对传入的参数进行赋值操作
        //开始调用服务
        myLogger.info("参数写入完成,Url：" + url + "开始请求");
        Long startTime = new Date().getTime();
        Object obj = servicePsamAuthCall.invoke(str);
        result = (String) obj;
        Long endTime = new Date().getTime();
        myLogger.info("Url：" + url + "请求时间：" + (endTime - startTime) + "ms");
        return result;
    }*/

   /* public static String toCWebService(String url, String methodName, Map<String, Object> params, String namespace, int timeOut) throws RemoteException, ServiceException {
        String result = "";
        if (!url.contains("?wsdl")) {
            url += "?wsdl";
        }
        String soapActionURI = namespace + methodName;
        Service service = new Service();
        Call call;
        call = (Call) service.createCall();
        call.setTargetEndpointAddress(url);
        call.setUseSOAPAction(true);
        call.setSOAPActionURI(soapActionURI);
        call.setOperationName(new QName(namespace, methodName));
        call.setTimeout(timeOut * 1000);
        call.setReturnType(XMLType.XSD_STRING);
        Object[] str = new Object[params.size()];
        int i = 0;
        for (String key : params.keySet()) {
            call.addParameter(new QName(namespace, key), XMLType.XSD_STRING, ParameterMode.IN);
            str[i] = params.get(key).toString();
            i++;
        }
        Object obj = call.invoke(str);
        result = (String) obj;
        return result;
    }*/

    public static Map<String, Object> getResult(String obj) {
        if (obj == null || obj.equals("")) {
            return null;
        }
        Map<String, Object> map = com.alibaba.fastjson.JSONObject.parseObject(obj);
        return map;
    }

   /* public static String getImgStrByWebService(String imgType, String listNO, Holder<String> imgTBName, Holder<Integer> staNo, Map<String, Object> returnMap, String url) {
        Logger myLogger = LoggerFactory.getLogger("ImgListNo");
        Map<String, Object> params = new HashMap<>();
        if (imgType.equals("4")) {
            params.put("listNO", listNO);
            params.put("transferFlag", StaInfo.UserType);
            params.put("staNo", staNo.value);
            try {
                return WebServiceUtil.getMyWebService(url, "GetImgByGantry", params);
            } catch (Exception e) {
                myLogger.info("访问 " + url + " 接口错误 " + ExceptionUtil.getExceptionStr(e));
                returnMap.put("resultData", "[]");
                returnMap.put("resultCode", "0");
                returnMap.put("resultText", "访问 " + url + " 接口错误 " + e.getMessage());
                return new JSONObject(returnMap).toString();
            }
        } else {
            params.put("bucketName", "bucket" + imgTBName.value);
            params.put("listNO", listNO);
            params.put("transferFlag", StaInfo.UserType);
            params.put("staNo", staNo.value);
            params.put("imgType", imgType);
            try {
                return WebServiceUtil.getMyWebService(url, "GetImgByBucket", params);
            } catch (Exception e) {
                myLogger.info("访问 " + url + " 接口错误 " + ExceptionUtil.getExceptionStr(e));
                returnMap.put("resultData", "[]");
                returnMap.put("resultCode", "0");
                returnMap.put("resultText", "访问 " + url + " 接口错误 " + e.getMessage());
                return new JSONObject(returnMap).toString();
            }
        }
    }*/
}
