//#import Util.js
//#import base64.js
//#import HttpUtil.js
//#import session.js
//#import $@projectCode:services/modelService.jsx
//#import @handlers/include/checklogin.jsx

var spec = @spec;

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

;(function(){

    var env = checklogin();
    if(!env){
        return;
    }
    var shopId = env.shopId;
    var warehouseId = env.warehouseId;
    var m = shopId;

    //判断是subplatform,还是shop,还是platform
    var params = JSON.parse($body);
    var searchArgs = params.searchArgs;
    var keyword = searchArgs.keyword;
    var pageSize = 0;
    var from = 0;

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

    function getFilters(){
        delete searchArgs.keyword;
        var filters = [];
        for(var k in searchArgs){
            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;
    }

    var filters = getFilters();

    if(m !== '0'){
        filters = filters.concat([
            {"term": { "_m.keyword": m }},
            {"term":{"_t":spec["_t"]}}
        ]);
    }
    else{
        //如果m === '0'，代表是平台
        filters = filters.concat([
            {"term":{"_t":spec["_t"]}}
        ]);
    }


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

    var aggs = {};

    var meta = spec[ "#meta" ];
    if(meta.charts){
        for(var i=0; i < meta.charts.length; i++){
            var chart = meta.charts[i];
            /*
            chart = {
                name:"daily_new_object",
                agg: {
                    "date_histogram": {
                        "field": "owl_createTime",
                        "calender_interval": "day",
                        "format" : "yyyy-MM-dd",
                        "time_zone": "+08:00"
                    }
                },
                description:'新增用户'
            }
             */
            aggs[chart.name] = chart.agg;
        }
    }


    if(aggs){
        query.aggs = aggs;
    }



    //下面开始计算统计数据

    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+"/@projectCode/_search";

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


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

    result.state = 'ok';
    out.print(JSON.stringify(result));

})();



