var System = require("../../system");
var settings = require("../../../config/settings");
const ApiBase = require("../api.base");
var moment = require('moment');
const logCtl = System.getObject("web.oplogCtl");
// const uuidv4 = require('uuid/v4');
class ByTmMonit extends ApiBase {
  constructor() {
    super();
    this.reqTimeOut = 60000;
    this.tmSearchUrl = settings.apiconfig.tmSearchUrl();
    this.gsbicsearch = System.getObject("api.gsbicsearch");
    this.dynamicsTmSearchUrl = settings.reqEsAddr() + "bigdata_middle_gsb_tm_info_dynamics/_search";;
    this.tm_status = { 1: "申请中", 2: "已初审", 3: "已注册", 4: "已无效", 5: "其他" };
  }
  /**
    * 排序有倒序 对数组中的对象，按对象的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]);
    }
  }
  convertDate(time) {
    if (time == null) {
      return "";
    }
    var date = new Date(Number(time * 1000));
    var y = 1900 + date.getYear();
    var m = "0" + (date.getMonth() + 1);
    var d = "0" + date.getDate();
    return y + "-" + m.substring(m.length - 2, m.length) + "-" + d.substring(d.length - 2, d.length);
  }
  //获取截止期限时间
  /*
    total_type:统计类型,-1为全部，1为可无效、2为可撤三、3可续展、4可宽展、5可异议
  */
  getProcessTime(tItem, total_type) {
    if (total_type == -1) {
      return "---";
    }
    else if (total_type == 1) {
      if (tItem.regist_notice_day) {
        var dStr = this.convertDate(tItem.regist_notice_day);
        return moment(dStr).add(5, "years").format("YYYY-MM-DD");
      } else {
        return "---";
      }
    }
    else if (total_type == 2) {
      return "---";
    }
    else if (total_type == 3) {
      return this.convertDate(tItem.tm_end_day);
    }
    else if (total_type == 4) {
      if (tItem.tm_end_day) {
        var dStr = this.convertDate(tItem.tm_end_day);
        return moment(dStr).add(6, "months").format("YYYY-MM-DD");
      } else {
        return "---";
      }
    }
    else if (total_type == 5) {
      if (tItem.first_notice_day) {
        var dStr = this.convertDate(tItem.first_notice_day);
        return moment(dStr).add(3, "months").format("YYYY-MM-DD");
      } else {
        return "---";
      }
    }
    else {
      return "---";
    }
  }
  async getTmNameStr(tmName, nameType) {//获取商标名称查询

    // console.log(typeof(nameType),"..........nameType?????????????????????????????????????????");
    // console.log(nameType,"......nameType????????value?????????????????????????????????");
    tmName = await this.getConvertSemiangleStr(tmName);

    var tiiaojianparams = {
      "bool": {
        "should": []
      }
    };
    if (nameType == "1" || nameType == "3") {
      tiiaojianparams.bool.should.push({
        "term": {
          "tm_name.raw": tmName
        }
      });
      tiiaojianparams.bool.should.push({
        "term": {
          "tm_name.raw": tmName.split('').reverse().join('')
        }
      });
    }
    if (nameType == "2" || nameType == "3") {
      if (tmName && tmName != "undefined") {
        var len = 0;
        for (var i = 0; i < tmName.length; i++) {
          var a = tmName.charAt(i);
          if (a.match(/[^\x00-\xff]/ig) != null) {
            len += 1;
          }
        }
        if (len <= 2) {
          tiiaojianparams.bool.should.push({
            "bool": {
              "must": [
                {
                  "match": {
                    "tm_name_standard": {
                      "query": tmName,
                      "minimum_should_match": "100%"
                    }
                  }
                },
                {
                  "range": {
                    "cn_count": {
                      "lte": len + 2
                    }
                  }
                }
              ]
            }
          });
          tiiaojianparams.bool.should.push({
            "bool": {
              "must": [
                {
                  "query_string": {
                    "default_field": "tm_name",
                    "query": "\"" + tmName.split('').reverse().join('') + "\""
                  }
                }, {
                  "range": {
                    "cn_count": {
                      "lte": len + 2
                    }
                  }
                }
              ]
            }
          });
        } else if (len == 3) {
          tiiaojianparams.bool.should.push({
            "bool": {
              "must": [
                {
                  "match": {
                    "tm_name_standard": {
                      "query": tmName,
                      "minimum_should_match": "75%"
                    }
                  }
                },
                {
                  "range": {
                    "cn_count": {
                      "lte": len + 1
                    }
                  }
                }
              ]
            }
          });
        } else if (len == 4) {
          tiiaojianparams.bool.should.push({
            "bool": {
              "must": [
                {
                  "match": {
                    "tm_name_standard": {
                      "query": tmName,
                      "minimum_should_match": "70%"
                    }
                  }
                },
                {
                  "range": {
                    "cn_count": {
                      "lte": len + 1
                    }
                  }
                }
              ]
            }
          });
        } else {
          tiiaojianparams.bool.should.push({
            "bool": {
              "must": [
                {
                  "match": {
                    "tm_name_standard": {
                      "query": tmName,
                      "minimum_should_match": "50%"
                    }
                  }
                },
                {
                  "range": {
                    "cn_count": {
                      "lte": len + 1
                    }
                  }
                }
              ]
            }
          });
        }
      }
    }
    return tiiaojianparams;
  }
  //获取聚合数据
  /*
   返回list:[{name,value}]
  */
  async getEggsInfo(params, reqUrl) {
    var rc = System.getObject("util.execClient");
    var rtn = null;
    var tList = [];
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      if (j.status != undefined) {
        //执行查询有错
        //日志记录
        logCtl.error({
          optitle: "ES查询商标数量ogetEggsInfo异常error",
          op: "base/api/impl/bytmmonit.js",
          content: rtn.stdout,
          clientIp: ""
        });
        return tList = [];
      }
      var letCount = j.aggregations.group_by_count.buckets.length;
      tList.push({
        name: "全部",
        value: -1
      });
      if (letCount > 0) {
        for (let i = 0; i < letCount; i++) {
          var item = j.aggregations.group_by_count.buckets[i];
          if (item) {
            tList.push({
              // name:item.key+""+"("+item.doc_count+")",
              name: item.key,
              value: parseInt(item.key)
            });
          }
        }
      }
      return tList;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "ES查询专利数量opClassName=utilspaSve，opMethod=paCountByApplicantName，异常error",
        op: "base/service/impl/utilspaSve.js",
        content: e.stack,
        clientIp: ""
      });
      return tList = [];
    }
  }
  //返回查询统计数量
  async getTmMonitCount(obj, reqUrl) {//获取商标监控长度
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return 0;
    }
    var params = await this.getWhereInfo(obj, 0);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      // console.log("resultData--------------------------------------------------.");
      // console.log(resultData);
      return resultData.hits.total;
    } catch (e) {
      console.log("error:::::");
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "XX商标监控统计数量",
        op: "base/api/impl/bytmmonit/getTmMonitCount",
        content: e.stack,
        clientIp: ""
      });
      return 0;
    }
  }
  //返回查询列表
  async getTmMonitList(obj) {//获取商标监控列表
    // console.log("obj...................................getlist......................");
    // console.log(obj);
    var result = {
      code: 1,
      message: "success",
      data: []
    };
    var isVerify = obj.isVerify || 1;
    if (isVerify == 1) {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = data.status;
        result.message = data.msg;
        return result;
      }
    }
    //请求类型,默认为1则请求商标es，2为请求商标动态监控es
    var reqType = 1;
    if (obj.req_type != null && obj.req_type != "" && obj.req_type != "undefined") {
      reqType = obj.req_type;
    }
    var reqUrl = reqType == 2 ? this.dynamicsTmSearchUrl : this.tmSearchUrl;
    var params = await this.getWhereInfo(obj, 1);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      // console.log("params....................................getTmMonitList......................");
      // console.log(params);
      rtn = await rc.execPost(params, reqUrl);
      // console.log("rtn...........................");
      // console.log(rtn);
      var resultData = JSON.parse(rtn.stdout);
      var tResult = System.getResult3(resultData.hits, null);
      // console.log("tResult....................getTmMonitList...............");
      // console.log(tResult);
      var addList = [];
      var self = this;
      if (tResult.status == 0 && tResult.data && tResult.data.length > 0) {
        for (var i = 0; i < tResult.data.length; i++) {
          var tItem = tResult.data[i];
          if (tItem) {
            var tmpProcess_time = self.getProcessTime(tItem, obj.total_type);
            var addItem = {
              pic_url: tItem.pic_url,
              tm_name: tItem.tm_name,
              tm_regist_num: tItem.tm_regist_num,
              ncl_one_codes: tItem.ncl_one_codes,
              apply_day: self.convertDate(tItem.apply_day),//申请日期
              status: self.tm_status[tItem.status],//商标状态
              applicant_cn: tItem.applicant_cn,
              process_time: tmpProcess_time == "---" ? tmpProcess_time : "截至" + "" + tmpProcess_time,
              process_time_info: tmpProcess_time == "---" ? "" : tmpProcess_time,
              is_shadow: 0//是否阴影，1是，0否
            }
            addList.push(addItem);
          }
        }
      }
      result.data = addList;
      //可显示的最大条数
      let totalNum = 1000;
      //可无效条数
      obj.total_type = 1;
      var kwx_total = await this.getTmMonitCount(obj, reqUrl);
      //可撤三条数
      obj.total_type = 2;
      var kcs_total = await this.getTmMonitCount(obj, reqUrl);
      //可续展条数
      obj.total_type = 3;
      var kxz_total = await this.getTmMonitCount(obj, reqUrl);
      //可宽展条数
      obj.total_type = 4;
      var kkz_total = await this.getTmMonitCount(obj, reqUrl);
      //可异议条数
      obj.total_type = 5;
      var kyy_total = await this.getTmMonitCount(obj, reqUrl);

      result.kwx_total = kwx_total > totalNum ? totalNum : kwx_total;
      result.kcs_total = kcs_total > totalNum ? totalNum : kcs_total;
      result.kxz_total = kxz_total > totalNum ? totalNum : kxz_total;
      result.kkz_total = kkz_total > totalNum ? totalNum : kkz_total;
      result.kyy_total = kyy_total > totalNum ? totalNum : kyy_total;
      result.name = obj.monit_name;
      result.total_count = tResult.total > 1000 ? 1000 : tResult.total;
      //聚合结果
      params.aggs = {
        "group_by_count": {
          "terms": {
            "field": "apply_year",
            "size": 30
          }
        }
      };
      var tmpYearParams = params;
      tmpYearParams.query.bool.must.push({
        "range": {
          "apply_year": {
            "gt": 0
          }
        }
      });
      var tapply_yearList = await this.getEggsInfo(tmpYearParams, reqUrl);
      //排序规则：倒序正序，<倒序，>正序
      var sortYearList = tapply_yearList.sort((a, b) => {
        if (a.value < b.value) {  // 可以改成其他key
          return 1
        } else {
          return -1
        }
      });
      // sortYearList.push({name:-1,value:"全部"});

      params.aggs = {
        "group_by_count": {
          "terms": {
            "field": "ncl_one_codes",
            "size": 45
          }
        }
      };
      var tncl_one_codesList = await this.getEggsInfo(params, reqUrl);
      var sortCodesList = tncl_one_codesList.sort((a, b) => {
        if (a.value > b.value) {  // 可以改成其他key
          return 1
        } else {
          return -1
        }
      });
      // sortCodesList.push({name:-1,value:"全部"});

      result.ncl_type = sortCodesList;
      result.year_list = sortYearList;
      // console.log("result...................................................???????????");
      // console.log(result);
      return result;
    } catch (e) {
      console.log(e.stack, "获取监控列表异常.....................");
      //日志记录
      logCtl.error({
        optitle: "XX商标监控列表搜索异常",
        op: "base/api/impl/bytmmonit/getTmMonitList",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "获取监控列表异常";
      return result;
    }
  }
  //返回短的查询列表
  async getShortTmMonitList(obj) {//获取短的商标监控列表
    // console.log("obj...................................getlist......................");
    // console.log(obj);
    var result = {
      code: 1,
      message: "success",
      data: []
    };
    var isVerify = obj.isVerify || 1;
    if (isVerify == 1) {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = data.status;
        result.message = data.msg;
        return result;
      }
    }
    //请求类型,默认为1则请求商标es，2为请求商标动态监控es
    var reqType = 1;
    if (obj.req_type != null && obj.req_type != "" && obj.req_type != "undefined") {
      reqType = obj.req_type;
    }
    var reqUrl = reqType == 2 ? this.dynamicsTmSearchUrl : this.tmSearchUrl;
    var params = await this.getWhereInfo(obj, 2);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      console.log("params.....................................getShortTmMonitList.................");
      console.log(params);
      rtn = await rc.execPost(params, reqUrl);
      // console.log("rtn.........................");
      // console.log(rtn);
      var resultData = JSON.parse(rtn.stdout);
      var tResult = System.getResult3(resultData.hits, null);
      // console.log("tResult....................getShortTmMonitList...........");
      // console.log(tResult);
      var addList = [];
      var self = this;
      if (tResult.status == 0 && tResult.data && tResult.data.length > 0) {
        var nowtime = new Date();
        for (var i = 0; i < tResult.data.length; i++) {
          var tItem = tResult.data[i];
          if (tItem) {
            var tmpProcess_time = self.getProcessTime(tItem, obj.total_type);
            var addItem = {
              apply_year: tItem.apply_year,//申请年份
              status: tItem.status,
              tm_regist_num: tItem.tm_regist_num,
              ncl_one_codes: tItem.ncl_one_codes,
              op_time: parseInt(nowtime.getTime() / 1000),
              process_time: tmpProcess_time == "---" ? "" : tmpProcess_time,
              is_shadow: 0//是否阴影，1是，0否
            }
            addList.push(addItem);
          }
        }
      }
      result.total_count = tResult.total;
      result.data = addList;
      // console.log("result...................................................???????????");
      // console.log(result);
      return result;
    } catch (e) {
      console.log(e.stack, "获取短的监控列表异常.....................");
      //日志记录
      logCtl.error({
        optitle: "XX商标监控短的列表搜索异常",
        op: "base/api/impl/bytmmonit/getShortTmMonitList",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "获取监控列表异常";
      return result;
    }
  }

  //获取查询条件
  /*
    参数：islist  --0统计条数、1为显示列表数据、2显示短的列表数据（只有注册号、大类）
  */
  async getWhereInfo(obj, islist) {
    var pagesize = obj.page_size == null ? 20 : obj.page_size;
    var from = obj.current_page == null ? 0 : Number((obj.current_page - 1) * obj.page_size);
    if (pagesize > 10000) {
      pagesize = 20;
    }
    // console.log(from, "from.............");
    // console.log(pagesize, "pagesize.................");

    var monitType = obj.monit_type || "";
    var tmName = obj.name || "";
    var nameType = obj.name_type || "";
    var nclType = obj.ncl_type || "";
    var tmRegistNum = obj.tm_regist_num || "";
    var applicantCn = obj.applicant_cn || "";
    var tmAgency = obj.tm_agency || "";
    //新加的条件
    //申请日期,-1为全部否则为选择对应的年份
    var apply_year = Number(obj.apply_year || "");
    //法律状态,-1为全部,1:申请中；2:已初审；3:已注册；4:已无效  5-其他
    var status = Number(obj.status || "");
    //类别,-1为全部否则为选择对应的大类
    var ncl_one_codes = obj.ncl_one_codes || "";
    //统计类型,-1为全部，1为可无效、2为可撤三、3可续展、4可宽展、5可异议、6新申请
    var total_type = Number(obj.total_type || "-1");

    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "size": 0
    };
    if (islist && islist == 1) {
      params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize,
        "_source": [
          "pic_url",
          "tm_name",
          "tm_regist_num",
          "ncl_one_codes",
          "apply_day",
          "first_notice_day",
          "regist_notice_day",
          "tm_end_day",
          "status",
          "applicant_cn"
        ]
      };
    }
    if (islist && islist == 2) {
      params = {
        "query": {
          "bool": {
            "must": []
          }
        },
        "from": from,
        "size": pagesize,
        "_source": [
          "apply_year",
          "status",
          "regist_notice_day",
          "tm_end_day",
          "first_notice_day",
          "tm_regist_num",
          "ncl_one_codes"
        ]
      };
    }
    if (monitType && monitType == 2) {
      if (tmAgency) {
        //代理机构监控
        var param = {
          "term": {
            "tm_agency": tmAgency
          }
        };
        params.query.bool.must.push(param);
      }
    }
    else {
      var tiiaojianparams = await this.getTmNameStr(tmName, nameType);
      if (tiiaojianparams.bool.should.length > 0) {
        params.query.bool.must.push(tiiaojianparams);
      }
      if (tmRegistNum && tmRegistNum != "undefined") {
        params.query.bool.must.push({
          "term": {
            "tm_regist_num": tmRegistNum
          }
        });
      }
      if (applicantCn && applicantCn != "undefined") {
        params.query.bool.must.push({
          "term": {
            "applicant_cn": applicantCn
          }
        });
      }
      if (!ncl_one_codes || ncl_one_codes == "undefined" || ncl_one_codes == "-1") {
        if (nclType && nclType != "undefined" && nclType.length > 0) {
          params.query.bool.must.push({
            "terms": {
              "ncl_one_codes": nclType
            }
          });
        }
      }
    }

    if (apply_year && apply_year != "undefined" && apply_year != -1) {
      params.query.bool.must.push({
        "term": {
          "apply_year": apply_year
        }
      });
    }
    //处理统计类型为6新申请的统计
    if (total_type && total_type != "undefined" && total_type != -1) {
      if (total_type == 6) {
        status = 1;
      }
    }
    if (status && status != "undefined" && status != -1) {
      params.query.bool.must.push({
        "term": {
          "status": status
        }
      });
    } else {
      params.query.bool.must.push({
        "terms": {
          "status": ["1", "2", "3"]
        }
      });
    }
    if (ncl_one_codes && ncl_one_codes != "undefined" && ncl_one_codes != "-1") {
      params.query.bool.must.push({
        "term": {
          "ncl_one_codes": ncl_one_codes
        }
      });
    }
    if (total_type && total_type != "undefined" && total_type != -1) {//total_type=1为可无效、2为可撤三、3可续展、4可宽展、5可异议、6新申请
      //total_type=1为可无效、2为可撤三、3可续展、4可宽展、5可异议
      var ctime = new Date();
      var nowtime = new Date();
      if (total_type == 1) {//1为可无效
        // ctime.setYear(-5);
        ctime.setFullYear(ctime.getFullYear() - 5);
        params.query.bool.must.push({
          "range": {
            "regist_notice_day": {
              "gte": parseInt(ctime.getTime() / 1000),
              "lte": parseInt(nowtime.getTime() / 1000)
            }
          }
        });
      }
      else if (total_type == 2) {//2为可撤三
        ctime.setFullYear(ctime.getFullYear() - 3);
        params.query.bool.must.push({
          "range": {
            "regist_notice_day": {
              "lte": parseInt(ctime.getTime() / 1000)
            }
          }
        });
      }
      else if (total_type == 3) {//3可续展
        ctime.setFullYear(ctime.getFullYear() + 1);
        params.query.bool.must.push({
          "range": {
            "tm_end_day": {
              "gte": parseInt(nowtime.getTime() / 1000),
              "lte": parseInt(ctime.getTime() / 1000)
            }
          }
        });
      }
      else if (total_type == 4) {//4可宽展
        var newCtime = moment().add(-6, "months").format("YYYY-MM-DD");
        params.query.bool.must.push({
          "range": {
            "tm_end_day": {
              "gte": parseInt(new Date(newCtime).getTime() / 1000),
              "lte": parseInt(nowtime.getTime() / 1000)
            }
          }
        });
      }
      else if (total_type == 5) {//5可异议
        var newCtime = moment().add(-3, "months").format("YYYY-MM-DD");
        params.query.bool.must.push({
          "range": {
            "first_notice_day": {
              "gte": parseInt(new Date(newCtime).getTime() / 1000),
              "lte": parseInt(nowtime.getTime() / 1000)
            }
          }
        });
      }
    }
    return params;
  }

  /*从db中获取的数据，进行跟es关联 */
  async getEsDataByDb(total_type, dbDataList) {
    var tm_regist_num_list = [];
    var ncl_one_codes_list = [];
    for (let index = 0; index < dbDataList.length; index++) {
      const element = dbDataList[index];
      if (element) {
        tm_regist_num_list.push(element.tm_regist_num);
        ncl_one_codes_list.push(element.ncl_one_codes);
      }
    }
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "terms": {
                "tm_regist_num": tm_regist_num_list
              }
            },
            {
              "terms": {
                "ncl_one_codes": ncl_one_codes_list
              }
            }
          ]
        }
      },
      "from": 0,
      "size": 300,
      "_source": [
        "pic_url",
        "tm_name",
        "tm_regist_num",
        "ncl_one_codes",
        "apply_day",
        "first_notice_day",
        "regist_notice_day",
        "tm_end_day",
        "status",
        "applicant_cn"
      ]
    };
    var reqUrl = this.tmSearchUrl;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      var tResult = System.getResult3(resultData.hits, null);
      var self = this;
      if (tResult.status == 0 && tResult.data && tResult.data.length > 0) {
        for (let i = 0; i < dbDataList.length; i++) {
          const item = dbDataList[i];
          if (item) {
            const esItem = tResult.data.filter(f => f.tm_regist_num == item.tm_regist_num && f.ncl_one_codes == item.ncl_one_codes);
            if (esItem && esItem.length > 0) {
              var tmpProcess_time = self.getProcessTime(esItem[0], total_type);
              dbDataList[i].pic_url = esItem[0].pic_url || "---";
              dbDataList[i].tm_name = esItem[0].tm_name || "---";
              dbDataList[i].apply_day = self.convertDate(esItem[0].apply_day) || "---";//申请日期
              dbDataList[i].applicant_cn = esItem[0].applicant_cn || "---";
              dbDataList[i].process_time = tmpProcess_time == "---" ? tmpProcess_time : "截至" + "" + tmpProcess_time;
            }
            else {
              dbDataList[i].pic_url = "---";
              dbDataList[i].tm_name = "---";
              dbDataList[i].apply_day = "---";//申请日期
              dbDataList[i].applicant_cn = "---";
              dbDataList[i].process_time = "---";
            }
          }
        }
      }
      return dbDataList;
    } catch (e) {
      console.log(e.stack, "XX商标监控列表从db中获取数据搜索异常.....................");
      //日志记录
      logCtl.error({
        optitle: "XX商标监控列表从db中获取数据搜索异常",
        op: "base/api/impl/bytmmonit/getEsDataByDb",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "XX商标监控列表从db中获取数据搜索异常";
      return result;
    }
  }
  //从db中获取的数据，返回es查询统计数量
  async getTmMonitCountByDb(total_type, obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return 0;
    }
    obj.total_type = total_type;
    var reqUrl = this.tmSearchUrl;
    var params = await this.getWhereInfo(obj, 0);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      // console.log("resultData--------------------------------------------------");
      // console.log(resultData);
      return resultData.hits.total;
    } catch (e) {
      console.log("error:::::");
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "从db中获取的数据，返回es查询统计数量",
        op: "base/api/impl/bytmmonit/getTmMonitCountByDb",
        content: e.stack,
        clientIp: ""
      });
      return 0;
    }
  }

  async agencygetsumsearch(obj) {
    var self = this;
    var isVerify = obj.isVerify || 1;
    if (isVerify == 1) {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        return { code: -100, msg: "appKey异常，请稍后再试", data: null };
      }
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    companyName = await this.getConvertSemiangleStr(companyName);
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }

    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "tm_agency": companyName
              }

            }
          ]
        }
      },
      "size": 0,
      "aggregations": {
        "applicant_cn_list": {
          "terms": {
            "field": "applicant_cn",
            "size": 201
          }
        }
      }
    };
    if (obj.type == 1) {
      var param = {
        "term": {
          "apply_year": 2019,
        }
      }
      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);
      var sources = [];
      var data = {
        "result": 1,
        "totalSize": j.aggregations.applicant_cn_list.buckets.length
      };
      var a = { code: 1, msg: "操作成功", data: data };
      return a;
    } catch (e) {
      return { code: -200, msg: "操作异常，请稍后再试", data: 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;
  };

  async agencygetsearch(obj) {
    var self = this;
    var isVerify = obj.isVerify || 1;
    if (isVerify == 1) {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        return { code: -100, msg: "appKey错误", data: null };
      }
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;
    companyName = await this.getConvertSemiangleStr(companyName);
    if (obj.currentPage == null) {
      var from = 0;
    } else {
      var from = Number((obj.currentPage - 1) * obj.pageSize);
    }

    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "tm_agency": companyName
              }

            }
          ]
        }
      },
      "size": 0,
      "aggregations": {
        "applicant_cn_list": {
          "terms": {
            "field": "applicant_cn",
            "size": 200
          }
        }
      }
    };
    if (obj.type > 0) {
      var param = {
        "term": {
          "apply_year": 2019,
        }
      }
      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);
      var sources = [];
      var companys = j.aggregations.applicant_cn_list.buckets;
      var data = {
        "result": 1,
        "totalSize": j.aggregations.applicant_cn_list.buckets.length,
        "list": sources
      };
      var cobj = {
        appKey: obj.appKey,
        companyNames: []
      };
      companys.forEach(a => {
        cobj.companyNames.push(a.key);
      });
      var companyNameinfos = await self.gsbicsearch.companymgetsearch(cobj);
      var companyinfos = companyNameinfos.data.list;
      for (var k = 0; k < companys.length; k++) {
        var companyname = companys[k].key;
        var nameindex = companyinfos.findIndex(f => f.name == companyname);
        if (nameindex < 0) {
          var source = {
            company_name: companyname,
            legal_person: "未公开",
            tel: "未公开",
            regtime: "未公开",
            regcapital: "未公开",
            tm_count: companys[k].doc_count,
            area: "未公开"
          }
        } else {
          var source = {
            company_name: companyinfos[nameindex].name,
            legal_person: companyinfos[nameindex].legalRepresentative,
            tel: companyinfos[nameindex].tel_info,
            regtime: companyinfos[nameindex].dateIssue,
            regcapital: companyinfos[nameindex].registeredCapital,
            tm_count: companys[k].doc_count,
            area: companyinfos[nameindex].businessAddress
          }
        }
        sources.push(source);
      }
      var a = { code: 1, msg: "操作成功", data: data };
      return a;
    } catch (e) {
      return { code: -200, msg: "操作异常，请稍后再试", data: 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 = ByTmMonit;
