package com.seeyon.apps.jync_file.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.jync_file.kit.PropKit;

/**
 * 接口调用工具类
 * 2021-06-08
 * @author huangzhengguo
 *
 */
public class InterfaceListUtil {

	/**
	 * 获取一个token
	 *
	 * @param restUserName rest用户名
	 * @param restPassword rest密码
	 * @return
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	public String getToken(String loginName) throws FileNotFoundException, IOException {
		String address = "";
		String token = "";
		if("".equals(loginName)) {
			address = PropKit.getProp(PropKit.OATOKENURL)+"/"+PropKit.getProp(PropKit.RESTNAME)+"/"+PropKit.getProp(PropKit.RESTPASSWORD);
		}else {
			address = PropKit.getProp(PropKit.OATOKENURL)+"/"+PropKit.getProp(PropKit.RESTNAME)+"/"+PropKit.getProp(PropKit.RESTPASSWORD)+"?loginName="+loginName;
		}
		HttpURLConnection connection = (HttpURLConnection) new URL(address).openConnection();
        connection.setRequestMethod("GET");
        int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            String result = response.toString();
    		if(result.contains("{")) {
    			JSONObject jsObj = JSONObject.parseObject(result);
    			System.out.println(jsObj);
    			token = jsObj.get("id").toString();
    		}else {
    			token = result;
    		}
    		System.out.println(token);
        } else {
            System.out.println("GET request not worked");
        }
		return token;
	}

	/**
	 * 调用get接口
	 *
	 * @param par    拼接在url中的参数
	 * @param strUrl 需要调用的url对应的配置文件的key
	 * @return
	 */
	public String doGet(String par, String strUrl, String token) {
		String address = MessageFormat.format(getProperties(strUrl), par + "?token=") + token;

		DefaultHttpClient client = new DefaultHttpClient();
		String result = "";
		HttpGet get = new HttpGet(address);
		try {
			HttpResponse res = client.execute(get);
			if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(res.getEntity());
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
//			JSONObject jsObj = JSONObject.parseObject(result);
		return result;

	}

	/**
	 * 调用post接口
	 *
	 * @param str    调用接口传递的参数json
	 * @param urlStr 需要调用的url对应的参数文件中的编码
	 * @return
	 */
	public JSONObject doPost(String str, String urlStr,String token) {
		HttpURLConnection connection = null;
		InputStream is = null;
		OutputStream os = null;
		BufferedReader br = null;
		String result = null;
		try {
//			String token = getToken(getProperties("restUserName"), getProperties("restPassword"));
			URL url = new URL(getProperties(urlStr) + "?token=" + token);
			// 通过远程url连接对象打开连接
			connection = (HttpURLConnection) url.openConnection();
			// 设置连接请求方式
			connection.setRequestMethod("POST");
			// 设置连接主机服务器超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取主机服务器返回数据超时时间：60000毫秒
			connection.setReadTimeout(60000);

			// 默认值为：false，当向远程服务器传送数据/写数据时，需要设置为true
			connection.setDoOutput(true);
			// 默认值为：true，当前向远程服务读取数据时，设置为true，该参数可有可无
			connection.setDoInput(true);
			// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
			connection.setRequestProperty("Content-Type", "application/json");
			// 通过连接对象获取一个输出流
			os = connection.getOutputStream();
			// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
			if (!("".equals(str) || str == null)) {
				os.write(str.getBytes("UTF-8"));
			}
			// 连接对象获取一个输入流，向远程读取
			if (connection.getResponseCode() == 200) {

				is = connection.getInputStream();
				// 对输入流对象进行包装:charset根据工作项目组的要求来设置
				br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

				StringBuffer sbf = new StringBuffer();
				String temp = null;
				// 循环遍历一行一行读取数据
				while ((temp = br.readLine()) != null) {
					sbf.append(temp);
					sbf.append("\r\n");
				}
				result = sbf.toString();
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			// 关闭资源
			if (null != br) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != os) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != is) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			// 断开与远程地址url的连接
			connection.disconnect();
		}
		JSONObject json = JSONObject.parseObject(result);
		return json;

	}

	/**
	 * 获取指定参数文件的值（pa.properties）
	 *
	 * @param str 参数文件中的key
	 * @return
	 */
	public String getProperties(String str) {
		Properties properties = null;
		try {
			properties = PropertiesLoaderUtils.loadAllProperties("pa.properties");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (String) properties.get(str);
	}

	/**
	 * 调用Soap接口  对接平台使用
	 * @param action 平台接口中的方法参数名称
	 * @param xml	传递平台的XML数据参数
	 * @return	返回调取soap接口后接口的返回值（未处理）
	 * @throws HttpException
	 * @throws IOException
	 */
	public String doSoap(String action, String xml,String id) throws HttpException, IOException {
		String wsdl = "";
		if("createDepartment".equals(action)||"updateDepartment".equals(action)) {
			wsdl = getProperties("DeptWsdl");
		}else if("createPractitioner".equals(action)||"updatePractitioner".equals(action)) {
			wsdl = getProperties("MemberWsdl");
		}
		System.out.println("wsdl:"+wsdl);
		int timeout = 10000;

		// 构造soap请求信息
		StringBuffer sb = new StringBuffer("");
		sb.append(
			"<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:urn=\"urn:hl7-org:v3\">");
		sb.append("<soap:Header/>");
		sb.append("<soap:Body>");
		sb.append(" <urn:HIPMessageServer>");
		sb.append("<urn:action>" + action + "</urn:action><urn:message>" + xml + "</urn:message>");
		sb.append("</urn:HIPMessageServer>");
		sb.append("</soap:Body>");
		sb.append("</soap:Envelope>");

		// HttpClient发送SOAP请求
//		System.out.println("HttpClient 发送SOAP请求");
		HttpClient client = new HttpClient();
		PostMethod postMethod = new PostMethod(wsdl);
		Header header = new Header();
		// 设置连接超时
		client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
		// 设置读取时间超时
		client.getHttpConnectionManager().getParams().setSoTimeout(timeout);
		// 然后把Soap请求数据添加到PostMethod中
		RequestEntity requestEntity = null;
		try {
			requestEntity = new StringRequestEntity(sb.toString(), "text/xml", "UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 设置请求头部，否则可能会报 “no SOAPAction header” 的错误
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date businessTime = new Date();
		Date operationTime = new Date();
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMddHHmmss");
		Date root = new Date();
		String rootId = sdf1.format(root);
		postMethod.setRequestHeader("SOAPAction", "");
		postMethod.setRequestHeader("Content-Type", "application/fhir+json");
		postMethod.setRequestHeader("rootId", rootId);
		postMethod.setRequestHeader("token", id);
		postMethod.setRequestHeader("domain", "OA");
		postMethod.setRequestHeader("businessTime", sdf.format(businessTime));
		postMethod.setRequestHeader("key", "806c1571-35de-41a2-b3c9-06ae5474d43a");
		postMethod.setRequestHeader("operationTime", sdf.format(operationTime));
		// 设置请求体
		postMethod.setRequestEntity(requestEntity);
		int status = client.executeMethod(postMethod);
		// 打印请求状态码
//		System.out.println("status:" + status);
		// 获取响应体输入流
		InputStream is = postMethod.getResponseBodyAsStream();
		// 获取请求结果字符串
		byte[] bytes = new byte[is.available()];
		is.read(bytes);
		String result = new String(bytes);

		return result;
	}

	/**
	 * 下载文件到指定目录
	 * @param dowUrl:http地址
	 * @param  dowPath:指定目录
	 * */
    public String download(String dowUrl, String dowPath){
        try {
//		log.info("下载地址是："+dowUrl+",存储地址是："+dowPath);
            URL url = new URL(dowUrl);

            URLConnection urlConnection = url.openConnection();

            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;// http的连接类

            //String contentType = httpURLConnection.getContentType();//请求类型,可用来过滤请求，

            httpURLConnection.setConnectTimeout(1000*5);//设置超时

            httpURLConnection.setRequestMethod("GET");//设置请求方式，默认是GET

            httpURLConnection.setRequestProperty("Charset", "UTF-8");// 设置字符编码

            httpURLConnection.connect();// 打开连接

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

            String path = dowPath;// 指定存放位置
            File filed = new File(path);

            OutputStream out = new FileOutputStream(filed);
            int size = 0;

            byte[] b = new byte[2048];
            //把输入流的文件读取到字节数据b中，然后输出到指定目录的文件
            while ((size = bin.read(b)) != -1) {
                out.write(b, 0, size);
            }
            // 关闭资源
            bin.close();
            out.close();
			return "200";
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "500";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
			return "400";
        }
    }
}
