//#import Util.js
//#import HttpUtil.js
//#import base64.js


var SearchUtil = {
    /**
     * 构造时间范围搜索条件（默认搜索参数为beginCreateTime和endCreateTime）
     * @param params ：请求参数对象
     * @returns {null}
     */
    getSearchDateRange:function (params) {
        return SearchUtil.getSearchDateRangeEx(params.beginCreateTime, params.endCreateTime);
    },
    /**
     * 构造时间范围搜索条件
     * @param beginTime ：格式为4102415999000
     * @param endTime ：格式为4102415999000
     * @returns {null}
     */
    getSearchDateRangeEx:function (beginTime, endTime) {
        if(!beginTime && !endTime) {
            return null;
        }
        if(!beginTime) {
            beginTime = 0;
        }
        if(!endTime) {
            endTime = 4102415999000;//表示永久的时间：2099-12-31 23:59:59
        }
        return [Number(beginTime), Number(endTime)];
    },
    /**
     * 创建查询对象
     * @param searchTableName 查询的表名
     * @param searchArgs     查询字段，格式{key:value,key:value}如果是范围查询{key:[v1,v2]}
     * @param page          页码
     * @param pageSize      页大小
     * @param sortArgs      排序方式 格式{key:"desc",key:"asc"}
     * @returns 查询条件对象
     */
    createQuery: function (searchTableName, searchArgs, page, pageSize, sortArgs) {
        if(searchTableName.indexOf("owl_") < 0) {
            searchTableName = "owl_" + searchTableName;
        }

        function trim(s) {
            if (s) {
                return s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
            }
            return "";
        }

        function getFilters() {
            var filters = [];
            for (var k in searchArgs) {
                if(k == "keyword"){
                    continue;
                }
                var v = searchArgs[k];
                if (typeof(v) == 'object' && Array.isArray(v)) {
                    var range = {}
                    range[k] = {
                        'gte': v[0],
                        'lte': v[1]
                    }
                    filters.push({range: range});
                } else {
                    var term = {};
                    if (v) {
                        term[k+".keyword"] = trim('' + v);
                        filters.push({term: term})
                    }
                }

            }
            return filters;
        }

        function getKeywordQuery(keyword){
            if(keyword && trim(keyword).length>0){
                return "\"" + trim(keyword) + "\""
            }
            else{
                return "*"
            }
        }

        var filters = getFilters();


        // filters = filters.concat([{"term": {"_t": searchTableName}}]);

        var query = {
            "query": {
                "bool": {
                    "must": {
                        "query_string": {
                            "query":getKeywordQuery(searchArgs.keyword)
                        }
                    },
                    "must_not": {
                        "match": {
                            "del": "T"
                        }
                    },
                    "filter": filters
                }
            }
        };

        if (page) {
            if (!pageSize) {
                pageSize = 10;
            }
            pageSize = Number(pageSize);
            var from = page * pageSize - pageSize;
            query["from"] = from;
            query["size"] = pageSize;
        }

        var sort = [];
        if (sortArgs && !Array.isArray(sortArgs)) {
            $.log("sortArgs is not array." + JSON.stringify(sortArgs))
            for (var k in sortArgs) {
                var v = sortArgs[k];
                var temp = {};
                temp[k] = {"order": v};
                sort.push(temp);
            }
        }
        else if(sortArgs && sortArgs.length>0){
            $.log("sortArgs is array." + JSON.stringify(sortArgs))
            sort = sortArgs;
        }
        else {
            sort.push({owl_createTime: {order: "desc"}});
        }
        query["sort"] = sort;

        return query;
    },

    /**
     * 条件查询
     * @param searchTableName 查询的表名
     * @param query 查询对象
     * @returns 查询结果对象，包含list:查询结果集，total:结果数量
     */
    searchByElements: function (searchTableName, query) {
        if(searchTableName.indexOf("owl_") < 0) {
            searchTableName = "owl_" + searchTableName;
        }

        var elasticSearchUrl = $.getEnv("elasticSearchUrl");

        var headers = {"Content-Type": "application/json;charset=utf-8"};
        var elasticSearchUser = $.getEnv("elasticSearchUser");
        var elasticSearchPass = $.getEnv("elasticSearchPass");
        if (elasticSearchUser && elasticSearchPass) {
            var auth = Base64.encode(elasticSearchUser + ":" + elasticSearchPass);
            var basicAuth = "Basic " + auth;
            headers["Authorization"] = basicAuth;
        }
        var searchUrl = elasticSearchUrl + "/" + searchTableName + "/_search";

        var sndTxt = JSON.stringify(query);
        $.log(sndTxt);

        var s = HttpUtils.postRaw(searchUrl, sndTxt, headers);
        var result = JSON.parse(s);
        var objs= [];
        var total = 0;
        if (result) {
            if(result.hits){
                var hits = result.hits.hits;
                total = result.hits.total;
                objs = hits.map(function (hit) {
                    return hit._source
                });
            }
        }
        var ret = {
            list: objs,
            total: total
        };
        return ret;
    },
    searchByElementsEx: function (searchTableName, query) {
        if(searchTableName.indexOf("owl_") < 0) {
            searchTableName = "owl_" + searchTableName;
        }

        var elasticSearchUrl = $.getEnv("elasticSearchUrl");

        var headers = {"Content-Type": "application/json;charset=utf-8"};
        var elasticSearchUser = $.getEnv("elasticSearchUser");
        var elasticSearchPass = $.getEnv("elasticSearchPass");
        if (elasticSearchUser && elasticSearchPass) {
            var auth = Base64.encode(elasticSearchUser + ":" + elasticSearchPass);
            var basicAuth = "Basic " + auth;
            headers["Authorization"] = basicAuth;
        }
        var searchUrl = elasticSearchUrl + "/" + searchTableName + "/_search";

        var sndTxt = JSON.stringify(query);

        var s = HttpUtils.postRaw(searchUrl, sndTxt, headers);
        var result = JSON.parse(s);
        return result;
    }
};