package com.steering.mes.mcp.CollarLibrary;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;

import org.apache.axis.Constants;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;

public class ServiceToCx {
	
     public static Boolean HttpPostExample(String strUrl,String json) {
    	 try {
    	 URL url = new URL(strUrl); // 替换为你的URL
         HttpURLConnection conn = (HttpURLConnection) url.openConnection();
         conn.setRequestMethod("POST");
         conn.setDoOutput(true);
         // 设置请求头，如Content-Type
         conn.setRequestProperty("Content-Type", "application/json");
         // 写入请求体
         try (OutputStream os = conn.getOutputStream()) {
             byte[] inputBytes = json.getBytes("utf-8");
             os.write(inputBytes);
         }
	         conn.disconnect();
	         return true;
    	 }catch (Exception e) {
    		 return false;
         }
     }
     
     /**调用webservice接口
      * url:调用路径
      * TargetSpaceName:命名空间名，可在浏览器输入接口地址查看
      * serviceName:调用方法名
      * keys Object[] 对象数组类型:方法参数名
      * values Object[] 对象数组类型:参数值
      * */
     public static String webServiceAxisCase(String url,String TargetSpaceName,String serviceName,
     		 	Object[] values) throws Exception{
     	String result = "";
     	try {
             String endpoint = url;  
             //直接引用远程的wsdl文件
             Service service = new Service();  
             Call call = (Call) service.createCall();
             call.setTargetEndpointAddress(new URL(endpoint));  
             //call.setOperationName(serviceName);//调用的方法名 当这种调用不到的时候,可以使用下面的,加入命名空间名
             call.setOperationName(new QName(TargetSpaceName, serviceName));// 调用的方法名 加入命名空间名
             //java的webservice可以不传参数名，但是asmx的接口调用必须指定确定的参数名称与下列方法
             //call.setUseSOAPAction(true);
             //call.setSOAPActionURI(TargetSpaceName + serviceName);
             
             for(int i = 0; i < values.length; i++){
     			//String key = (String) keys[i]; //方法参数
     			Object value = values[i]; //参数值
     			if(value == null){
     				call.addParameter("arg"+i, Constants.XSD_STRING, ParameterMode.IN);
     			} else if(value instanceof String){
     				call.addParameter("arg"+i, Constants.XSD_STRING, ParameterMode.IN);
     			} else if(value instanceof Integer){
     				call.addParameter("arg"+i, Constants.XSD_INTEGER, ParameterMode.IN);
     			} else if(value instanceof Boolean){
     				call.addParameter("arg"+i, Constants.XSD_BOOLEAN, ParameterMode.IN);
     			}
     		}
             call.setReturnType(Constants.XSD_STRING);// 设置返回类型  
             if(values.length == 0)
             	result = (String) call.invoke(new Object[]{});  
             else
             	result = (String) call.invoke(values);
             // 给方法传递参数，并且调用方法  
         } catch (Exception e) {  
             System.err.println("Error:"+e.toString());
         }  
     	return result;
     }
       
     public static String callWebserviceASMX(String urls,DefaultWebServiceRequest request ,String method, String json) throws Exception {
         try {
        	 String soapRequest = requestString(request);
        	 URL url = new URL(urls);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod("POST");
             connection.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
             connection.setRequestProperty("SOAPAction", "http://webservice.transport.ixbuscore.baosight.com/"+method+"");
             connection.setDoOutput(true);
             try(OutputStream os = connection.getOutputStream()) {
                 byte[] bytes = soapRequest.getBytes(StandardCharsets.UTF_8);
                 os.write(bytes);
             }
             catch (Exception e)
             {

             }

             int responseCode = connection.getResponseCode();
             // 处理响应
             if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
                 BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                 String inputLine;
                 StringBuilder response = new StringBuilder();

                 while ((inputLine = in.readLine()) != null) {
                     response.append(inputLine);
                 }
                 in.close();
             } else {
                 System.err.println("失败代码 : " + responseCode);
                 BufferedReader errorReader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
                 System.err.println("错误信息:\n" + errorReader);
                 errorReader.close();
                 return errorReader.readLine();
             }
             return String.valueOf(responseCode);
         } catch (Exception e) {
             throw new Exception(e.getMessage());
         }
     }
     
     public static String callWebserviceASMX(String method,String json){
 		System.out.println("Start invoking....");
 		String str = "";
 		try{
 			String endPoint = "http://172.16.4.68/PlanBrief/PlanService.asmx";
 			String soapaction = "http://tempuri.org/"; 
 			Service service = new Service();
 			Call call = (Call) service.createCall();
 			call.setTargetEndpointAddress(new java.net.URL(endPoint));
 			call.setOperation(method);
 			call.setUseSOAPAction(true);
 			call.setSOAPActionURI(soapaction+method);
 			call.setOperationName(new QName(soapaction,method));
 			call.addParameter(new QName(soapaction, "strDate"), Constants.XSD_STRING, ParameterMode.IN); 
 			call.setReturnType(Constants.XSD_STRING);
 			str = (String) call.invoke(new  Object[]{json});
 			System.out.println(str);
 		}catch(Exception e){
 			e.printStackTrace();}
 		/*//获取webservice接口地址
 		String result = "";
 		String url = "http://172.16.4.68/PlanBrief/PlanService.asmx";         //获取域名地址，server定义的
 		String soapaction = "http://tempuri.org/";        
 		Service service = new Service();         
 		try {
 			Call call = (Call) service.createCall();
 			call.setTargetEndpointAddress(url);              //设置要调用的方法
 		    call.setOperationName(new QName(soapaction,method));              //设置要返回的数据类型
 		    call.setReturnType(new QName(soapaction,method), String.class);            
 		    call.setUseSOAPAction(true);            
 		    call.setSOAPActionURI(soapaction+method);             //调用方法并传递参数
 		    call.setReturnType(org.apache.axis.encoding.XMLType.XSD_STRING);
 		    result = (String) call.invoke(new Object[]{json});            
 		    System.out.println("result is:::"+result);  
 		    } catch (Exception e) {
 		    	e.printStackTrace();        
 		    } 
 		return result;*/
 	   return str;
 }
     public static String requestString (DefaultWebServiceRequest request) {
    	 String soapRequest = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                 "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" +
                 "  <soap:Body>\n" +
                 "    <receiveMessage xmlns=\"http://webservice.transport.ixbuscore.baosight.com\">\n" +
                 "      <request>\n" +
                 "        <msgBody>"+request.getMsgBody()+"</msgBody>\n" +
                 "        <msgSendTime>"+request.getMsgSendTime()+"</msgSendTime>\n" +
                 "        <msgToken>"+request.getMsgToken()+"</msgToken>\n" +
                 "        <Password>"+request.getPassword()+"</Password>\n" +
                 "        <serviceId>"+request.getServiceId()+"</serviceId>\n" +
                 "        <sourceAppCode>"+request.getSourceAppCode()+"</sourceAppCode>\n" +
                 "        <tempField>"+request.getTempField()+"</tempField>\n" +
                 "        <Version>"+request.getVersion()+"</Version>\n" +
                 "      </request>\n" +
                 "    </receiveMessage>\n" +
                 "  </soap:Body>\n" +
                 "</soap:Envelope>";
    	 return soapRequest;
     }
}
