package com.liangjian.dataplatform.member.jobUtil;


import com.liangjian.dataplatform.member.entity.po.secondary.FiltersUtils;
import com.liangjian.dataplatform.member.util.StringUtil;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.UnknownHostException;
import java.sql.*;
import java.util.*;

public class EsUtils {

	public static final String INDEX_NAME = "java_demo_index";
	public static final String TYPE_NAME = "java_demo_type";
	//sql查询es _xpack/sql?format=json
	public static String Host="http://192.168.50.34:9200/";

	private static RestHighLevelClient client;

	/**
	 * 创建es链接
	 * @return
	 * @throws UnknownHostException
	 */
	public static RestHighLevelClient  getEsClient() throws UnknownHostException {
		client =
				new RestHighLevelClient(
						RestClient.builder(
								new HttpHost[]{new HttpHost("192.168.50.39", 9200, "http")}));
		return client;

	}

	public static void closeClient() throws IOException {
		if(client!=null)
			client.close();
	}

	public static String getIndexName() {
		return INDEX_NAME;
	}
	public static String getTypeName() {
		return TYPE_NAME;
	}

	/***
	 * react查询条件转sql字符
	 * @param filters
	 * @return
	 */
	public static String getFilterString(List<FiltersUtils> filters,String alias){
		String queryCondition = "";
		if (filters != null)
		{
			for (FiltersUtils item : filters)
			{
				if (item != null && !item.getValue().equals("") && item.getField() != null )
				{
					switch (item.getOperate())
					{
						case "equal":
							queryCondition += " and "+alias+item.getField()+"=  '"+ item.getValue()+ "'";
							break;
						case "notequal":
							queryCondition += " and "+alias+item.getField()+"!=  '" + item.getValue()+"'";

							break;
						case "less":
							queryCondition += " and "+alias+item.getField()+"< " + item.getValue();

							break;
						case "lessorequal":
							queryCondition += " and "+alias+item.getField()+"<= " + item.getValue();

							break;
						case "greater":
							queryCondition += " and "+alias+item.getField()+"> " + item.getValue();

							break;
						case "greateroreeuqal":
							queryCondition += " and "+alias+item.getField()+">= " + item.getValue();

							break;
						case "contains":
							queryCondition += " and "+alias+item.getField()+" like '%" + item.getValue() +"%'";

							break;
						case "startswith":
							queryCondition += " and "+alias+item.getField()+" like '" + item.getValue() + "%'";

							break;
						case "endswith":
							queryCondition += " and "+alias+item.getField()+" like '%" + item.getValue() + "'";
							break;
					}
				}
			}
		}
		return queryCondition;
	}

	/**
	 * jdbc执行clickhousesql
	 * @param sql
	 * @return
	 */
	public static List<Map> exeSql(String sql){
		String address = "jdbc:clickhouse://139.159.192.185:8123?user=default&password=79B084A8D7363488DEBFA5D151CCC9B1";
		Connection connection = null;
		Statement statement = null;
		ResultSet results = null;
		List<Map> list = new ArrayList();
		try {
			Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
			connection = DriverManager.getConnection(address);
			statement = connection.createStatement();
			results = statement.executeQuery(sql);
			ResultSetMetaData rsmd = results.getMetaData();
			int b=rsmd.getColumnCount();
			while(results.next()){
				Map map = new HashMap();
				for(int i = 1;i<=rsmd.getColumnCount();i++){
					map.put(rsmd.getColumnName(i),results.getString(rsmd.getColumnName(i)));
				}
				list.add(map);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {//关闭连接
			try {
				if(results!=null){
					results.close();
				}
				if(statement!=null){
					statement.close();
				}
				if(connection!=null){
					connection.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return list;
	}


	public static String  httpGetClickHouse(String url) throws IOException {
		System.out.println("get=="+url);
		RequestConfig requestConfig = RequestConfig.custom()
				.setConnectTimeout(5000)
				.setSocketTimeout(55000)
				.setConnectionRequestTimeout(5000)
				.build();

		HttpClient clients = new DefaultHttpClient();
		HttpGet get=new HttpGet(url);
		//HttpPost post = new HttpPost(url);
		get.setConfig(requestConfig);
		HttpResponse response = clients.execute(get);
		String message="";
		if (response.getStatusLine().getStatusCode() == 200) {
			HttpEntity resEntity = response.getEntity();
			message = EntityUtils.toString(resEntity, "utf-8");
		} else {
			System.out.println("查询请求失败");
		}
		return message;
	}

	public static String  httpPostClickHouse(String url,String param) throws IOException {
		System.out.println("post=="+url+param);
		String message="";
		org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
		PostMethod post = null;
		try {
			PostMethod httpPost =new UTF8PostMethod(url);
			httpPost.setRequestBody(param);
			client.executeMethod(httpPost);
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (post != null) {
				try {
					post.releaseConnection();
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		return message;
	}

	public static String post(JSONObject json, String url){
		String result = "";
		String strjson=json.toString();
		HttpPost post = new HttpPost(url);
		try{
			CloseableHttpClient httpClient = HttpClients.createDefault();

			post.setHeader("Content-Type","application/json;charset=utf-8");
			post.addHeader("Authorization", "Basic YWRtaW46");
			StringEntity postingString = new StringEntity(json.toString(),"utf-8");
			post.setEntity(postingString);
			HttpResponse response = httpClient.execute(post);

			InputStream in = response.getEntity().getContent();
			BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
			StringBuilder strber= new StringBuilder();
			String line = null;
			while((line = br.readLine())!=null){
				strber.append(line+'\n');
			}
			br.close();
			in.close();
			result = strber.toString();
			if(response.getStatusLine().getStatusCode()!= HttpStatus.SC_OK){
				result = "服务器异常";
			}
		} catch (Exception e){
			System.out.println("请求异常");
			throw new RuntimeException(e);
		} finally{
			post.abort();
		}
		return result;
	}

	//sql链接es
	public static String query(String sqlStr, String url, boolean sign){
		String esStr = sqlStr;
		if(sign){
			esStr="{\"query\":\""+sqlStr+"\"}";
		}
		net.sf.json.JSONObject jsonObject= JSONObject.fromObject(esStr);
		return post(jsonObject,Host + url);
	}


	public static String getFilterString(List<FiltersUtils> filterList) {
		String queryCondition = "";
		if (filterList != null) {
			for (FiltersUtils item : filterList) {
				if (item != null && (!StringUtil.isEmpty(item.getValue()) || (item.getRules() != null && item.getRules().size() > 0))) {
					String val = item.getValue();
					String field = item.getField();
					String operate = item.getOperate();
					switch (operate) {
						case "equal":
							queryCondition += " and " + field + "=  '" + val + "'";
							break;
						case "notequal":
							queryCondition += " and " + field + "!=  '" + val+"'";

							break;
						case "less":
							queryCondition += " and " + field + "< '" + val+"'";

							break;
						case "lessorequal":
							queryCondition += " and " + field + "<= '" + val+"'";

							break;
						case "greater":
							queryCondition += " and " + field + "> '" + val+"'";

							break;
						case "greaterorequal":
							queryCondition += " and " + field + ">= '" + val+"'";

							break;
						case "contains":
							queryCondition += " and " + field + " like '%" + val + "%'";

							break;
						case "startswith":
							queryCondition += " and " + field + " >='" + val + "'";

							break;
						case "endswith":
							queryCondition += " and " + field + " <= '" + val + "'";

							break;
						case "or":
							var innerCondition = "1 = 1";
							List<Map<String, Object>> rulesMap = item.getRules();
							for (Map<String, Object> stringObjectMap : rulesMap) {
								String rulesField = (String) stringObjectMap.get("field");
								String rulesValue = (String) stringObjectMap.get("value");
								innerCondition += " or "+rulesField+" = '"+rulesValue+"'";
							}

							innerCondition = innerCondition.replace("1 = 1 or", "");
							queryCondition += " and (" + innerCondition + ")";

							break;
						case "nestand":
							var innerConditionNest = "1 = 1";
							List<Map<String, Object>> rules = item.getRules();
							for (Map<String, Object> stringObjectMap : rules) {
								String rulesField = (String) stringObjectMap.get("field");
								String rulesvalue = (String) stringObjectMap.get("value");
								innerConditionNest += " and "+rulesField+" = '"+rulesvalue+"'";
							}
							innerConditionNest = innerConditionNest.replace("1 = 1 and", "");
							queryCondition += " and (" + innerConditionNest + ")";

							break;
					}
				}
			}
//            Console.WriteLine(queryCondition);
		}
		return queryCondition;
	}




}
class UTF8PostMethod extends PostMethod{
	public UTF8PostMethod(String url){
		super(url);
	}
	@Override
	public String getRequestCharSet() {
		//return super.getRequestCharSet();
		return "UTF-8";
	}
}