var System = require("../../system");
var settings = require("../../../config/settings");
const ApiBase = require("../api.base");
//const cyjAppKey="ccb00829347e4048833af213e502c8c5";
class GsbTmSearchApi extends ApiBase {
  constructor() {
    super();
    this.xzCompanyUrl = settings.apiconfig.xzCompanySearchUrl(settings.env);
    this.xzAllCompanyUrl = settings.apiconfig.xzAllCompanySearchUrl(settings.env);
    this.xzDetailUrl = settings.apiconfig.xzDetailSearchUrl();
    this.byslTmUrl = settings.apiconfig.byslTmUrl();
    this.tmSearchUrl = settings.apiconfig.tmSearchUrl();
    this.tmFlowUrl = settings.apiconfig.tmFlowUrl();
    this.tmNclUrl = settings.apiconfig.tmNclUrl();
    this.yyDetailUrl = settings.apiconfig.yyDetailSearchUrl();
    this.nclUrl = settings.apiconfig.nclUrl();
    this.agencycompanySearchUrl = settings.apiconfig.agencycompanySearchUrl();
    this.utilstmSve = System.getObject("service.utilstmSve");
    this.phonesearch = System.getObject("api.phonesearch");
  };
  buildDate(date) {
    var date = new Date(date);
    var time = Date.parse(date);
    time = time / 1000;
    return time;
  };
  async xzSearch(obj) {//续展查询-ok
    var data = await this.checkKey(obj.appKey);
    var self = this;
    if (data && data.status && data.status == -1) {
      return data;
    }
    var type = obj.searchType;
    if (type == "" || type == null) {
      return System.getResult2(null, null);
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    var addr = obj.address == null ? "" : obj.address;
    if (obj.startDate == null || obj.startDate == "null") {
      var startTime = "";
    } else {
      var startTime = this.buildDate(obj.startDate);
    }
    if (obj.endDate == null || obj.endDate == "null") {
      var endTime = "";
    } else {
      var endTime = this.buildDate(obj.endDate);
    }
    var pagesize = obj.pageSize == null ? 15 : obj.pageSize;
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }

    var reqUrl = this.xzCompanyUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            //  {
            //   "exists": {
            //     "field": "tel_info"
            //  }
            // },
            {
              "term": {
                "tm_company_type": type
              }
            }
          ],
          "must_not": [
            {
              "wildcard": {
                "terms": "注销*"
              }
            },
            {
              "terms": {
                "status": [
                  "吊销,已注销",
                  "吊销后注销",
                  "吊销，已注销",
                  "已注销"
                ]
              }
            }
          ]
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "applicant_cn",
        "applicant_en",
        "applicant_cn_addr",
        "applicant_en_addr",
        "tel_info",
        "email_info",
        "status"
      ],
      "sort": [
        {
          "tm_end_day_max": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };
    if (companyName != "" && companyName != null) {
      var param = {
        "wildcard": {
          "applicant_cn": "*" + companyName + "*"
        }
      };
      params.query.bool.must.push(param);
    }
    if (addr != "" && addr != null) {
      var param = {
        "wildcard": {
          "applicant_cn_addr": "*" + addr + "*"
        }
      };
      params.query.bool.must.push(param);
    }
    if (startTime != "" && startTime != null) {
      var param = {
        "range": {
          "tm_end_day_max": {
            "gte": startTime
          }
        }
      };
      params.query.bool.must.push(param);
    }
    if (endTime != "" && endTime != null) {
      var param = {
        "range": {
          "tm_end_day_min": {
            "lt": endTime
          }
        }
      };
      params.query.bool.must.push(param);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      for (var i = 0; i < j.hits.hits.length; i++) {
        var c = j.hits.hits[i];
        if (c._source.applicant_cn) {
          var pobj = {
            appKey: obj.appKey,
            companyName: c._source.applicant_cn
          }
          var phones = await self.phonesearch.phoneNameSearch(pobj);
          if (phones.status == 0 && phones.data.list.length > 0) {
            c._source.tel_info = phones.data.list[0]._doc.phone_number;
            c._source.email_info = phones.data.list[0]._doc.email;
          }
        }
      }
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };
  async xzallSearch(obj) {//公司商机
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    var addr = obj.address == null ? "" : obj.address;
    var pagesize = obj.pageSize == null ? 15 : obj.pageSize;
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }
    var reqUrl = this.xzAllCompanyUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
          ],
          "must_not": [
            {
              "wildcard": {
                "terms": "注销*"
              }
            },
            {
              "terms": {
                "status": [
                  "吊销,已注销",
                  "吊销后注销",
                  "吊销，已注销",
                  "已注销"
                ]
              }
            }
          ]
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "applicant_cn",
        "applicant_cn_addr",
        "applicant_en",
        "applicant_en_addr",
        "reg_property",
        "reg_capital",
        "status",
        "total_num",
        "tm_company_types"
      ],
      "sort": [
        {
          "total_num": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };
    if (companyName != "" && companyName != null) {
      var param = {
        "wildcard": {
          "applicant_cn": "*" + companyName + "*"
        }
      };
      params.query.bool.must.push(param);
    }
    if (addr != "" && addr != null) {
      var param = {
        "wildcard": {
          "applicant_cn_addr": "*" + addr + "*"
        }
      };
      params.query.bool.must.push(param);
    }
    console.log(param);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async xzSearchDetail(obj) {//续展详情查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var type = obj.searchType;
    if (type == "" || type == null) {
      return System.getResult2(null, null);
    }
    if (obj.companyName == null && obj.companyName == "") {
      return System.getResult2(null, null);
    }
    var companyName = obj.companyName;
    if (obj.startDate == null) {
      var startTime = "";
    } else {
      var startTime = this.buildDate(obj.startDate);
    }
    if (obj.endDate == null) {
      var endTime = "";
    } else {
      var endTime = this.buildDate(obj.endDate);
    }
    var reqUrl = this.xzDetailUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "renewals_type": type
              }
            },
            {
              "term": {
                "applicant_cn": companyName
              }
            }
          ]
        }
      },
      "from": 0,
      "size": 500,
      "_source": [
        "ncl_one_codes",
        "tm_regist_num",
        "tm_name",
        "applicant_cn",
        "applicant_cn_addr",
        "tm_end_day",
        "tm_agency"
      ],
      "sort": [
        {
          "tm_end_day": "desc"
        }
      ]
    };
    if (startTime != "" || endTime != "") {
      var param = {
        "range": {
          "busness_day": {
          }
        }
      };
      if (startTime != "") {
        param.range.busness_day["gte"] = startTime;
      }
      if (endTime != "") {
        param.range.busness_day["lt"] = endTime;
      }
      params.query.bool.must.push(param);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async yySearchDetail(obj) {//异议详情查询-???
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    if (obj.companyName == null && obj.companyName == "") {
      return System.getResult2(null, null);
    }
    var companyName = obj.companyName;
    if (obj.startDate == null) {
      var startTime = "";
    } else {
      var startTime = this.buildDate(obj.startDate);
    }
    if (obj.endDate == null) {
      var endTime = "";
    } else {
      var endTime = this.buildDate(obj.endDate);
    }

    var reqUrl = this.yyDetailUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "registrant_name": companyName
              }
            }
          ]
        }
      },
      "from": 0,
      "size": 500,
      "_source": [
        "tm_regist_num",
        "tm_name",
        "registrant_name",
        "registrant_addr",
        "first_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "tm_agency"
      ],
      "sort": [
        {
          "first_notice_day": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };
    if (startTime != "" || endTime != "") {
      var param = {
        "range": {
          "first_notice_day": {
          }
        }
      };
      if (startTime != "") {
        param.range.first_notice_day["gte"] = startTime;
      }
      if (endTime != "") {
        param.range.first_notice_day["lt"] = endTime;
      }
      params.query.bool.must.push(param);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };
  async byslSearch(obj) {//不予受理查询-???
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    var pagesize = obj.pageSize == null ? 15 : obj.pageSize;
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }
    var reqUrl = this.byslTmUrl;
    var params = {
      "query": {
        "match_all": {}
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "registrant_name",
        "tm_regist_num",
        "no_accepted_day",
        "no_accepted_notice_issue",
        "no_accepted_notice_page_num",
        "link_url",
        "registrant_addr"
      ],
      "sort": [
        {
          "no_accepted_day": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };
    if (companyName != null && companyName != "") {
      params.query = {
        "bool": {
          "must": [
            {
              "wildcard": {
                "registrant_name": "*" + companyName + "*"
              }
            }
          ]
        }
      };
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };
  async byslDetail(obj) {//不予受理详情查询-???
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    if (obj.companyName == null && obj.companyName == "") {
      return System.getResult2(null, null);
    }
    var companyName = obj.companyName;

    var reqUrl = this.byslDetailUrl;
    var params = {
      "query": {
        "term": {
          "registrant_name": companyName
        }
      },
      "from": 0,
      "size": 500,
      "_source": [
        "registrant_name",
        "tm_regist_num",
        "no_accepted_day",
        "no_accepted_notice_issue",
        "no_accepted_notice_page_num",
        "link_url"
      ],
      "sort": [
        {
          "no_accepted_day": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };
    if (companyName != null && companyName != "") {
      params.query = {
        "bool": {
          "must": [
            {
              "wildcard": {
                "registrant_name": "*" + companyName + "*"
              }
            }
          ]
        }
      };
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmSearch(obj) {//商标查询-ok
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var param = {
      tm_name: obj.tmName,
      reg_num: obj.regNum,
      applicant_cn: obj.applicantCn,
      page_size: obj.pageSize,
      current_page: obj.currentPage
    }
    return this.utilstmSve.tmSearch(param, "GsbTmSearchApi");
  };

  async tmAccurateSearch(obj) {//根据商标名称进行精准查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    if (tmName == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };

    if (tmName != null && tmName != "") {
      var param = {
        "match": {
          "tm_name.raw": tmName
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };
  async tmAccurateJuheSearch(obj) {//根据商标名称精准查询，对查询结果进行类别聚合
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;

    if (tmName == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "term": {
              "tm_name.raw": tmName
            }
          }
        }
      },
      "aggregations": {
        "ncl_one_codes_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45,
          }
        }
      }
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResultjuhe4(j, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmNameSearch(obj) {//根据商标名称模糊查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    if (tmName == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };

    if (tmName != null && tmName != "") {
      var param = {
        "match": {
          "tm_name": tmName
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmNamejuheSearch(obj) {//根据商标名称模糊查询，对查询结果进行类别聚合
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;

    if (tmName == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "match": {
              "tm_name": tmName
            }
          }
        }
      },
      "aggregations": {
        "ncl_one_codes_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45,
          }
        }
      }
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResultjuhe4(j, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmzchSearch(obj) {//根据商标商标号精准查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var regNum = obj.regNum == null ? "" : obj.regNum;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    if (regNum == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };

    if (regNum != "" && regNum != null) {
      var param = {
        "regexp": {
          "tm_regist_num": "[TG]{0,1}" + regNum
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmzchjuheSearch(obj) {//根据商标商标号精准查询，对查询结果进行类别聚合
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var regNum = obj.regNum == null ? "" : obj.regNum;

    if (regNum == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "regexp": {
              "tm_regist_num": "[TG]{0,1}" + regNum
            }
          }
        }
      },
      "aggregations": {
        "ncl_one_codes_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45,
          }
        }
      }
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResultjuhe4(j, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmzcrSearch(obj) {//根据商标注册人模糊查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var applier = obj.applier == null ? "" : obj.applier;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    if (applier == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };

    if (applier != "" && applier != null) {
      var param = {
        "wildcard": {
          "applicant_cn": "*" + applier + "*"
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmzcrjuheSearch(obj) {//根据商标注册人模糊查询，对查询结果进行类别聚合
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var applier = obj.applier == null ? "" : obj.applier;

    if (applier == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "wildcard": {
              "applicant_cn": "*" + applier + "*"
            }
          }
        }
      },
      "aggregations": {
        "ncl_one_codes_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45,
          }
        }
      }
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResultjuhe4(j, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async tmSearchByRegNum(obj) {//商标查询(多注册号)-ok
    var reqUrl = this.tmSearchUrl;
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    if (obj.regNums == null || obj.regNums.length < 1) {
      return System.getResult2(null, null);
    }
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    var regNums = obj.regNums == null ? "" : obj.regNums;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "ncl_one_codes"
              }
            },
            {
              "terms": {
                "tm_regist_num": regNums
              }
            }
          ]
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
      "sort": [
        {
          "apply_day": "desc"
        },
        {
          "_id": "asc"
        }
      ]
    };

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };

  async getTmFlow(obj) {//商标流程
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var param = {
      reg_num: obj.regNum
    }
    return this.utilstmSve.getTmFlow(param, "GsbTmSearchApi");
  }

  async getTmNclSmallCodes(obj) {//商标小类
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var param = {
      reg_num: obj.regNum,
      nclone_code: obj.nclOneCode
    }
    return this.utilstmSve.getTmNclSmallCodes(param, "GsbTmSearchApi");
  }

  async getNcl(obj) {//尼斯数据
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var nclcode = obj.nclcode == null ? "" : obj.nclcode;
    var level = obj.level == null ? "" : obj.level;
    var nclcodelist = obj.nclcodelist || null;
    var reqUrl = this.nclUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": 0,
      "size": 2000,
      "_source": [
        "pid",
        "level",
        "code",
        "name"
      ],
      "sort": [
        {
          "code": "asc"
        }
      ]
    };
    if (nclcode != null && nclcode != "") {
      var param = {
        "term": {
          "pid": nclcode
        }
      }
      params.query.bool.must.push(param)
    }
    if (level != null && level != "" && level != 'undefined') {
      var param = {
        "term": {
          "level": level
        }
      }
      params.query.bool.must.push(param)
    }
    if (nclcodelist != null) {
      var param = {
        "terms": {
          "code": nclcodelist
        }
      }
      params.query.bool.must.push(param)
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(JSON.parse(rtn.stdout).hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  };
  async getNclByLikeName_new(obj) {//尼斯数据
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var ncls = obj.ncls || null;
    var name = obj.name;
    var reqUrl = this.nclUrl;
    var params = {
      "query": {
        "bool": {
          "should": []
        }
      },
      "from": 0,
      "size": 2000,
      "_source": [
        "pid",
        "level",
        "code",
        "name",
        "belong_to_onecode"
      ],
      "sort": [
        {
          "belong_to_onecode": "asc"
        },
        {
          "code": "asc"
        }
      ]
    };
    if (name != null && name != "") {
      var param1 = {
        "bool": {
          "must": [
            {
              "term": {
                "level": 3
              }
            },
            {
              "query_string": {
                "default_field": "name.raw",
                "query": "*" + name + "*"
              }
            }
          ]
        }
      };
      var param2 = {
        "bool": {
          "must": [
            {
              "term": {
                "level": 3
              }
            },
            {
              "query_string": {
                "default_field": "code",
                "query": "*" + name + "*"
              }              
            }
          ]
        }
      };
      if (ncls && ncls.length > 0) {
        param1.bool.must.push({
          "terms": {
            "belong_to_onecode": ncls
          }
        });
        param2.bool.must.push({
          "terms": {
            "belong_to_onecode": ncls
          }
        });
      }
      params.query.bool.should.push(param1);
      params.query.bool.should.push(param2);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      var tmpNclList = System.getResult3(j.hits, null);

      var threeNclList = tmpNclList.data;

      if (threeNclList == null || threeNclList.length <= 0) {
        return System.getResult3(j.hits, null, "数据为空");
      }
      var oneMapNcl = {};
      var twoMapNcl = {};
      var nclCodeList = [];
      //数据
      var oneNclList = [];
      for (let index = 0; index < threeNclList.length; index++) {
        const element = threeNclList[index];
        var tmpTwoNclItem = {//二级
          code: element.pid,
          name: "",
          pcode: element.belong_to_onecode,
          type: 1,
          children: []
        };
        var tmpThreeNclItem = {//三级
          code: element.code,
          name: element.name,
          pcode: element.pid
        };
        if (!twoMapNcl[element.pid]) {
          twoMapNcl[element.pid] = element.pid;
          nclCodeList.push(element.pid);
        }//不存在二级
        if (!oneMapNcl[element.belong_to_onecode]) {
          oneMapNcl[element.belong_to_onecode] = element.belong_to_onecode;
          nclCodeList.push(element.belong_to_onecode);

          tmpTwoNclItem.children.push(tmpThreeNclItem);
          var tmponeNclItem = {
            code: element.belong_to_onecode,
            name: "",
            pcode: "",
            type: 1,
            children: [tmpTwoNclItem]
          };
          oneNclList.push(tmponeNclItem);
        } //不存在一级
        else {
          for (let j = 0; j < oneNclList.length; j++) {
            const jItem = oneNclList[j];
            if (jItem.code == element.belong_to_onecode) {
              var twoCount = 0;
              for (let k = 0; k < jItem.children.length; k++) {
                const kItem = jItem.children[k];
                if (kItem.code == element.pid) {
                  oneNclList[j].children[k].children.push(tmpThreeNclItem);
                  twoCount++;
                  break;
                }//处理存在二级
              }
              if (twoCount == 0) {
                tmpTwoNclItem.children.push(tmpThreeNclItem);
                oneNclList[j].children.push(tmpTwoNclItem);
              }//处理不存在二级
              break;
            }//处理存在的一级
          }
        }//存在一级
      }
      //尼斯大类处理
      var tmpNclList = await this.getNcl({ nclcodelist: nclCodeList, appKey: obj.appKey });
      var getNclList = tmpNclList.data;
      if (getNclList == null || getNclList.length <= 0) {
        return System.getResult3(j.hits, null, "大类二类数据为空");
      }
      var self = this;
      for (let i = 0; i < oneNclList.length; i++) {
        const element = oneNclList[i];
        var tOneNameItem = getNclList.filter(f => f.code == element.code);
        if (tOneNameItem && tOneNameItem.length > 0) {
          oneNclList[i].name = tOneNameItem[0].name;
        }
        element.children.sort(self.keysort('code', false));
        for (let n = 0; n < element.children.length; n++) {
          const nItem = element.children[n];
          var tTwoNameItem = getNclList.filter(f => f.code == nItem.code);
          if (tTwoNameItem && tTwoNameItem.length > 0) {
            oneNclList[i].children[n].name = tTwoNameItem[0].name;
            //处理三级排序 
            var yesCodeList = [];
            var noCodeList = [];
            for (let l = 0; l < nItem.children.length; l++) {
              const lItem = nItem.children[l];
              if (!lItem.code || lItem.code == "undefined") {
                noCodeList.push(lItem);
              } else {
                yesCodeList.push(lItem);
              }
            }//三级排序   
            if (noCodeList.length > 0) {
              yesCodeList.push.apply(yesCodeList, noCodeList);
            }
            oneNclList[i].children[n].children = yesCodeList;
          }
        }//处理二级name       
      }
      return System.getResult2(oneNclList, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "尼斯数据查询异常==error",
        op: "base/api/impl/gsbtmsearch/getNclByLikeName_new",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  }
  /**
   * 排序有倒序 对数组中的对象，按对象的key进行sortType排序
   * @param key 数组中的对象为object,按object中的key进行排序
   * @param sortType true为降序；false为升序
   */
  keysort(key, sortType) {
    return function (a, b) {
      return sortType ? ~~(a[key] < b[key]) : ~~(a[key] > b[key]);
    }
  }
  async getNclByLikeName(obj) {//尼斯数据
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var ncls = obj.ncls || null;
    var name = obj.name;
    var reqUrl = this.nclUrl;
    var params = {
      "query": {
        "bool": {
          "should": []
        }
      },
      "from": 0,
      "size": 2000,
      "_source": [
        "pid",
        "level",
        "code",
        "name"
      ],
      "sort": [
        {
          "code": "desc"
        }
      ]
    };
    if (name != null && name != "") {
      var param1 = {
        "bool": {
          "must": [
            {
              "term": {
                "level": 3
              }
            },
            {
              "query_string": {
                "default_field": "name.raw",
                "query": "*" + name + "*"
              }
            }
          ]
        }
      };
      var param2 = {
        "bool": {
          "must": [
            {
              "term": {
                "level": 3
              }
            },
            {
              "term": {
                "code": name
              }
            }
          ]
        }
      };
      if (ncls && ncls.length > 0) {
        param1.bool.must.push({
          "terms": {
            "belong_to_onecode": ncls
          }
        });
        param2.bool.must.push({
          "terms": {
            "belong_to_onecode": ncls
          }
        });
      }
      params.query.bool.should.push(param1);
      params.query.bool.should.push(param2);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      var tmpNclList = System.getResult3(j.hits, null);

      var threeNclList = tmpNclList.data;

      if (threeNclList == null || threeNclList.length <= 0) {
        return System.getResult3(j.hits, null, "数据为空");
      }
      //尼斯大类处理
      var tmpGetOneNclList = await this.getNcl({ level: 1, appKey: obj.appKey });
      var getOneNclList = tmpGetOneNclList.data;
      if (getOneNclList == null || getOneNclList.length <= 0) {
        return System.getResult3(j.hits, null, "大类数据为空");
      }
      //尼斯二级类处理
      var tmpGetTwoNclList = await this.getNcl({ level: 2, appKey: obj.appKey });
      var getTwoNclList = tmpGetTwoNclList.data;
      if (getTwoNclList == null || getTwoNclList.length <= 0) {
        return System.getResult3(j.hits, null, "二类数据为空");
      }

      var oneNclList = [];
      var twoNclList = [];
      var newThreeNclList = [];

      for (let i = 0; i < threeNclList.length; i++) {
        var threeNcl = threeNclList[i];
        if (threeNcl != null) {
          var tmpTwoNclFind = tmpTwoNclFind = getTwoNclList.find(f => (f.code == threeNcl.pid));
          if (tmpTwoNclFind != null) {
            //组建新的小类结构
            var tnewThreeNclItem = {
              code: threeNcl.code, name: threeNcl.name, pcode: threeNcl.pid
            };
            newThreeNclList.push(tnewThreeNclItem);

            var tmpOneNclFind = getOneNclList.find(f => (f.code == tmpTwoNclFind.pid));
            //赋值大类、二类数据
            if (tmpOneNclFind != null) {
              var oneNcli = await oneNclList.findIndex(function (value, index, arr) {
                return value.code == tmpOneNclFind.code;
              });
              if (oneNcli < 0) {
                oneNclList.push(tmpOneNclFind);
              }
              var twoNcli = await twoNclList.findIndex(function (value, index, arr) {
                return value.code == tmpTwoNclFind.code;
              });
              if (twoNcli < 0) {
                twoNclList.push(tmpTwoNclFind);
              }
            }
          }
        }
      }
      if (oneNclList.length <= 0) {
        return System.getResult3(j.hits, null, "遍历三类后大类数据为空");
      }
      if (twoNclList.length <= 0) {
        return System.getResult3(j.hits, null, "遍历三类后二类数据为空");
      }

      oneNclList.sort(function (s1, s2) {
        if (s1.code > s2.code) {
          return 1
        } else {
          return -1
        }
      })

      var result = [];
      for (let k = 0; k < oneNclList.length; k++) {
        var tOneItem = oneNclList[k];
        if (tOneItem != null) {
          var tParam = {
            code: tOneItem.code,
            name: tOneItem.name,
            pcode: tOneItem.pid,
            children: await this.setChildren(tOneItem.code, twoNclList, newThreeNclList)
          };
          result.push(tParam);
        }
      }
      return System.getResult2(result, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  }

  async setChildren(oneCode, twoNclList, newThreeNclList) {
    //遍历大类下的有数据的二类
    var tmpTwoNclList = twoNclList.filter(function (item) {
      return item.pid == oneCode;
    });
    if (tmpTwoNclList.length <= 0) {
      return null;
    }
    var tmpParams = [];
    for (var i = 0; i < tmpTwoNclList.length; i++) {
      var tmpOneItem = tmpTwoNclList[i];
      if (tmpOneItem != null) {
        var param = {
          code: tmpOneItem.code,
          name: tmpOneItem.name,
          pcode: tmpOneItem.pid,
          children: newThreeNclList.filter(function (item) {
            return item.pcode == tmpOneItem.code;
          })
        };
        tmpParams.push(param);
      }
    }
    return tmpParams;
  }
  async imagesearch(obj) {//图像检索结果进行查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmRegistNum = obj.tmRegistNum == null ? "" : obj.tmRegistNum;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    if (tmRegistNum == "" && tmRegistNum == null) {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };
    if (tmRegistNum != "" && tmRegistNum != null) {
      var param = {
        "term": {
          "tm_regist_num": tmRegistNum
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }

    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  }
  async imagesearchbycode(obj) {//图像检索结果进行分类查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmRegistNumsAll = obj.tmRegistNumsAll == null ? "" : obj.tmRegistNumsAll;
    var sqlbtabkey = obj.sqlbtabkey == null ? "" : obj.sqlbtabkey;
    var pagesize = obj.pagesize == null ? 15 : obj.pagesize;
    if (obj.page == null) {
      var from = 0;
    } else {
      var from = Number((obj.page - 1) * obj.pagesize);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };
    if (tmRegistNumsAll.length > 0 && tmRegistNumsAll != null) {
      var param = {
        "terms": {
          "tm_regist_num": tmRegistNumsAll
        }
      }
      params.query.bool.must.push(param)
    }
    if (sqlbtabkey != "" && sqlbtabkey != null) {
      var param = {
        "term": {
          "ncl_one_codes": sqlbtabkey
        }
      }
      params.query.bool.must.push(param)
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  }

  async imagesearchjuhe(obj) {//图像检索结果进行聚合
    // var data=await this.checkKey(obj.appKey);
    // if(data && data.status && data.status==-1){
    //   return data;
    // }
    var tmRegistNumsAll = obj.tmRegistNumsAll == null ? "" : obj.tmRegistNumsAll;
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "terms": {
              "tm_regist_num": tmRegistNumsAll
            }
          }
        }
      },
      "aggregations": {
        "ncl_one_codes_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45,
          }
        }
      }
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResultjuhe4(j, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }


  }
  async fqImageSearch(obj) {
    var tmRegistNum = obj.tmRegistNum == null ? "" : obj.tmRegistNum;
    if (tmRegistNum == "" || tmRegistNum == null) {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": {
            "term": {
              "tm_regist_num": tmRegistNum
            }
          }
        }
      },
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "first_notice_day",
        "original_regist_notice_day",
        "first_notice_issue",
        "first_notice_page_num",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "tm_agency",
        "pic_url"
      ],
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  }
  async getAgencyName(obj) {//代理机构名称查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    companyName = await this.getConvertSemiangleStr(companyName);
    var pageSize = obj.pageSize == null ? 15 : obj.pageSize;
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }
    var reqUrl = this.agencycompanySearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": [

            {
              "term": {
                "company_name": companyName
              }
            }
          ]
        }
      },
      "from": from,
      "size": pageSize,
      "_source": [
        "company_name"
      ]
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      return System.getResult3(j.hits, null);
    } catch (e) {
      return rtn = System.getResult2(null, null);
    }
  }

  async getConvertSemiangleStr(str) {
    var result = "";
    str = str.replace(/\s+/g, "");
    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;
  };
}
module.exports = GsbTmSearchApi;
// var capi=new GsbTmSearchApi();
// capi.xzSearch({}).then(function(result){
//   console.log((result));
// }).catch(function(e){
//   console.log(e);
// });
