package com.liangjian.dataplatform.member.service.impl;

import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersData;
import com.liangjian.dataplatform.member.entity.po.secondary.FiltersUtils;
import com.liangjian.dataplatform.member.entity.tag.EsTagInfo;
import com.liangjian.dataplatform.member.jobUtil.EsUtils;
import com.liangjian.dataplatform.member.service.IMemEsCountService;
import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.time.DateUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.cardinality.CardinalityAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.sum.SumAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.Transient;
import javax.transaction.Transactional;
import java.io.IOException;
import java.lang.annotation.RetentionPolicy;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class MemEsCountService implements IMemEsCountService {

    //链接查询es
    public static EsUtils esUtils=new EsUtils();

    @PersistenceContext(unitName = "entityManagerFactoryFourthly")
    private EntityManager em;

    //sql查询es
    public static String Host="http://192.168.50.34:9200/";

    /***
     * 复购率统计
     * @return
     */
    @Override
    public Map<String, Object> getOrderCount() {
        String tabIndex="mem_repurchaseinfo";

        Map<String,Object> map=new HashMap<String,Object>();
        try {
            //创建查询链接
            RestHighLevelClient client = esUtils.getEsClient();
            SearchRequest request = new SearchRequest(tabIndex);
            //request.types(tabIndex);

            //查找统计
            SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);

            SumAggregationBuilder builder = AggregationBuilders.sum("F_SUM").field("F1");

            SumAggregationBuilder mbuilder = AggregationBuilders.sum("M_SUM").field("M1");

            CardinalityAggregationBuilder cardinalityAggregationBuilder = AggregationBuilders.cardinality("M_COUNT").field("_id");

            //重购单数大于2
            RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("F1");
            rangeQueryBuilder.gte(2);

            //聚合统计
            FilterAggregationBuilder filterAggregationBuilder = AggregationBuilders.filter("F_SUMS",rangeQueryBuilder);
            SumAggregationBuilder sumAggregationBuilder =  AggregationBuilders.sum("F_SUM").field("F1");
            filterAggregationBuilder.subAggregation(sumAggregationBuilder);

            FilterAggregationBuilder filterAggregationBuilder1 = AggregationBuilders.filter("M_SUMS",rangeQueryBuilder);
            SumAggregationBuilder sumAggregationBuilder1 = AggregationBuilders.sum("M_SUMS").field("M1");
            filterAggregationBuilder1.subAggregation(sumAggregationBuilder1);

            FilterAggregationBuilder filterAggregationBuilder2 = AggregationBuilders.filter("M_COUNTS",rangeQueryBuilder);
            CardinalityAggregationBuilder sumAggregationBuilder2 = AggregationBuilders.cardinality("M_COUNTS").field("_id");
            filterAggregationBuilder2.subAggregation(sumAggregationBuilder2);

            searchSourceBuilder.aggregation(filterAggregationBuilder);
            searchSourceBuilder.aggregation(builder);
            searchSourceBuilder.aggregation(mbuilder);
            searchSourceBuilder.aggregation(cardinalityAggregationBuilder);
            searchSourceBuilder.aggregation(filterAggregationBuilder1);
            searchSourceBuilder.aggregation(filterAggregationBuilder2);

            request.source(searchSourceBuilder);

            SearchResponse response = client.search(request,RequestOptions.DEFAULT);
            Aggregations aggregations = response.getAggregations();
            Map<String, Aggregation>  aggregationMap = aggregations.getAsMap();


            //SearchHits searchHits=response.getHits();

            //关闭链接
            esUtils.closeClient();
            map.put("jsonSum",aggregationMap);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return map;
    }

    /***
     * 复购用户列表
     * @param client
     * @param request
     * @return
     */
    public Map<String,Object> getOrderCountList(RestHighLevelClient client,SearchRequest request) throws IOException {
        //request.source(searchSourceBuilder);

        SearchResponse response = client.search(request,RequestOptions.DEFAULT);
        return null;
    }

    /***
     * ES会员统计
     * @return
     */
    @Override
    public Map<String,Object> getMemeberCount(String tagKey,String zkey,String sexkey){
        String sqlStr ="";
        String url="_xpack/sql?format=json";
        Map<String,Object> retMap=new HashMap<String,Object>();
        try {
            //es用户标签筛选
            if(tagKey!=null && tagKey!=""){
                String [] tagStr=tagKey.split(",");
                for (String str:tagStr) {

                }
            }
            //平台筛选
            if(zkey!=null && zkey!="" && !zkey.equals("0")){
                sqlStr+=" and OriginType in("+zkey+") ";
            }
            //性别筛选
            if(sexkey!=null && sexkey!=""){
                sqlStr+=" and MemberGender in("+sexkey+") ";
            }
            //性别统计
            String jsonStr = ESQuery("select MemberGender,count(MemUsualPhone) as cn from mem_memberbase_p where 1=1 and MemberGender>=0 " + sqlStr + " group by MemberGender",url);
            JSONObject sexJson = JSONObject.fromObject(jsonStr);
            List<JsonArray> sexMap = (List<JsonArray>) sexJson.get("rows");

            //地区统计
            jsonStr = ESQuery("select MemUsualProvinceCode,count(MemUsualPhone) as cn from mem_memberbase_p where 1=1 " + sqlStr + " group by MemUsualProvinceCode ORDER BY cn desc",url);
            JSONObject prJson=JSONObject.fromObject(jsonStr);
            List<JSONArray> prMap = (List<JSONArray>) prJson.get("rows");

            //省级列表
            jsonStr=ESQuery("select* from areamap where Level = 1",url);
            JSONObject areJson=JSONObject.fromObject(jsonStr);
            List<JSONArray> areMap = (List<JSONArray>) areJson.get("rows");
            List<String[]> arList=new ArrayList<String[]>();
            //地区赋值省级、值
            for(JSONArray array: areMap){
                for(JSONArray array1 :prMap){
                    String [] ar=new String[3];
                   if(array.get(2).equals(array1.get(0))){
                       ar[0]=String.valueOf(array.get(0));
                       ar[1]=String.valueOf(array1.get(1));
                       ar[2]=String.valueOf(array1.get(0));
                       arList.add(ar);
                   }
                }
            }
            retMap.put("itmes",arList);
            retMap.put("sexjson",sexMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }

    /**
     * 指定天数新增会员数量
     * @param mDay
     * @return
     */
    @Override
    public Map<String,Object> getMemeberDayCount(Integer mDay){
        Map<String,Object> map=new HashMap<String,Object>();
        //默认15天
        Date d=DateUtils.addDays(new Date(), -15);
        if(mDay!=null&&!mDay.equals("")){
            d= DateUtils.addDays(new Date(), -mDay);
        }
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        String jsonStr=ESQuery("select HISTOGRAM(RegisterTime, INTERVAL 1 DAYS) AS h,count(*) as cn from mem_memberbase_p where 1=1  and RegisterTime <='"+fmt.format(new Date())+"' and RegisterTime >='"+fmt.format(d)+"' group by h ORDER BY h desc","_xpack/sql?format=json");
        JSONObject sexJson = JSONObject.fromObject(jsonStr);
        List<JSONArray> meList = (List<JSONArray>) sexJson.get("rows");
        map.put("dayJson",meList);
        return map;
    }


    /***
     * 标签列表
     * @param data
     * @return
     */
    @Override
    public Map<String,Object> getAllTagList(FiltersData data){
        int start = 0;
        String filter="";
        if (data.getPageIndex() == 1)
        {
            start = 0;
        }
        else
        {
            start = ((data.getPageIndex() - 1) * data.getPageSize());
        }
        filter = esUtils.getFilterString(data.getFilters(),"");
        Map<String,Object> map=new HashMap<String,Object>();
        //sql转dsl
        String sql = ESQuery("select * from mem_tag where 1 = 1 "+filter+"  order by TagTypeId,TagId limit "+data.getPageSize()+"","_sql/translate?format=json");

        String from = "\"from\":" + start + ",";

        StringBuilder sb = new StringBuilder(sql);
        sql=sb.insert(1,from).toString();
        JSONObject json= JSONObject.fromObject(sql);
        String jsonStr=esUtils.post(json,Host+"mem_tag/_search?format=json");
        JSONObject tagJson = (JSONObject) JSONObject.fromObject(jsonStr).get("hits");
        List<JSONObject> tagList = (List<JSONObject>) tagJson.get("hits");
        List<JSONObject> tag=new ArrayList<JSONObject>();
        for(JSONObject obj:tagList){
            JSONObject js=new JSONObject();
            js.put("TagId",obj.getString("_id"));
            js.put("_id",obj.getString("_id"));
            js.put("TagTypeName",obj.getJSONObject("_source").getString("TagTypeName"));
            js.put("TagName",obj.getJSONObject("_source").getString("TagName"));
            js.put("TagKey",obj.getJSONObject("fields").getJSONArray("TagKey").getString(0));
            js.put("TagCrtTime",obj.getJSONObject("fields").getJSONArray("TagCrtTime").getString(0));
            js.put("TagTypeId",obj.getJSONObject("fields").getJSONArray("TagTypeId").getString(0));
            tag.add(js);
        }
        jsonStr=ESQuery("select count(1) cn from mem_tag where 1 = 1 "+filter,"_xpack/sql?format=json");
        JSONArray countArr= (JSONArray) JSONObject.fromObject(jsonStr).get("rows");
        map.put("items",tag);
        map.put("totalCount",countArr.get(0));
        return map;
    }

    /***
     * 添加修改分类
     * @param esTagInfo
     * @return
     */

    @Override
    public String editType(EsTagInfo esTagInfo){

        String sqlStr="";
        if(esTagInfo.getText()!=null){
            if(esTagInfo.getId()!=null&&!esTagInfo.getId().equals("")){
                sqlStr=" UPDATE  Mem_DataDictory SET [Text]='"+esTagInfo.getText()+"' WHERE Id='"+esTagInfo.getId()+"'";
            }else{
                List list = em.createNativeQuery("select max(cast(Value as int)) from mem_DataDictory where ParentId = '5552'").getResultList();
                Integer index=Integer.parseInt(list.get(0).toString())+1;
                sqlStr="INSERT INTO Mem_DataDictory ([Key],Text,[Value],Remark,ParentId,SortKey,IsHide,SyncStatus)" +
                        " VALUES ('TagType_"+index+"','"+esTagInfo.getText()+"','"+index+"','',5552,0,0,'N' )";
            }
            em.getTransaction().begin();
            Query query= em.createNativeQuery(sqlStr);
            query.executeUpdate();
            em.getTransaction().commit();
        }
        return null;
    }

    /***
     * 添加修改标签
     * @param esTagInfo
     * @return
     */
    @Override
    public String editTag(EsTagInfo esTagInfo){
        String retStr="";
        if(esTagInfo!=null&&esTagInfo.getTagTypeId()!=null&&!esTagInfo.getTagTypeId().equals("")){
            JSONObject jsonObject=new JSONObject();
            String tagId="";
            if(esTagInfo.getTagId()!=null&&!esTagInfo.equals("")){//修改
                tagId=esTagInfo.getTagId();
                jsonObject.put("TagId",esTagInfo.getTagId());
                jsonObject.put("TagKey",esTagInfo.getTagKey());
                jsonObject.put("TagName",esTagInfo.getTagName());
                jsonObject.put("TagTypeName",esTagInfo.getTagTypeName());
                jsonObject.put("TagTypeId",esTagInfo.getTagTypeId());
            }else if(esTagInfo.getTagTypeId()!=null){//新增
                //获取父级
                List list=em.createNativeQuery("SELECT A.[Text] FROM Mem_DataDictory AS A WHERE 1 = 1 AND A.ParentId = 5552 and A.Value="+esTagInfo.getTagTypeId()).getResultList();
                if(list.size()>0){
                    String TagId=esTagInfo.getTagTypeId();
                    String TagName= list.get(0).toString();
                    String jsonStr=ESQuery("select count(1) as key from mem_tag where TagTypeId="+esTagInfo.getTagTypeId(),"_sql?format=json");
                    JSONArray countArr= (JSONArray) JSONObject.fromObject(jsonStr).get("rows");
                    Integer count= Integer.parseInt(countArr.get(0).toString().replaceAll("\\[","").replaceAll("\\]",""))+1;
                    TagId+=padRight(String.valueOf(count),6,'0');
                    jsonStr=ESQuery("select TagKey from mem_tag where TagId in ("+TagId+") or TagName = '"+esTagInfo.getTagName()+"'","_sql?format=json");
                    JSONObject areJson=JSONObject.fromObject(jsonStr);
                    List<JSONArray> areMap = (List<JSONArray>) areJson.get("rows");
                    if(areMap.size()>0){
                        return "标签已存在";
                    }
                    tagId=TagId;
                    jsonObject.put("TagId",TagId);
                    jsonObject.put("TagKey",count);
                    jsonObject.put("TagName",esTagInfo.getTagName());
                    jsonObject.put("TagTypeName",TagName);
                    jsonObject.put("TagTypeId",esTagInfo.getTagTypeId());
                }
            }

            jsonObject.put("TagCrtTime",new Date().getTime());
            if(tagId!=null&&!tagId.equals("")){
                retStr=esUtils.post(jsonObject,Host+"mem_tag/_doc/"+tagId);
            }
        }
        return retStr;
    }

    /***
     * 类目列表
     * @param data
     * @return
     */
    @Override
    public Map<String,Object> getTagTypes(FiltersData data){
        Map<String,Object> map=new HashMap<String,Object>();
        String filter="";
        Integer pageIndex = data.getPageIndex();
        Integer pageSize = data.getPageSize();
        Integer sortDirection = data.getSortDirection();
        String direct = " desc ";
        filter = esUtils.getFilterString(data.getFilters(),"A.");
        if (sortDirection != 1)
        {
            direct = " asc";
        }

        int start = (pageIndex - 1) * pageSize;
        int end = (start + 1 + pageSize);

        String commandText0 = "select * from ";
        String commandText1 = "(" +
                "select A.Id,A.IsHide,A.[Text],A.SortKey,A.SyncStatus,A.[Key],A.ParentId,A.Remark,A.[Value],row_number() over" +
                "(  order by A.Id " + direct + " )  as rownum from " +
                "Mem_DataDictory as A  " +
                " where  1=1 " +
                " and A.ParentId = 5552 " +
                filter +
                ")AAA ";
        String commandText2 = " where AAA.rownum>" + start + " and AAA.rownum<" + end
                + "  ORDER BY AAA.Id desc";
        String commandText3 = commandText0 + commandText1 + commandText2;
        List list = em.createNativeQuery(commandText3).getResultList();
        String[] key = {"Id","IsHide","Text","SortKey","SyncStatus","Key","ParentId","Remark","Value"};
        List<Map<String,Object>> listMap=transferToMap(key,list);
        list = em.createNativeQuery("select count(Id) from "+ commandText1).getResultList();
        map.put("items",listMap);
        map.put("totalCount",list.get(0));
        return map;
    }

    /***
     * 用户用药信息
     * @return
     */
    @Override
    public Map<String,Object> getUsedrug(FiltersData data) {
        Map<String,Object> retMap=new HashMap<String,Object>();
        List<Map<String, Object>> listMap=null;
        //clickhouse查询用药信息
        int OutDays = 5;
        List<FiltersUtils> filters = data.getFilters();
        Integer pageIndex = data.getPageIndex();
        Integer pageSize = data.getPageSize();
        String sortField = data.getSortField();
        Integer sortDirection = data.getSortDirection();
        String commandText="";
        String source = "";//平台
        String tagstr = "";//标签
        if (filters != null && filters.size() > 0)
        {

            String keyTag = null;
            for (FiltersUtils filter : filters)
            {
                if (filter.getField().equals("OutDays") && filter.getValue() != null && filter.getValue() != "")
                {
                    OutDays = Integer.parseInt(filter.getValue());
                }
                if (filter.getField() .equals("tagKey") && filter.getValue() != null && filter.getValue() != "")
                {
                    keyTag = filter.getValue();
                }
            }
            if (keyTag!=null) {
                var keyArr = keyTag.split("_");//0标签1平台2终端
                if (keyArr.length > 0)
                {
                    var key0 = keyArr[0].split(",");
                    if (!key0[0].equals("0")&& key0[0].length()>0)
                    {
                        for (String memtag : key0)
                        {
                            commandText = commandText + "'" + memtag + "',";
                        }
                        if (commandText != "" && commandText.length() > 0)
                        {
                            tagstr = " AND t.tagId IN(" + commandText.substring(0, commandText.length() - 1) + ") ";
                        }

                    }
                    if (keyArr.length > 1 && keyArr[1] != null)
                    {
                        var key1 = keyArr[1].split(",");
                        if (!key1[0].equals("0"))
                        {
                            source = source + " AND s.ConsigneeType IN("+ keyArr[1] + ") ";
                        }
                    }
                    if (keyArr.length > 2 && keyArr[2]!=null)
                    {
                        var key2 = keyArr[2].split(",");
                        if (!key2[0].equals("0"))
                        {
                            source = source + " AND s.OriginType IN(" + keyArr[2]+ ") ";
                        }
                    }
                }
            }
        }

        String direct = " asc ";
        if (sortDirection != 1)
        {
            direct = " desc ";
        }
        String orderStr = " MinDates asc,DomeCount desc ";
        if (sortField.equals("MemPhone")||sortField.equals("UseCount")||sortField.equals("DomeCount")||sortField.equals("EndTime")) {
            orderStr = sortField + direct;
        }

        int start = (pageIndex - 1) * pageSize;
        int end = (start + 1 + pageSize);



        Date d= DateUtils.addDays(new Date(), -60);
        Random re=new Random(1100);
        int totalCount=9464;
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss" );
        String sql = " sum(CASE WHEN(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) <= "+ OutDays + " THEN 1 ELSE 0 END) as DomeCount," +
                "sum(CASE WHEN(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) >0 THEN 1 ELSE 0 END) as UseCount, " +
                "min(minus(multiply(toInt8(u.UsageDays),toInt8(s.Amount)),minus(today(),toDate(s.OrderTime)))) as MinDates," +
                "min(toDateTime(plus(multiply(toInt8(u.UsageDays),toInt8(s.Amount))*24*3600,toUnixTimestamp(s.OrderTime)))) as EndTime," +
                "toDate(plus(toUnixTimestamp(now()),MinDates*24*3600)) as EndDay," +
                "" + OutDays + " as OutDays," +
                "s.AConsigneePhone2 AS MemPhone ";

        String commandText1 = "SELECT " + sql+
                "  FROM `default`.OrdersAndOrderProducts s " +
                "global LEFT JOIN (select ProductCode,min(UsageDays)as UsageDays  from ProductUsage group by ProductCode) u ON u.ProductCode = s.ProductCode " +
                "global LEFT JOIN (select MemberPhone,tagId,id,MAX(create_date) FROM memberTagV2 m " +
                "global LEFT JOIN (SELECT id,create_date FROM memberTagV2 WHERE tagId='0' GROUP BY id,MemberPhone,tagId,create_date)c ON c.id=m.MemberPhone " +
                "WHERE  m.create_date>c.create_date GROUP BY m.id,m.MemberPhone,m.tagId) t ON t.MemberPhone=s.AConsigneePhone2 " +
                "where u.UsageDays != '' AND s.AConsigneePhone2 != '' " +
                " AND s.OrderTime > '"+ fmt.format(d) + "' " + source+ tagstr;
        commandText1 = commandText1 + " GROUP BY MemPhone,s.OrderTime HAVING DomeCount>0 and MinDates>=1 "+
                " ORDER BY " + orderStr;
        String commandText2 = " LIMIT "+ start + ",20 ";
        String commandText3 =  commandText1 + commandText2;
        try {
              List<Map> map=esUtils.exeSql(commandText3);
              //List<Map> total=esUtils.exeSql("SELECT count(1) cn FROM  ("+ commandText1 + ")");
             for(Map m:map){
                 String strSql="USE Mall SELECT o.OrderStatus,p1.ProductCode,p1.ProductName,p1.Dosage,(select dbo.DesDecryptFixKey('123456','123456e10adc3949ba59abbe56e057f20f883e',o.AConsigneePhone2)) as AConsigneePhone2,o.Consignee,CONVERT(varchar(100), p.CreationDate, 23) AS CrDate,B.CreationDate AS GoDate,p1.packing,(ISNULL(u.UsageDays*p.Amount,0)) AS EndCount FROM  Orders o  LEFT JOIN OrderProducts p ON o.OrdersCode= p.OrdersCode  LEFT JOIN Product p1 ON p1.ProductCode=p.ProductCode  LEFT JOIN ProductUsage u ON u.ProductCode=p1.ProductCode  LEFT JOIN MemberStopDrugMsg B ON B.MemPhone=o.AConsigneePhone2  WHERE NOT (o.AConsigneePhone2 IN(SELECT B.MemPhone FROM MemberStopDrugMsg B ) AND p1.ProductCode IN(SELECT B.ProductCode FROM MemberStopDrugMsg B )) AND o.CreationDate > '2019-10-10 14:05:04'  AND p1.ProductCode!='' AND o.AConsigneePhone2='"+m.get("MemPhone")+"' GROUP BY o.OrderStatus,p1.ProductCode,o.Consignee,CONVERT(varchar(100), p.CreationDate, 23),B.CreationDate,p1.ProductName,p1.Dosage,p.Amount,u.UsageFrequencyCount,u.UsageDays,u.UsagePerUseCount,p1.packing,o.AConsigneePhone2  ORDER BY B.CreationDate ";
                 String[] key = {"OrderStatus","ProductCode","ProductName","Dosage","AConsigneePhone2","Consignee","CrDate","GoDate","packing","EndCount"};
                 List list=em.createNativeQuery(strSql).getResultList();
                 listMap=transferToMap(key,list);
                 m.put("Mem_Goods",listMap);
                 int totla1 = 0;
                 int totla2 = 0;
                 if(listMap.size()>0){
                    for(Map u:listMap){
                        if (u.get("EndCount")!=null) {
                            Date date = fmt.parse(u.get("CrDate").toString()+" 00:00:00");
                            long ts = new Date().getTime() / 1000 / 3600 / 24 - date.getTime() / 1000 / 3600 / 24;
                            long tocount=Long.parseLong(u.get("EndCount").toString())-ts;
                            if(tocount<0){
                                tocount=0;
                            }
                            u.put("EndCount",tocount);
                        }
                        u.put("ProductCode",u.get("ProductCode")+"_"+re.nextInt());
                    }

                     String AConsigneePhone2=String.valueOf(listMap.get(0).get("AConsigneePhone2"));
                     m.put("MemPhone",AConsigneePhone2.substring(0,3)+"****"+AConsigneePhone2.substring(7,AConsigneePhone2.length()));
                     m.put("MemName",listMap.get(0).get("Consignee"));
                     m.put("UpTime",listMap.get(0).get("GoDate"));
                 }

             }

            retMap.put("items",map);
            retMap.put("totalCount",totalCount);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retMap;
    }

    //sql链接es
    public String ESQuery(String sqlStr,String url){
        String esStr="{\"query\":\""+sqlStr+"\"}";
        JSONObject jsonObject=JSONObject.fromObject(esStr);
        return esUtils.post(jsonObject,Host+url);
    }

    private List<Map<String, Object>> transferToMap(String[] key, List list){
        Map<String,Object> map = null;
        List<Map<String, Object>>  resultList = new java.util.ArrayList();
        for(int j = 0; j < list.size(); j++){
            Object[] objArr = (Object[])list.get(j);
            map = new HashMap<String,Object>();
            for(int i = 0; i < key.length; i++){
                map.put(key[i],objArr[i]);
            }
            resultList.add(map);
        }
        return resultList;
    }

    //标签ID补全
    public static String padRight(String src, int len, char ch) {
        int diff = len - src.length();
        if (diff <= 0) {
            return src;
        }
        char[] charr = new char[len];
        System.arraycopy(src.toCharArray(), 0, charr, diff, src.length());
        for (int i = 0; i < diff; i++) {
            charr[i] = ch;
        }
        return new String(charr);
    }
}