var System=require("../../system");
var settings=require("../../../config/settings");
const logCtl=System.getObject("web.oplogCtl");
//工商查询操作
class UtilsIcService{
  constructor(){
    this.paSearchUrl=settings.apiconfig.paSearchUrl();
    // this.tmSearchUrl=settings.apiconfig.tmSearchUrl();
  }

    /*查询某一个公司名下有多少条专利(applicant_name:公司-精确)
    auther:sy
    {
        "status": 0,
        "msg": "操作成功",
        "total": 54,
        "data": [
            {
                "fm_count": 1,
                "wg_count": 1,
                "syxx_count": 1
            }
        ],
        "bizmsg": "empty"
    }

    返回值说明:status为0则为成功，否则为查询有误
    	 "fm_count",发明
    	 "wg_count",外观设计
    	 "syxx_count",实用新型
    */
    async paCountByApplicantName(obj,opName){
      var applicantName=obj.applicant_name==null||obj.applicant_name==""||obj.applicant_name=="undefined"?"":obj.applicant_name;
      if(applicantName==""){
        return System.getResult2(null,null,null,"申请人不能为空");
      }
      applicantName=await this.getConvertSemiangleStr(applicantName);
      var reqUrl=this.paSearchUrl;
      var params ={
          "size": 0,
          "query": {
              "bool": {
                  "must": [
                      {
                          "term": {
                              "applicant_name.raw": applicantName
                          }
                      }
                  ]
              }
          },
          "aggs": {
              "group_by_type": {
                  "terms": {
                      "field": "pub_type"
                  }
              }
          }
      };
      // var params ={
      //     "size": 0,
      //     "query": {
      //         "bool": {
      //             "must": [
      //                 {
      //                     "term": {
      //                         "applicant_cn": "江苏洋河酒厂股份有限公司"
      //                     }
      //                 }
      //             ]
      //         }
      //     },
      //     "aggs": {
      //         "group_by_type": {
      //             "terms": {
      //                 "field": "status"
      //             }
      //         }
      //     }
      // };
      var rc=System.getObject("util.execClient");
      var rtn=null;
      try{
        rtn=await rc.execPost(params,reqUrl);
        var j=JSON.parse(rtn.stdout);
        if(j.status!=undefined){
          //执行查询有错
          //日志记录
          logCtl.error({
             optitle:"ES查询专利数量opClassName=utilspaSve，opMethod=paCountByApplicantName，ES执行异常error",
             op:"base/service/impl/tmutilsSve.js",
             content:rtn.stdout,
             clientIp:""
           });
           return System.getResult2(null,null,null,"查询出错");
        }
        var rtnResult= System.getResult3(j.hits,null);
        var tmpCount={
           fm_count:0,
           wg_count:0,
           syxx_count:0
        };
        var letCount=j.aggregations.group_by_type.buckets.length;
        if(letCount>0){
          for (var i = 0; i < letCount; i++) {
              var item=j.aggregations.group_by_type.buckets[i];
              if(item.key=="外观设计"){
                tmpCount.wg_count=item.doc_count;
              }
              else if(item.key=="实用新型"){
                tmpCount.syxx_count=item.doc_count;
              }
              else if (item.key=="发明") {
                tmpCount.fm_count=item.doc_count;
              }
          }
        }
        rtnResult.data.push(tmpCount);
        return rtnResult;
      }catch(e){
        //日志记录
        logCtl.error({
           optitle:"ES查询专利数量opClassName=utilspaSve，opMethod=paCountByApplicantName，异常error",
           op:"base/service/impl/utilspaSve.js",
           content:e.stack,
           clientIp:""
         });
        return System.getResult2(null,null,null,"查询异常");
      }
      return this.returnResult(params,reqUrl,opName,"paCountByApplicantName");
    }

    /*查询某一个公司名下有专利列表(applicant_name:公司-精确)
      auther:sy
      返回值：
        {
          "status": 0,
          "msg": "操作成功",
          "total": 2,
          "data": [
              {
              	 "filing_name":"",
              	 "pub_status_now":"",
      			 "filing_no":"",
              	 "filing_date":"",
              	 "gr_date":"",
              	 "gr_no":"",
              	 "pub_date":"",
              	 "pub_no":"",
      			 "pa_type":""
              }
          ],
          "bizmsg": "empty"
      }
      返回值说明:status为0则为成功，否则为查询有误
      	 "filing_name",发明名称
      	 "pub_status_now",法律状态
      	 "filing_no",申请号
      	 "filing_date",申请日期
      	 "gr_date",授权日期
      	 "gr_no",授权公布号
      	 "pub_date",公开（公告）日期
      	 "pub_no",公开（公告）号
      	 "pa_type"专利类型
           "total"						  总条数
      */
    async paShortListByApplicantName(obj,opName){
      var applicantName=obj.applicant_name==null||obj.applicant_name==""||obj.applicant_name=="undefined"?"":obj.applicant_name;
      var paType=obj.pa_type==null||obj.pa_type==""||obj.pa_type=="undefined"?"":obj.pa_type;
      if(applicantName==""){
        return System.getResult2(null,null,null,"申请人不能为空");
      }
      if(paType==""){
        return System.getResult2(null,null,null,"专利类型不能为空");
      }
      var pagesize=obj.page_size==null||obj.page_size==""||obj.page_size=="undefined"?20:obj.page_size;
      if(pagesize>100){
        pagesize=20;
      }
      var from=obj.current_page==null||obj.current_page==""||obj.current_page=="undefined"?0:Number((obj.current_page-1)*pagesize);
      applicantName=await this.getConvertSemiangleStr(applicantName);
       var reqUrl=this.paSearchUrl;
       var params =  {
          "query": {
              "bool": {
                  "must": [
                      {
                          "term": {
                              "applicant_name.raw": applicantName
                          }
                      },
                      {
                          "term": {
                              "pub_type":paType
                          }
                      }
                  ]
              }
          },
          "from": from,
          "size": pagesize,
          "_source": [
              "filing_name",
              "pub_status_now",
              "filing_no",
              "filing_date",
              "gr_date",
              "gr_no",
              "pub_date",
              "pub_no",
              "agency_name",
              "inventor_name",
              "main_ipc",
              "abstr_text",
              "pub_type"
          ],
          "sort": [
              {
                  "filing_date": "desc"
              }
          ]
      };
      return this.returnResult(params,reqUrl,opName,"paShortListByApplicantName");
    }

    /*查询某一个公司名下有多少条专利(pub_no:公开（公告）号-精确、gr_no:授权公布号-精确)
      auther:sy
      返回值：
        {
          "status": 0,
          "msg": "操作成功",
          "total": 2,
          "data": [
              {
              	 "filing_name":"",
              	 "pub_status_now":"",
      			 "filing_no":"",
              	 "filing_date":"",
              	 "gr_date":"",
              	 "gr_no":"",
              	 "pub_date":"",
              	 "pub_no":""
      			 "agency_name",
      			 "inventor_name",
      			 "main_ipc",
      			 "abstr_text",
      			 "pa_type":""
              }
          ],
          "bizmsg": "empty"
      }
      返回值说明:status为0则为成功，否则为查询有误
      	 "filing_name",发明名称
      	 "pub_status_now",法律状态
      	 "filing_no",申请号
      	 "filing_date",申请日期
      	 "gr_date",授权日期
      	 "gr_no",授权公布号
      	 "pub_date",公开（公告）日期
      	 "pub_no",公开（公告）号
      	 "agency_name",代理机构
      	 "inventor_name",发明人
      	 "main_ipc",主分类号
      	 "abstr_text",详情信息
      	 "pa_type",专利类型
           "total"						  总条数
      */
    async paDetails(obj,opName){
      var pubNo=obj.pub_no==null||obj.pub_no==""||obj.pub_no=="undefined"||obj.pub_no=="null"?"":obj.pub_no;
      var grNo=obj.gr_no==null||obj.gr_no==""||obj.gr_no=="undefined"||obj.gr_no=="null"?"":obj.gr_no;
      if(pubNo==""&&grNo==""){
        return System.getResult2(null,null,null,"参数不能为空");
      }
      var pagesize=obj.page_size==null||obj.page_size==""||obj.page_size=="undefined"?20:obj.page_size;
      if(pagesize>100){
        pagesize=20;
      }
      var from=obj.current_page==null||obj.current_page==""||obj.current_page=="undefined"?0:Number((obj.current_page-1)*pagesize);
       var reqUrl=this.paSearchUrl;
       var params =  {
           "query": {
             "bool": {
               "must": []
             }
           },
           "from": from,
           "size": pagesize,
           "_source": [
             "filing_name",
             "pub_status_now",
     		     "filing_no",
             "filing_date",
             "gr_date",
             "gr_no",
             "pub_date",
             "pub_no",
         		 "agency_name",
         		 "inventor_name",
         		 "main_ipc",
         		 "abstr_text",
         		 "pub_type"
           ],
           "sort": [
             {
               "filing_date": "desc"
             }
           ]
       };
       if(pubNo!=""){
         var param=  {
               "term": {
                 "pub_no": pubNo
               }
         }
         params.query.bool.must.push(param)
       }
       if(grNo!=""){
         var param=  {
               "term": {
                 "gr_no": grNo
               }
         }
         params.query.bool.must.push(param)
       }
      return this.returnResult(params,reqUrl,opName,"paDetails");
    }

    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);
      }
     return result;
    }

    async returnResult(params,reqUrl,opClassName,opMethod){
      var rc=System.getObject("util.execClient");
      var rtn=null;
      try{
        rtn=await rc.execPost(params,reqUrl);
        var j=JSON.parse(rtn.stdout);
        if(j.status!=undefined){
          //执行查询有错
          //日志记录
          logCtl.error({
             optitle:"ES查询专利信息opClassName="+opClassName+"，opMethod="+opMethod+"ES执行异常error",
             op:"base/service/impl/tmutilsSve.js",
             content:rtn.stdout,
             clientIp:""
           });
           return System.getResult2(null,null,null,"查询出错");
        }
        return System.getResult3(j.hits,null);
      }catch(e){
        //日志记录
        logCtl.error({
           optitle:"ES查询专利信息opClassName="+opClassName+"，opMethod="+opMethod+"操作异常异常error",
           op:"base/service/impl/tmutilsSve.js",
           content:e.stack,
           clientIp:""
         });
        return System.getResult2(null,null,null,"查询异常");
      }
    }

}
module.exports=UtilsIcService;
