using Nest;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsvCount_ES
{
    /// <summary>
    /// 直接获取ESData的特殊类
    /// </summary>
    public class ESItemAccess : ESAccess
    {
        public const string NullValue = "空空";


        /// <summary>
        /// 根据itemID搜索Item
        /// </summary>
        /// <param name="id">itemID</param>
        /// <returns>返回实体</returns>
        public static Item SearchByItemID(string id)
        {
            SearchDescriptor<Item> builder = new SearchDescriptor<Item>()
                        .Size(1)
                        .Query(q => q
                            .Bool(b => b
                                .Must(m => m
                                    .QueryString(qs => qs.DefaultField(f => f.ItemID).Query(id))
                                )
                            )
                        );

            try
            {
                return SearchTop(builder);
            }
            catch (Exception e)
            {
                
                LogService.WriteError(string.Format("ES SearchByItemID Fail:{0} ItemID:{1}", e.ToString(), id));
                return null;
            }
        }

        /// <summary>
        /// 根据itemID搜索Item
        /// </summary>
        /// <param name="id">itemID</param>
        /// <returns>返回实体</returns>
        public static Item[] SearchByItemIDs(List<string> itemIds)
        { 
           

            try
            {
                SearchDescriptor<Item> builder = new SearchDescriptor<Item>()
                       .Size(1000)
                       .Query(q => q
                           .Bool(b => b
                               .Must(m => m
                                   .QueryString(qs => qs.DefaultField(f => f.ItemID).Query("\"" + string.Join("\" \"", itemIds) + "\""))
                               )
                           )
                       );

                return Search(builder);
            }
            catch (Exception e)
            {
                LogService.WriteError(string.Format("ES SearchByItemIDs Fail:{0}", e.ToString()+ string.Join("\" \"", itemIds)));
                return null;
            }
        }

     
    }


    public class ESAccess
    {
        /// <summary>
        ///     从ES中搜索数据,仅返回需要的数据本体
        /// </summary>
        /// <param name="searchQuery">查询条件</param>
        /// <typeparam name="T">需要查询的类</typeparam>
        /// <returns>数据结果</returns>
        public static T[] Search<T>(SearchDescriptor<T> searchQuery) where T : class
        {
            ISearchResponse<T> result = SearchDetail(searchQuery);
            if (result == null )
                return null;
            if (result.Documents == null)
            {
            
                List <Item> alist = new List<Item>();
                return (T[])(Object)alist;

            }
               
            else
                return result.Documents.ToArray();
        }
        /// <summary>
        /// 从ES中搜索数据,仅返回第一条数据本体
        /// </summary>
        /// <typeparam name="T">查询条件</typeparam>
        /// <param name="searchQuery">需要查询的类</param>
        /// <returns>数据结果</returns>
        public static T SearchTop<T>(SearchDescriptor<T> searchQuery) where T : class
        {
            var response = Search(searchQuery);
            if (response == null)
                return null;
            else
                return response.FirstOrDefault();
        }
        /// <summary>
        /// 从ES中搜索数据,返回详细信息,包括数据本体,查询时间,命中总数等
        /// </summary>
        /// <param name="searchQuery">查询条件</param>
        /// <typeparam name="T">需要查询的类</typeparam>
        /// <returns>统计数据结果集</returns>
        public static ISearchResponse<T> SearchDetail<T>(SearchDescriptor<T> searchQuery) where T : class
        { 
            ElasticClient client = new ElasticClient(ESClientConfigureManager.ConnectSetting);
            ISearchResponse<T> response = null;
            try
            {
                response = PerformanceUtility.OperationTimedMonitor<ISearchResponse<T>>(
                    PerformanceUtility.DefaultTriggerTimeSpan,
                    PerformanceUtility.DefaultIntervalTimeSpan,
                    Serialize(searchQuery),
                    //searchQuery.ExplainJson(),
                    () => { return client.Search<T>(searchQuery); });
                var isItem = typeof(T) == typeof(Item);
                if (isItem)
                {
                    foreach (var document in response.Documents)
                    {
                        var item = document as Item;
                        ReverseNullValueForQuery(item);
                    }
                }
            }
            catch (Exception e)
            {
                LogService.WriteError("ESAccess SearchDetail Fail", e);
            }
            return response;
        }

        public static void ReverseNullValueForQuery(Item item)
        {
           
            if (item.DuplicationID == ESItemAccess.NullValue)
            {
                item.DuplicationID = null;
            }
           
        }


        public static string Serialize<T>(T obj) where T : class
        {
            try
            {
                ElasticClient client = new ElasticClient(ESClientConfigureManager.ConnectSetting);
                using (MemoryStream stream = new MemoryStream())
                {
                    client.Serializer.Serialize(obj, stream);
                    byte[] b = stream.ToArray();
                    return Encoding.UTF8.GetString(b, 0, b.Length);
                }
            }
            catch
            {
                return "";
            }
        }

        public static T Deserialize<T>(string json) where T : class
        {
            ElasticClient client = new ElasticClient(ESClientConfigureManager.ConnectSetting);
            return client.Serializer.Deserialize<T>(new MemoryStream(Encoding.UTF8.GetBytes(json)));
        }

    }
}
