var System=require("../../system");
var settings=require("../../../config/settings");
const querystring = require('querystring');
const ApiBase =require("../api.base");

class CjtLbsSearchApi extends ApiBase{
  constructor(){
    super();
    this.lbsUrl = settings.reqEsAddrIc()+"bigdata_lbs_op/_search";
    this.baiduUrl = "http://api.map.baidu.com/geocoder/v2";
  };
  buildDate(date){
    var date = new Date(date);
    var time = Date.parse(date);
    time=time / 1000;
    return time;
  };
  async lbsSearch(obj){//根据不同条件设置，(appkey，地址，距离必选,注册时间，一级行业，经营状态可选，排序条件可选，1为排序，0为不排序，默认不排序）查询LBS信息
    //http://api.map.baidu.com/geocoder/v2/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation //GET请求
    var data=await this.checkKey(obj.appKey);
    if(data && data.status && data.status==-1){
      return data;
    }

    var pagesize = obj.pagesize==null?10:obj.pagesize;
    var currentpage = obj.currentpage==null?1:obj.currentpage
    var from = obj.currentpage==null?0:Number((obj.currentpage-1)*obj.pagesize);

    var address=obj.address==null?"":obj.address;
    if(address==""){
        return {status:-1,msg:"传入地址为空",data:null};
    }
    var distance=obj.distance==null?"":obj.distance;
    if(distance==""){
        return {status:-1,msg:"传入距离为空",data:null};
    }
    address=await this.getConvertSemiangleStr(address);//全半角转化
    var baiduparams = {
        address:address,
        output:"json",
        ak:"wjuGR1o7dAX2hnAMFQDxjhAGVOrciktm"
    }

    var lat = "";
    var lng = "";
    var baidudata=querystring.stringify(baiduparams);
    var baiduurl = "http://api.map.baidu.com/geocoder/v2/?address="+address + "&output=json&ak=wjuGR1o7dAX2hnAMFQDxjhAGVOrciktm";
    var rc1=System.getObject("util.execClient");
    try{
      var rtn1=await rc1.execGet("",baiduurl);
      var relocation=JSON.parse(rtn1.stdout);
      if(relocation.status!=0){
        return {status:-1,msg:"获取地址的坐标信息出错",data:null};
      }else{
        lat = relocation.result.location.lat;
        lng = relocation.result.location.lng;
      }
    }catch(e){
      return {status:-1,msg:"获取地址的坐标信息出错",data:null};
    }

    if (lat=="" || lng=="")
    {
      return {status:-1,msg:"获取地址的坐标信息出错",data:null};
    }

    var starttime = obj.starttime==null?"":obj.starttime;
    var endtime = obj.endtime==null?"":obj.endtime;
    var categoryname = obj.categoryname==null?"":obj.categoryname;
    var managementstate = obj.managementstate==null?"":obj.managementstate;
    var sortmark = obj.sortmark==null?0:obj.sortmark;
    if (sortmark ==0)
    {
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize
      };
    }
    else{
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize,
        "sort": [
          {
           "_geo_distance": {
               "location": {
                   "lat": lat,
                   "lon": lng
               },
               "order": "asc",
               "unit": "km",
               "mode": "min",
               "distance_type": "plane"
           }
          }
        ]
      };
    }

    var param =  {
      "geo_distance": {
        "distance": distance +"km",
        "location": {
          "lat": lat,
          "lon": lng
        }
      }
    }
    params.query.bool.must.push(param)

    if (managementstate!=""){
      param =  {
        "term": {
          "management_sate": managementstate
        }
      }
    }
    params.query.bool.must.push(param)

    if (categoryname!=""){
      param =  {
        "term": {
            "category_code1": categoryname
        }
      }
    }
    params.query.bool.must.push(param)

    if (starttime != "" && endtime != ""){
      param =  {
        "range": {
          "estiblish_time": {
            "gte": starttime,
            "lte": endtime
          }
        }
      }
    }
    params.query.bool.must.push(param)


    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.lbsUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      var sources=[];
      var data={
        "result":1,
        "totalSize":j.hits.total,
        "pageSize":pagesize,
        "currentPage":currentpage,
        "list":sources
      };
      console.log(data);
      j.hits.hits.forEach(function(c){
        if (sortmark == 0){
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3
          }
        }
        else{
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3,
            "differ_distance":(c.sort[0].toFixed(3)).toString() + "km"
            //"differ_distance":("%.3f" % c.sort[0]).toString() + "km"
          }

        };
        sources.push(source);

      });
      return {status:0,msg:"操作成功",data:data};
    }catch(e){
      return {status:-1,msg:"操作失败",data:null};
    }
  };

  async lbsCitySearch(obj){//按照城市查询
    var data=await this.checkKey(obj.appKey);
    if(data && data.status && data.status==-1){
      return data;
    }

    var pagesize = obj.pagesize==null?10:obj.pagesize;
    var currentpage = obj.currentpage==null?1:obj.currentpage
    var from = obj.currentpage==null?0:Number((obj.currentpage-1)*obj.pagesize);

    var cityname=obj.cityname==null?"":obj.cityname;
    if(cityname==""){
        return {status:-1,msg:"传入城市为空",data:null};
    }

    var lat = "";
    var lng = "";
    var baiduurl = "http://api.map.baidu.com/geocoder/v2/?address="+ cityname + "&output=json&ak=wjuGR1o7dAX2hnAMFQDxjhAGVOrciktm";
    var rc1=System.getObject("util.execClient");
    try{
      var rtn1=await rc1.execGet("",baiduurl);
      var relocation=JSON.parse(rtn1.stdout);
      if(relocation.status!=0){
        return {status:-1,msg:"获取城市的坐标信息出错",data:null};
      }else{
        lat = relocation.result.location.lat;
        lng = relocation.result.location.lng;
      }
    }catch(e){
      return {status:-1,msg:"获取城市的坐标信息出错",data:null};
    }

    if (lat=="" || lng=="")
    {
      return {status:-1,msg:"获取城市的坐标信息出错",data:null};
    }

    var starttime = obj.starttime==null?"":obj.starttime;
    var endtime = obj.endtime==null?"":obj.endtime;
    var categoryname = obj.categoryname==null?"":obj.categoryname;
    var managementstate = obj.managementstate==null?"":obj.managementstate;
    var sortmark = obj.sortmark==null?0:obj.sortmark;
    if (sortmark ==0)
    {
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize
      };
    }
    else{
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize,
        "sort": [
          {
           "_geo_distance": {
               "location": {
                   "lat": lat,
                   "lon": lng
               },
               "order": "asc",
               "unit": "km",
               "mode": "min",
               "distance_type": "plane"
           }
          }
        ]
      };
    }

    var param =  {
      "query_string": {
        "default_field": "company_address",
        "query": "\""+ cityname + "\""
      }
    }
    params.query.bool.must.push(param)

    if (managementstate!=""){
      param =  {
        "term": {
          "management_sate": managementstate
        }
      }
    }
    params.query.bool.must.push(param)

    if (categoryname!=""){
      param =  {
        "term": {
            "category_code1": categoryname
        }
      }
    }
    params.query.bool.must.push(param)

    if (starttime != "" && endtime != ""){
      param =  {
        "range": {
          "estiblish_time": {
            "gte": starttime,
            "lte": endtime
          }
        }
      }
    }
    params.query.bool.must.push(param)


    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.lbsUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      var sources=[];
      var data={
        "result":1,
        "totalSize":j.hits.total,
        "pageSize":pagesize,
        "currentPage":currentpage,
        "list":sources
      };
      console.log(data);
      j.hits.hits.forEach(function(c){
        if (sortmark == 0){
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3
          }
        }
        else{
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3,
            "differ_distance":(c.sort[0].toFixed(3)).toString() + "km"
            //"differ_distance":("%.3f" % c.sort[0]).toString() + "km"
          }

        };
        sources.push(source);

      });
      return {status:0,msg:"操作成功",data:data};
    }catch(e){
      return {status:-1,msg:"操作失败",data:null};
    }
  };

  async lbsLalSearch(obj){//按照城市查询
    var data=await this.checkKey(obj.appKey);
    if(data && data.status && data.status==-1){
      return data;
    }

    var pagesize = obj.pagesize==null?10:obj.pagesize;
    var currentpage = obj.currentpage==null?1:obj.currentpage
    var from = obj.currentpage==null?0:Number((obj.currentpage-1)*obj.pagesize);
    var distance=obj.distance==null?"":obj.distance;
    if(distance==""){
        return {status:-1,msg:"传入距离为空",data:null};
    }
    var lat = obj.lat==null?"":obj.lat;
    var lng = obj.lng==null?"":obj.lng;

    if (lat=="" || lng=="")
    {
      return {status:-1,msg:"传入坐标为空",data:null};
    }

    var starttime = obj.starttime==null?"":obj.starttime;
    var endtime = obj.endtime==null?"":obj.endtime;
    var categoryname = obj.categoryname==null?"":obj.categoryname;
    var managementstate = obj.managementstate==null?"":obj.managementstate;
    var sortmark = obj.sortmark==null?0:obj.sortmark;
    if (sortmark ==0)
    {
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize
      };
    }
    else{
      var params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize,
        "sort": [
          {
           "_geo_distance": {
               "location": {
                   "lat": lat,
                   "lon": lng
               },
               "order": "asc",
               "unit": "km",
               "mode": "min",
               "distance_type": "plane"
           }
          }
        ]
      };
    }

    var param =  {
      "geo_distance": {
        "distance": distance +"km",
        "location": {
          "lat": lat,
          "lon": lng
        }
      }
    }
    params.query.bool.must.push(param)

    if (managementstate!=""){
      param =  {
        "term": {
          "management_sate": managementstate
        }
      }
    }
    params.query.bool.must.push(param)

    if (categoryname!=""){
      param =  {
        "term": {
            "category_code1": categoryname
        }
      }
    }
    params.query.bool.must.push(param)

    if (starttime != "" && endtime != ""){
      param =  {
        "range": {
          "estiblish_time": {
            "gte": starttime,
            "lte": endtime
          }
        }
      }
    }
    params.query.bool.must.push(param)


    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.lbsUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      var sources=[];
      var data={
        "result":1,
        "totalSize":j.hits.total,
        "pageSize":pagesize,
        "currentPage":currentpage,
        "list":sources
      };
      console.log(data);
      j.hits.hits.forEach(function(c){
        if (sortmark == 0){
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3
          }
        }
        else{
          var source={
            "self_location":[lng,lat],
            "company_id":c._source.company_id,
            "company_name":c._source.company_name,
            "legal_id":c._source.legal_id,
            "legal_name":c._source.legal_name,
            "company_type":c._source.company_type,
            "company_address":c._source.company_address,
            "estiblish_time":c._source.estiblish_time,
            "business_scope":c._source.business_scope,
            "phone_number":c._source.phone_number,
            "credit_code":c._source.credit_code,
            "register_id":c._source.register_id,
            "organization_code":c._source.organization_code,
            "management_sate":c._source.management_sate,
            "company_location":c._source.location,
            "from_time":c._source.from_time,
            "to_time":c._source.to_time,
            "company_property":c._source.company_property,
            "reg_institute":c._source.reg_institute,
            "institute_code":c._source.institute_code,
            "parent_code":c._source.parent_code,
            "reg_capital":c._source.reg_capital,
            "industry_code":c._source.industry_code,
            "category_code1":c._source.category_code1,
            "category_code2":c._source.category_code2,
            "category_code3":c._source.category_code3,
            "differ_distance":(c.sort[0].toFixed(3)).toString() + "km"
            //"differ_distance":("%.3f" % c.sort[0]).toString() + "km"
          }

        };
        sources.push(source);

      });
      return {status:0,msg:"操作成功",data:data};
    }catch(e){
      return {status:-1,msg:"操作失败",data:null};
    }
  };

  async getConvertSemiangleStr(str){
      var result = "";
      var len = str.length;
      for(var i=0;i<len;i++)
      {
          var cCode = str.charCodeAt(i);
          //全角与半角相差（除空格外）：65248（十进制）
          cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode;
          //处理空格
          cCode = (cCode==0x03000)?0x0020:cCode;
          result += String.fromCharCode(cCode);
      }
      //处理地址中的特殊字符
      result = result.replace(new RegExp("!","g"),"");
      result = result.replace(new RegExp("\\*","g"),"");
      result = result.replace(new RegExp("\\'","g"),"");
      result = result.replace(new RegExp("\\(","g"),"");
      result = result.replace(new RegExp("\\)","g"),"");
      result = result.replace(new RegExp(";","g"),"");
      result = result.replace(new RegExp(":","g"),"");
      result = result.replace(new RegExp("@","g"),"");
      result = result.replace(new RegExp("&","g"),"");
      result = result.replace(new RegExp("=","g"),"");
      result = result.replace(new RegExp("\\+","g"),"");
      result = result.replace(new RegExp("$","g"),"");
      result = result.replace(new RegExp(",","g"),"");
      result = result.replace(new RegExp("/","g"),"");
      result = result.replace(new RegExp("\\?","g"),"");
      result = result.replace(new RegExp("%","g"),"");
      result = result.replace(new RegExp("#","g"),"");
      result = result.replace(new RegExp("\\[","g"),"");
      result = result.replace(new RegExp("\\]","g"),"");
      return result;
  };
}
module.exports=CjtLbsSearchApi;
