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

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

function buildSort(sort){
  if(!sort){
    return {};
  }
  var result = [];
  for(var k in sort){
    var direction = sort[k];
    if(direction === 'ascend'){
      var sortItem = {};
      sortItem[k] = [{"order":"asc"}]
      result.push(sortItem);
    }
    else if(direction === 'descend'){
      var sortItem = {};
      sortItem[k] = [{"order":"desc"}]
      result.push(sortItem);
    }
  }
  return result;
}
;(function(){

  var env = checklogin();
  if(!env){
    return;
  }
  var shopId = env.shopId;
  var warehouseId = env.warehouseId;
  var loginId = env.loginId;
  var roleId = env.roleId;
  var orgId = env.orgId;
  var spec = @spec;
  var tableId = 'owl_' + spec._t;
  var permissions = getPermissions(roleId,tableId);
  var m = shopId;
  ///////////////////////////////

//判断是subplatform,还是shop,还是platform
  var params = JSON.parse($body);
  var searchArgs = params.searchArgs;
  var keyword = searchArgs.keyword;
  var pageSize = params.pageSize;
  var page = params.page;
  var sort = params.sort;
  var recycleBin = searchArgs.recycleBin;
  // $.log("searchArgs=" + JSON.stringify(searchArgs));
  delete searchArgs.recycleBin;
  // $.log("recycleBin=" + recycleBin);

  var effectiveSort = buildSort(sort);
  if(!page){
    page = 1;
  }
  if(!pageSize){
    pageSize=15;
  }
  pageSize = Number(pageSize);
  var from = page * pageSize-pageSize;

  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 if(typeof(v)=='object' && v.type==='terms'){
        var terms = {};
        if(v.values){
          terms[k + ".keyword"] = v.values;
          filters.push({terms:terms});
        }
      }
      else{
        var term = {};
        if(v){
          term[k+".keyword"] = trim('' + v)
          filters.push({term:term})
        }
      }
    }

    var meta = spec['#meta'];
    var isPublic = meta && meta.isPublic;

/*
    if(!isPublic && orgId && orgId!=='0'){
      filters.push({
        "term":{
          "_orgIds.keyword" : orgId
        }
      })
    }
*/
    if(meta && meta.isTree && env.orgId!=='0'){
      if(meta.root){
        if(meta.root.startsWith("$")){
          var rootId = eval(meta.root.substring(1));
          filters.push({
            "term":{
              "parentPathIds" : rootId
            }
          })
        }
      }

    }
    return filters;
  }

  var filters = getFilters();
  var meta = spec['#meta'];
  var isPublic = meta && meta.isPublic;
  if(!isPublic && orgId && orgId!=='0') {
    var permissionFilter = getListPermissionFilter(tableId, roleId, orgId, loginId, permissions);

    if (permissionFilter) {
      filters.push(permissionFilter);
    }
  }

  if(recycleBin){
    filters.push({"term":{"del.keyword":"T"}});
    var query = {
      "query": {
        "bool": {
          "must": {
            "query_string": {
              "query":getKeywordQuery()
            }
          },
          "filter": filters
        }
      },
      "from" : from, "size" : pageSize,
      sort:effectiveSort || [{owl_createTime:{order:"desc"}}]
    }
  }
  else{
    var query = {
      "query": {
        "bool": {
          "must": {
            "query_string": {
              "query":getKeywordQuery()
            }
          },
          "must_not": {
            "match": {
              "del": "T"
            }
          },
          "filter": filters
        }
      },
      "from" : from, "size" : pageSize,
      sort:effectiveSort || [{owl_createTime:{order:"desc"}}]
    }
  }


  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);

  if(!result.hits || !result.hits.hits){
    // $.log("error search:sndQuery=" + sndTxt + "------\nresponse:\n" + s );
    var ret = {
      state:'ok',
      list:[],
      total:{value:0},
      count:0
    }
    out.print(JSON.stringify(ret));
    return;
  }


  var hits = result.hits.hits;
  var total = result.hits.total;

  var objs = hits.map(function(hit){return hit._source});

  delete query.from;
  delete query.size;
  delete query.sort;
  sndTxt = JSON.stringify(query);
  var countUrl = elasticSearchUrl+"/@projectCode/_count";

  var ss = HttpUtils.postRaw( countUrl, sndTxt, headers);
  var cr = JSON.parse(ss);

  var count = cr.count;
//这里重新从pigeon取了一次数据，做了删除的判断
// var ids = hits.map(function(hit){return hit._source.id});
// var list = owl_wh_receiptService.getObjects(ids);
// var objs  = list.filter(function(value){
//   return value.del != "T";
// });
  var ret = {
    state:'ok',
    list:objs,
    total:total,
    count : count
  }
  out.print(JSON.stringify(ret));

})();