package com.cirle.scientific.utils;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.opensearch.DocumentClient;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SearcherClient;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;
import com.aliyun.opensearch.sdk.generated.search.Config;
import com.aliyun.opensearch.sdk.generated.search.Rank;
import com.aliyun.opensearch.sdk.generated.search.SearchFormat;
import com.aliyun.opensearch.sdk.generated.search.SearchParams;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.util.Map;

@Slf4j
public class SolrUtils {

	private static final String accesskey = "LTAI5tHTG5eNAC7pmoqUDghi";

	private static final String secret = "K8aZK7RWhqw4LdkP9MtwiC7Rq0avwt";

	private static final String host = "http://opensearch-cn-beijing.aliyuncs.com";
	
	//app
	private static final String appName = "qkj_search";
	private static final String table_name = "qkj_searchdata";

	private static OpenSearchClient serviceClient;

	static {
		//创建并构造OpenSearch对象
		OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
		//创建OpenSearchClient对象，并以OpenSearch对象作为构造参数
		serviceClient = new OpenSearchClient(openSearch);
	}

	/**
	 * 企业名称搜索文档
	 * 
	 * @param query
	 *            查询子句，格式举例：title:'栓塞'
	 * @param sortMap
	 *            排序子句
	 * @param start
	 *            起始偏移量
	 * @param hits
	 *            命中数量
	 * @return
	 * @throws Exception
	 * @throws IOException
	 */
	public static String searchDoc(String query, Map<String, String> sortMap, int start, int hits){
		String searchRs = "";
		try {
			SearcherClient searcherClient = new SearcherClient(serviceClient);
			
			Config config = new Config(Lists.newArrayList(appName));
			config.setStart(start);
			config.setHits(hits);
			//设置返回格式为fulljson格式
			config.setSearchFormat(SearchFormat.JSON);
			
			Rank rand = new Rank();
			rand.setSecondRankName("obj_title");
			
			// 创建参数对象
			SearchParams searchParams = new SearchParams(config);
			// 指定搜索的关键词，这里要指定在哪个索引上搜索，如果不指定的话默认在使用“default”索引（索引字段名称是您在您的数据结构中的“索引字段列表”中对应字段。），若需多个索引组合查询，需要在setQuery处合并，否则若设置多个setQuery子句，则后面的子句会替换前面子句
			searchParams.setQuery(query);
			searchParams.setRank(rand);
			//searchParams.setFilter("obj_type=1");
			
			//执行查询语句返回数据对象
			SearchResult searchResult = searcherClient.execute(searchParams);
			//以字符串返回查询数据
			String result = searchResult.getResult();
			System.out.println(result);
			JSONObject resultJson = JSONObject.parseObject(result);
			if (resultJson.getString("status").equals("OK")) {
				return resultJson.getJSONObject("result").toString();
			} else {
				return resultJson.getJSONArray("errors").get(0).toString();
			}
		} catch (Exception e) {
			log.error("检索异常：" + e);
			searchRs = "";
		}

		return searchRs;
	}

	public static String updateDoc(String data){
		//定义DocumentClient对象添加json格式doc数据批量提交
		DocumentClient documentClient = new DocumentClient(serviceClient);
		//执行推送操作
		try {
			OpenSearchResult osr = documentClient.push(data, appName, table_name);
			log.info(osr.getResult());
			return osr.getResult();
		} catch (OpenSearchException e) {
			e.printStackTrace();
		} catch (OpenSearchClientException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) throws Exception, Exception {

		System.out.println(SolrUtils.searchDoc("default:'全科'", null, 0, 10));

		//String data = "[{\"cmd\":\"add\", \"fields\":{\"id\":\"1\",\"obj_title\":\"全科届123\"}}]";
		//System.out.println(SolrUtils.updateDoc(data));
	}

}