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

class WordPatentSearchApi extends ApiBase{
  constructor(){
    super();
    this.patentUrl = settings.reqEsAddrIc()+"bigdata_world_patent_bib_op/_search";
  };
  buildDate(date){
    var date = new Date(date);
    var time = Date.parse(date);
    time=time / 1000;
    return time;
  };
  async ObtainWorldPatentInfo(obj){
    console.log("-----------------api-ObtainWorldPatentInfo----------------");
    console.log(obj);
    var data=await this.checkKey(obj.appKey);
    if(data && data.status && data.status==-1){
      return data;
    }
    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
    };
    var applynum=obj.applynum==null?"":obj.applynum;//专利申请号
    if (applynum != null && applynum != ""){
      var param = {
        "term": {
           "app_number": applynum
        }
      }
      params.query.bool.must.push(param)
    }
    var publishnum=obj.publishnum==null?"":obj.publishnum;//专利申请号
    if (publishnum != null && publishnum != ""){
      var param = {
        "term": {
           "pub_number": publishnum
        }
      }
      params.query.bool.must.push(param)
    }
    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
  			msg:"操作成功",
        data:j.hits.hits
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null
      };
    }

  };

  async CommomSearchbyTitle(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var title = obj.title==null?"":obj.title;
    if(title==""){
        return {status:-1,msg:"传入标题信息为空",data:null,buckets:null};
    }

    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ],
      "aggregations": {
        "group_by_filing_year": {
            "terms": {
                "field": "app_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        },
        "group_by_pub_year": {
            "terms": {
                "field": "pub_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        }
      }
    };

    var param = {
      "match": {
        "title_name": title.toLowerCase()
      }
    }
    params.query.bool.must.push(param);

    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');

      param = {
        "bool": {
          "should": []
        }
      }

      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
      })
      params.query.bool.must.push(param);
    }

    var pubtype=obj.pubtype==null?"":obj.pubtype;//专利类型
    if (pubtype != null && pubtype != ""){
      param = {
        "term": {
           "pub_type": pubtype
        }
      }
      params.query.bool.must.push(param)
    }

    var pubstatus = obj.pubstatus==null?"":obj.pubstatus;//法律状态
    if (pubstatus != null && pubstatus != ""){
      param = {
        "term": {
           "status_code": pubstatus
        }
      }
      params.query.bool.must.push(param)
    }

    var filingyear = obj.filingyear==null?"":obj.filingyear;//申请年份
    if (filingyear != null && filingyear !=""){
      param = {
        "term": {
           "app_year": filingyear
        }
      }
      params.query.bool.must.push(param)
    }

    var pubyear = obj.pubyear==null?"":obj.pubyear;//公开年份
    if (pubyear != null && pubyear != ""){
      param = {
        "term": {
           "pub_year": pubyear
        }
      }
      params.query.bool.must.push(param)
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
  			msg:"操作成功",
        data:j.hits,
  			buckets:j.aggregations
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null,
        buckets:null
      };
    }

  };

  async CommomSearchbyFilingno(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var filingno = obj.filingno==null?"":obj.filingno;
    if(filingno==""){
        return {status:-1,msg:"传入的申请号信息为空",data:null,buckets:null};
    }

    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ],
      "aggregations": {
        "group_by_filing_year": {
            "terms": {
                "field": "app_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        },
        "group_by_pub_year": {
            "terms": {
                "field": "pub_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        }
      }
    };

    var param = {
      "wildcard": {
        "app_number": "*"+filingno+"*"
      }
    }
    params.query.bool.must.push(param);

    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');
      param = {
        "bool": {
          "should": []
        }
      }

      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
      })
      params.query.bool.must.push(param);
    }

    var pubtype=obj.pubtype==null?"":obj.pubtype;//专利类型
    if (pubtype != null && pubtype != ""){
      param = {
        "term": {
           "pub_type": pubtype
        }
      }
      params.query.bool.must.push(param)
    }

    var pubstatus = obj.pubstatus==null?"":obj.pubstatus;//法律状态
    if (pubstatus != null && pubstatus != ""){
      param = {
        "term": {
           "status_code": pubstatus
        }
      }
      params.query.bool.must.push(param)
    }

    var filingyear = obj.filingyear==null?"":obj.filingyear;//申请年份
    if (filingyear != null && filingyear !=""){
      param = {
        "term": {
           "app_year": filingyear
        }
      }
      params.query.bool.must.push(param)
    }

    var pubyear = obj.pubyear==null?"":obj.pubyear;//公开年份
    if (pubyear != null && pubyear != ""){
      param = {
        "term": {
           "pub_year": pubyear
        }
      }
      params.query.bool.must.push(param)
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
  			msg:"操作成功",
        data:j.hits,
  			buckets:j.aggregations
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null,
        buckets:null
      };
    }

  };

  async CommomSearchbyPubno(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var pubno = obj.pubno==null?"":obj.pubno;
    if(pubno==""){
        return {status:-1,msg:"传入的公开号信息为空",data:null,buckets:null};
    }

    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ],
      "aggregations": {
        "group_by_filing_year": {
            "terms": {
                "field": "app_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        },
        "group_by_pub_year": {
            "terms": {
                "field": "pub_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        }
      }
    };

    var param = {
      "wildcard": {
        "pub_number": "*"+pubno+"*"
      }
    }
    params.query.bool.must.push(param);

    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');
      param = {
        "bool": {
          "should": []
        }
      }

      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
      })
      params.query.bool.must.push(param);
    }

    var pubtype=obj.pubtype==null?"":obj.pubtype;//专利类型
    if (pubtype != null && pubtype != ""){
      param = {
        "term": {
           "pub_type": pubtype
        }
      }
      params.query.bool.must.push(param)
    }

    var pubstatus = obj.pubstatus==null?"":obj.pubstatus;//法律状态
    if (pubstatus != null && pubstatus != ""){
      param = {
        "term": {
           "status_code": pubstatus
        }
      }
      params.query.bool.must.push(param)
    }

    var filingyear = obj.filingyear==null?"":obj.filingyear;//申请年份
    if (filingyear != null && filingyear !=""){
      param = {
        "term": {
           "app_year": filingyear
        }
      }
      params.query.bool.must.push(param)
    }

    var pubyear = obj.pubyear==null?"":obj.pubyear;//公开年份
    if (pubyear != null && pubyear != ""){
      param = {
        "term": {
           "pub_year": pubyear
        }
      }
      params.query.bool.must.push(param)
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
        msg:"操作成功",
        data:j.hits,
        buckets:j.aggregations
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null,
        buckets:null
      };
    }

  };

  async CommomSearchbyApplicant(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var applicant = obj.applicant==null?"":obj.applicant;
    if(applicant==""){
        return {status:-1,msg:"传入的申请人信息为空",data:null,buckets:null};
    }

    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ],
      "aggregations": {
        "group_by_filing_year": {
            "terms": {
                "field": "app_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        },
        "group_by_pub_year": {
            "terms": {
                "field": "pub_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        }
      }
    };

    var param = {
      "match": {
        "applicant_name": applicant.toLowerCase()
      }
    }
    params.query.bool.must.push(param);

    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');
      param = {
        "bool": {
          "should": []
        }
      }

      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
      })
      params.query.bool.must.push(param);
    }

    var pubtype=obj.pubtype==null?"":obj.pubtype;//专利类型
    if (pubtype != null && pubtype != ""){
      param = {
        "term": {
           "pub_type": pubtype
        }
      }
      params.query.bool.must.push(param)
    }

    var pubstatus = obj.pubstatus==null?"":obj.pubstatus;//法律状态
    if (pubstatus != null && pubstatus != ""){
      param = {
        "term": {
           "status_code": pubstatus
        }
      }
      params.query.bool.must.push(param)
    }

    var filingyear = obj.filingyear==null?"":obj.filingyear;//申请年份
    if (filingyear != null && filingyear !=""){
      param = {
        "term": {
           "app_year": filingyear
        }
      }
      params.query.bool.must.push(param)
    }

    var pubyear = obj.pubyear==null?"":obj.pubyear;//公开年份
    if (pubyear != null && pubyear != ""){
      param = {
        "term": {
           "pub_year": pubyear
        }
      }
      params.query.bool.must.push(param)
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
        msg:"操作成功",
        data:j.hits,
        buckets:j.aggregations
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null,
        buckets:null
      };
    }
  };

  async CommomSearchbyInventor(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var inventor = obj.inventor==null?"":obj.inventor;
    if(inventor==""){
        return {status:-1,msg:"传入的发明人信息为空",data:null,buckets:null};
    }

    var params= {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ],
      "aggregations": {
        "group_by_filing_year": {
            "terms": {
                "field": "app_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        },
        "group_by_pub_year": {
            "terms": {
                "field": "pub_year",
                "size": 1000,
                "order":{"_term":"desc"}
            }
        }
      }
    };


    var param = {
      "match": {
        "inventor_name": inventor.toLowerCase()
      }
    }
    params.query.bool.must.push(param);

    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');
      param = {
        "bool": {
          "should": []
        }
      }

      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
  		})
      params.query.bool.must.push(param);
    }

    var pubtype=obj.pubtype==null?"":obj.pubtype;//专利类型
    if (pubtype != null && pubtype != ""){
      param = {
        "term": {
           "pub_type": pubtype
        }
      }
      params.query.bool.must.push(param)
    }

    var pubstatus = obj.pubstatus==null?"":obj.pubstatus;//法律状态
    if (pubstatus != null && pubstatus != ""){
      param = {
        "term": {
           "status_code": pubstatus
        }
      }
      params.query.bool.must.push(param)
    }

    var filingyear = obj.filingyear==null?"":obj.filingyear;//申请年份
    if (filingyear != null && filingyear !=""){
      param = {
        "term": {
           "app_year": filingyear
        }
      }
      params.query.bool.must.push(param)
    }

    var pubyear = obj.pubyear==null?"":obj.pubyear;//公开年份
    if (pubyear != null && pubyear != ""){
      param = {
        "term": {
           "pub_year": pubyear
        }
      }
      params.query.bool.must.push(param)
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return rtn = {
        status:0,
        msg:"操作成功",
        data:j.hits,
        buckets:j.aggregations
      };
    }catch(e){
      return rtn={
        status:-1,
        msg:"操作失败",
        data:null,
        buckets:null
      };
    }

  };

  async seniorSearch(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;
    if(obj.page==null){
      var from = 0;
    }else{
      var from = Number((obj.page-1)*obj.pagesize);
    }

    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "app_number",
        "app_date",
        "pub_number",
        "pub_type",
        "pub_date",
        "title_name",
        "applicant_name",
        "inventor_name"
      ]
    };

    var param = null;
    //对库做判断
    var dbnames = obj.danames==null?"":obj.danames;
    if (dbnames != null && dbnames != ""){
      var dbarray = dbnames.split('+');
      param = {
        "bool": {
          "should": []
        }
      }
      dbarray.forEach(function(d){
        var parr = {
          "term": {
             "db_name": d
           }
         }
        param.bool.should.push(parr)
  		})
      params.query.bool.must.push(param);
    }

    //对关键词
    var title=obj.title==null?"":obj.title;
    if (title != null && title != ""){
      param ={
        "match": {
           "title_name": title.toLowerCase()
        }
      }
      params.query.bool.must.push(param)
    }

    var abstr = obj.abstr==null?"":obj.abstr;
    if (abstr != null && abstr != ""){
      param ={
        "match": {
           "abstr_text": abstr.toLowerCase()
        }
      }
      params.query.bool.must.push(param)
    }

    var filingno=obj.filingno==null?"":obj.filingno;
    if(filingno!=null && filingno!=""){
      param=  {
        "term": {
          "app_number": filingno
        }
      }
      params.query.bool.must.push(param)
    }

    var pubno=obj.pubno==null?"":obj.pubno;
    if (pubno!=null && pubno!=""){
      param=  {
        "term": {
          "pub_number": pubno
        }
      }
      params.query.bool.must.push(param)
    }

    var priorno=obj.priorno==null?"":obj.priorno;
    if (priorno != null && priorno != ""){
      param={
        "wildcard": {
          "prior_info": priorno+"*"
        }
      }
      params.query.bool.must.push(param)
    }

    var appl=obj.applname==null?"":obj.applname;
    if (appl!=null && appl!=""){
      param=  {
        "term": {
          "applicant_name.raw": appl.toLowerCase()
        }
      }
      params.query.bool.must.push(param)
    }
    var inv=obj.invname==null?"":obj.invname;
    if (inv!=null && inv!=""){
      param=  {
        "term": {
          "inventor_name.raw": inv.toLowerCase()
        }
      }
      params.query.bool.must.push(param)
    }
    var ipc=obj.ipcno==null?"":obj.ipcno;
    if (ipc!=null && ipc!=""){
      var param=  {
        "term": {
          "other_ipc": ipc
        }
      }
      params.query.bool.must.push(param)
    }

    if(obj.filingdate1!=null && obj.filingdate1!=""){
      var filingdate1=obj.filingdate1;
    }
    else {
      var filingdate1 ="";
    }
    if(obj.filingdate2!=null && obj.filingdate2!=""){
      var filingdate2=obj.filingdate2;
    }
    else {
      var filingdate2 = "";
    }
    if (filingdate1!="" || filingdate2!=""){
      param={
        "range": {
          "app_date": {
          }
        }
      };
      if (filingdate1!=""){
        param.range.app_date["gte"]=filingdate1;
      }
      if (filingdate2!=""){
        param.range.app_date["lte"]=filingdate2;
      }
      params.query.bool.must.push(param);
    }

    if(obj.pubdate1!=null && obj.pubdate1!=""){
      var pubdate1=obj.pubdate1;
    }
    else {
      var pubdate1 ="";
    }
    if(obj.pubdate2!=null && obj.pubdate2!=""){
      var pubdate2=obj.pubdate2;
    }
    else {
      var pubdate2 = "";
    }
    if (pubdate1!="" || pubdate2!=""){
      param={
        "range": {
          "pub_date": {

          }
        }
      };
      if (pubdate1!=""){
        param.range.pub_date["gte"]=pubdate1;
      }
      if (pubdate2!=""){
        param.range.pub_date["lte"]=pubdate2;
      }
      params.query.bool.must.push(param);
    }

    var rc=System.getObject("util.execClient");
    var rtn=null;
    var requrl = this.patentUrl;
    try{
      rtn=await rc.execPost(params,requrl);
      var j=JSON.parse(rtn.stdout);
      return System.getResult2(j.hits,null);
    }catch(e){
      return rtn=System.getResult2(null,null);
    }
  };
}
module.exports = WordPatentSearchApi;
