var System = require("../../system");
var settings = require("../../../config/settings");
const ApiBase = require("../api.base");
const logCtl = System.getObject("web.oplogCtl");
// const uuidv4 = require('uuid/v4');
class FqTmSearchApi extends ApiBase {
  constructor() {
    super();
    this.reqTimeOut = 60000;
    this.esUrl = settings.reqEsAddr();
    this.tmZntjUrl = settings.apiconfig.tmZntjQueryUrl();
    this.tmtjdlQueryUrl = settings.apiconfig.tmtjdlQueryUrl();
    this.bgDetailSearchUrl = settings.apiconfig.bgDetailSearchUrl();
    this.tmSearchUrl = settings.apiconfig.tmSearchUrl();
    this.xzCompanyUrl = settings.apiconfig.xzCompanySearchUrl();
    this.xzDetailSearchUrl = settings.apiconfig.xzDetailSearchUrl();
    this.nclUrl = settings.apiconfig.nclUrl();
    this.utilstmSve = System.getObject("service.utilstmSve");
    this.GsbTmSearchApi = System.getObject("api.gsbtmsearch");
    this.imageQueryUrl = settings.apiconfig.imageQueryUrl();
    this.tm_type = { P: "普通商标", J: "集体商标", Z: "证明商标", T: "特殊商标" };
    this.tm_status = { 1: "有效", 2: "无效", 3: "待审", 4: "不定", 5: "未知状态" };
    this.phonesearch = System.getObject("api.phonesearch");
  };
  async getOneXz(obj) {
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    try {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = -100;
        result.message = "appKey参数错误"
        return result;
      }
      var req_key = obj.req_key || "fqTmXzData";
      //处理缓存
      var tbDataList = await this.cacheManager["FqTmDataCache"].getTmXzListByCache(req_key);
      if (tbDataList && tbDataList != "undefined" && tbDataList.length > 0) {
        var tmpResult = JSON.parse(tbDataList);
        if (tmpResult && tmpResult.length > 0) {
          //获取一个数据
          var oneItem = tmpResult[0];
          result.data = oneItem;
          //移除整个缓存
          if (tmpResult.length == 1) {
            this.cacheManager["FqTmDataCache"].delXzCache(req_key);
          }
          else {
            //移除单个数据
            tmpResult.splice(tmpResult.findIndex(v => v.companyname === oneItem.companyname), 1);
            //设置缓存
            var stringStr = JSON.stringify(tmpResult);
            await this.cacheManager["FqTmDataCache"].setTmXzList(req_key, stringStr);
          }
        }
      }
      else {
        result.message = "数据已用完";
      }
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "可续展的XX公司查询异常",
        op: "base/api/impl/fqtmsearch/getOneXz",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "查询异常"
      return result;
    }
  }

  async delXzCache(obj) {
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    try {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = -100;
        result.message = "appKey参数错误"
        return result;
      }
      if (obj.op != "stmXzDatas") {
        result.code = -100;
        result.message = "op参数错误"
        return result;
      }
      await this.cacheManager["FqTmDataCache"].delXzCache("fqTmXzData")
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "可续展的XX公司删除缓存异常",
        op: "base/api/impl/fqtmsearch/delXzCache",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "查询异常"
      return result;
    }
  }
  async setTmXzList(obj) {
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    try {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = -100;
        result.message = "appKey参数错误"
        return result;
      }
      if (obj.op != "stmXzDatas") {
        result.code = -100;
        result.message = "op参数错误"
        return result;
      }
      var tmXzList = await this.getXzCompanyByCache(obj);
      if (tmXzList && tmXzList.code == 1 && tmXzList.data && tmXzList.data.length > 0) {
        var jsonStr = JSON.stringify(tmXzList.data);
        await this.cacheManager["FqTmDataCache"].setTmXzList("fqTmXzData", jsonStr);
        return result;
      }
      result.code = -110;
      result.message = "设置失败"
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "可续展的XX公司设置缓存异常",
        op: "base/api/impl/fqtmsearch/setTmXzList",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "查询异常"
      return result;
    }
  }

  async getCompanyTel(appKey, companyName) {
    var tmpobj = { appKey: appKey, companyName: companyName, currentPage: 1, pageSize: 10 }
    var telList = await this.phonesearch.phoneNameSearch(tmpobj);
    if (telList.status == 0 && telList.data && telList.data.result == 1 &&
      telList.data.list.length > 0 && telList.data.list[0]._doc) {
      var phone_number = "";
      for (let j = 0; j < telList.data.list.length; j++) {
        const element = telList.data.list[j];
        if (element._doc) {
          if ((/^1[34578]\d{9}$/.test(element._doc.phone_number))) {
            //符合电话规则
            phone_number = element._doc.phone_number;
            break;
          }
        }
      }
      return phone_number;
    }
    return "";
  }

  async getXzCompanyByCache(obj) {
    var result = {
      code: 1,
      message: "success",
      data: []
    };
    try {
      var data = await this.checkKey(obj.appKey);
      if (data && data.status && data.status == -1) {
        result.code = -100;
        result.message = "appKey参数错误"
        return result;
      }
      var retList = [];
      var addCacheCount = 500;//推荐商机个数
      for (let index = 0; index < 50; index++) {
        obj.currentPage = index + 1;
        obj.pageSize = 200;
        obj.searchType = 1;
        obj.opcache = 1;
        var self = this;
        if (retList.length > addCacheCount) {
          break;
        }
        var tmpResult = await this.getCompanySearch(obj);
        if (tmpResult.status == 0 && tmpResult.data && tmpResult.data.length > 0) {
          for (let j = 0; j < tmpResult.data.length; j++) {
            const item = tmpResult.data[j];
            if (item) {
              if (retList.length > addCacheCount) {
                break;
              }
              var tmpTelInfo = await self.getCompanyTel(obj.appKey, item.applicant_cn);
              if (tmpTelInfo) {
                var param = {
                  companyname: item.applicant_cn,
                  companyaddr: item.applicant_cn_addr,
                  businesstype: 1,
                  tel: tmpTelInfo
                }
                retList.push(param);
              }
            }
          }

        }
      }
      result.data = retList;
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "可续展的XX公司查询异常",
        op: "base/api/impl/fqtmsearch/getXzCompanyByCache",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.message = "查询异常"
      return result;
    }
  }

  async tmSearch(obj) {//商标查询
    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, "FqTmSearchApi");
  }

  async getCompanySearch(obj) {//XX商标类型的公司查询=商标公司类别：1为续展、2为续展过期、3不予受理、4驳回、5异议、6变更
    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);
    }
    var opcache = obj.opcache || "";//是否从缓存中查询

    var companyName = obj.companyName == null ? "" : obj.companyName;
    var addr = obj.area == null ? "" : obj.area;
    var pagesize = obj.pageSize == null ? 20 : obj.pageSize;
    var from = obj.currentPage == null ? 0 : Number((obj.currentPage - 1) * obj.pageSize);
    if (!opcache || opcache != 1) {
      if (pagesize > 100) {
        pagesize = 20;
      }
    }


    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 (opcache && opcache ==1) {
    //   var tmpParam = {
    //     "regexp": {
    //       "applicant_cn": "[\\\u4E00-\\\u9FA5]{2,500}"
    //     }
    //   }
    //   params.query.bool.must.push(tmpParam)
    // }

    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);
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      return System.getResult3(resultData.hits, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "XX商标类型的公司查询异常",
        op: "base/api/impl/fqtmsearch/getCompanySearch",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  };

  async xzSearch(obj) {//续展公司查询
    return await this.getCompanySearch(obj);
  };

  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;
    var pagesize = obj.pageSize == null ? 20 : obj.pageSize;
    var from = obj.currentPage == null ? 0 : Number((obj.currentPage - 1) * obj.pageSize);
    if (pagesize > 100) {
      pagesize = 20;
    }
    var reqUrl = this.xzDetailSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "renewals_type": type
              }
            },
            {
              "term": {
                "applicant_cn": companyName
              }
            }
          ]
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "regist_notice_day",
        "original_regist_notice_day",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "applicant_en",
        "applicant_cn_addr",
        "applicant_en_addr",
        "tm_agency",
        "pic_url"
      ],
      "sort": [
        {
          "tm_end_day": "desc"
        }
      ]
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      return System.getResult3(resultData.hits, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "续展详情查询异常",
        op: "base/api/impl/fqtmsearch/xzSearchDetail",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  };

  async bgSearch(obj) {//变更公司查询
    return await this.getCompanySearch(obj);
  };

  async bgSearchDetail(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;
    var pagesize = obj.pageSize == null ? 20 : obj.pageSize;
    var from = obj.currentPage == null ? 0 : Number((obj.currentPage - 1) * obj.pageSize);
    if (pagesize > 100) {
      pagesize = 20;
    }
    var reqUrl = this.bgDetailSearchUrl;
    var params = {
      "query": {
        "term": {
          "before_change_applicant_cn": companyName
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "regist_notice_day",
        "original_regist_notice_day",
        "regist_notice_issue",
        "regist_notice_page_num",
        "tm_end_day",
        "applicant_cn",
        "applicant_en",
        "applicant_cn_addr",
        "applicant_en_addr",
        "tm_agency",
        "pic_url",
        "before_change_applicant_cn",
        "before_change_applicant_en",
        "before_change_applicant_cn_addr",
        "before_change_applicant_en_addr"
      ],
      "sort": [
        {
          "tm_end_day": "desc"
        }
      ]
    };
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      return System.getResult3(resultData.hits, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "变更详情查询异常",
        op: "base/api/impl/fqtmsearch/bgSearchDetail",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  };

  async zntjSearch(obj) {

    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var companyName = obj.companyName == null ? "" : obj.companyName;;
    if (companyName == "") {
      return System.getResult2(null, null);
    }
    companyName = await this.getConvertSemiangleStr(companyName);
    var companyList = await this.cacheManager["FqTmSearchCache"].getCompanyTmListByCache(companyName);
    if (companyList) {
      var tmpResult = JSON.parse(companyList);
      return System.getResult2(tmpResult.data, null);
    }

    var reqUrl = this.tmZntjUrl.replace("{companyName}", encodeURIComponent(companyName));
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execGetTimeOut({}, reqUrl, this.reqTimeOut);
      var tmpResult = JSON.parse(rtn.stdout);
      if (tmpResult.status != 0) {
        //日志记录
        logCtl.error({
          optitle: "商标智能推荐调用接口：" + reqUrl + "异常",
          op: "base/api/impl/fqtmsearch/zntjSearch",
          content: "返回值：" + rtn.stdout,
          clientIp: ""
        });
        return System.getResult2(null, null, "other method fail");
      }
      //设置缓存
      await this.cacheManager["FqTmSearchCache"].setCompanyTmList(companyName, rtn.stdout);
      return System.getResult2(tmpResult.data, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "商标智能推荐异常",
        op: "base/api/impl/fqtmsearch/zntjSearch",
        content: e.stack,
        clientIp: ""
      });
      return System.getResult2(null, null, "zntjSearch error;");
    }
  };

  async tjdlSearch(obj) {//根据经营范围推荐大类
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    debugger;
    var companyName = obj.companyName == null ? "" : obj.companyName;
    var tmName = obj.tmName == null ? "" : obj.tmName;
    if (companyName == "") {
      return System.getResult2(null, null);
    }
    companyName = await this.getConvertSemiangleStr(companyName);
    var reqUrl = this.tmtjdlQueryUrl.replace("{companyName}", encodeURIComponent(companyName));
    reqUrl = reqUrl.replace("{tmName}", encodeURIComponent(tmName));
    debugger;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execGetTimeOut({}, reqUrl, this.reqTimeOut);
      var tmpResult = JSON.parse(rtn.stdout);
      if (tmpResult.status != 0) {
        //日志记录
        logCtl.error({
          optitle: "根据经营范围推荐大类" + reqUrl + "异常",
          op: "base/api/impl/fqtmsearch/zntjSearch",
          content: "返回值：" + rtn.stdout,
          clientIp: ""
        });
        return System.getResult2(null, null, "other method fail");
      }
      return System.getResult2(tmpResult.data, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "根据经营范围推荐大类",
        op: "base/api/impl/fqtmsearch/tjdlSearch",
        content: e.stack,
        clientIp: ""
      });
      return System.getResult2(null, null, "zntjSearch error;");
    }
  };

  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 invalidTmSearch(obj) {//无效查询
    var data = await this.checkKey(obj.appKey);
    if (data && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;;
    var regNum = obj.regNum == null ? "" : obj.regNum;
    var applier = obj.applicantCn == null ? "" : obj.applicantCn;
    var pagesize = obj.pageSize == null ? 20 : obj.pageSize;
    var from = obj.currentPage == null ? 0 : Number((obj.currentPage - 1) * obj.pageSize);
    if (pagesize > 100) {
      pagesize = 20;
    }
    if (tmName == "" && regNum == "" && applier == "") {
      return System.getResult2(null, null);
    }
    applier = await this.getConvertSemiangleStr(applier);
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "status": 2
              }
            }
          ]
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_type",
        "tm_regist_num",
        "tm_name",
        "tm_name_py",
        "tm_name_en",
        "apply_day",
        "regist_notice_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",
        "applicant_en",
        "original_applicant_cn",
        "original_applicant_en",
        "applicant_cn_addr",
        "applicant_en_addr",
        "tm_agency",
        "pic_url"
      ],

    };
    if (tmName != null && tmName != "") {
      var param = {
        "match": {
          "tm_name": tmName
        }
      }
      params.query.bool.must.push(param)
    }
    if (regNum != "" && regNum != null) {
      var param = {
        "term": {
          "tm_regist_num": regNum
        }
      }
      params.query.bool.must.push(param)
    }
    if (applier != "" && applier != null) {
      var param = {
        "term": {
          "applicant_cn": applier
        }
      }
      params.query.bool.must.push(param)
    }
    if ((tmName == null || tmName == "") && (regNum == null || regNum == "") && (applier == null || applier == "")) {
      params.query = { "match_all": {} };
    }
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var resultData = JSON.parse(rtn.stdout);
      return System.getResult3(resultData.hits, null);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "无效查询异常",
        op: "base/api/impl/fqtmsearch/invalidTmSearch",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  };
  //尼斯数据
  async getTmNcl(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var reqUrl = this.nclUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "level": 1
              }
            }
          ]
        }
      },
      "from": 0,
      "size": 100,
      "_source": [
        "code",
        "name"
      ],
      "sort": [
        {
          "code": "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) {
      //日志记录
      logCtl.error({
        optitle: "尼斯数据异常",
        op: "base/api/impl/fqtmsearch/getTmNcl",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  }
  //获取商标列表
  async getTmList(obj) {
    // 参数说明：
    // appKey：key、
    // tmName：商标名称、
    // tmClsId：商标分类、0不限、
    // countId：字数id（0-不限、1-2字、2-3字、3-4字、4-5字、5-5字以上）、
    // tmType：商标类型（0-不限、1-中文、2-英文、3-中文+英文、4-纯图形）、
    // sort：排序（目前不设置值，按最新排序）
    // pageSize：每页大小、currentPage：当前页，下标1开始
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var tmName = obj.tmName == null ? "" : obj.tmName;;
    var tmClsId = obj.tmClsId == null || obj.tmClsId == "" ? "0" : obj.tmClsId;
    var tmType = obj.tmType == null || obj.tmType == "" ? "0" : obj.tmType;
    var countId = obj.countId == null || obj.countId == "" ? "0" : obj.countId;
    var pagesize = obj.pageSize == null || obj.pageSize == "" ? 20 : obj.pageSize;
    var from = obj.currentPage == null || obj.currentPage == "" ? 0 : Number((obj.currentPage - 1) * obj.pageSize);
    if (pagesize > 200) {
      pagesize = 200;
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "ncl_one_codes",
        "status",
        "tm_regist_num",
        "tm_name",
        "apply_day",
        "applicant_cn",
        "applicant_en",
        "original_applicant_cn",
        "original_applicant_en",
        "applicant_cn_addr",
        "applicant_en_addr",
        "pic_url"
      ],
      "sort": [
        {
          "apply_day": "desc"
        }
      ]
    };
    if (tmClsId != "0") {
      var param = {
        "term": {
          "ncl_one_codes": tmClsId
        }
      }
      params.query.bool.must.push(param)
    }
    if (tmName != null && tmName != "" && tmType != "4") {
      var param = {
        "match": {
          "tm_name": tmName
        }
      }
      params.query.bool.must.push(param)
    }
    //纯图形的则只查询商标名称为图形的商标
    if (tmType == "4") {
      var param = {
        "match": {
          "tm_name": "图形"
        }
      }
      params.query.bool.must.push(param)
    }
    else {
      var tmpResultStr = await this.getTmNameRegexpStr(tmType, countId);
      if (tmpResultStr != "") {
        var param = {
          "regexp": {
            "tm_name.raw": tmpResultStr
          }
        }
        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) {
      //日志记录
      logCtl.error({
        optitle: "获取商标列表异常",
        op: "base/api/impl/fqtmsearch/getTmList",
        content: e.stack,
        clientIp: ""
      });
      return rtn = System.getResult2(null, null);
    }
  }
  async getTmNameRegexpStr(tmType, countId) {
    // tmType：商标类型（0-不限、1-中文、2-英文、3-中文+英文、4-纯图形）、
    // countId：字数id（0-不限、1-2字、2-3字、3-4字、4-5字、5-5字以上）、
    var tmpCountId = "";
    switch (countId) {
      case "1":
        tmpCountId = "{2,2}";
        break;
      case "2":
        tmpCountId = "{3,3}";
        break;
      case "3":
        tmpCountId = "{4,4}";
        break;
      case "4":
        tmpCountId = "{5,5}";
        break;
      case "5":
        tmpCountId = "{5,100}";
        break;
      default:
        tmpCountId = "";
    }
    var resultStr = "";
    switch (tmType) {
      case "1":
        resultStr = "[\\\u4E00-\\\u9FA5]";
        break;
      case "2":
        resultStr = "[a-zA-Z]";
        break;
      case "3":
        resultStr = "[\\\u4e00-\\\u9fa5_a-zA-Z0-9_]";
        break;
      default:
        resultStr = "";
    }
    if (resultStr == "" && tmpCountId != "") {
      resultStr = "[\\\u4e00-\\\u9fa5_a-zA-Z0-9_]";
    }
    return resultStr + tmpCountId;
  }

  convertDate(time) {//es时间戳转换时间
    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);
  }

  async fqImageSearch(obj) {//商标图像检索接口
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var result = { totalSize: 0, pageSize: 0, currentPage: 1, list: [] };
    var sources = [];
    var key = settings.apiconfig.imageQueryKey;
    var tmUrl = obj.imageUrl;
    var url = this.imageQueryUrl + "?imageurl=" + encodeURIComponent(tmUrl) + "&appkey=" + key;
    var pagesize = obj.pageSize == null ? 20 : obj.pageSize;
    var currentPage = obj.currentPage == null ? 1 : obj.currentPage
    var from = Number((currentPage - 1) * pagesize);
    var end = Number(from + pagesize)
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execGet({}, url);
      var data = JSON.parse(rtn.stdout);
      if (data[0].length && data[0].length > 0 && data[0] != undefined) {
        var d = data[0];
        var tmRegistNumsAll = [];
        for (var i = 0; i < d.length; i++) {
          tmRegistNumsAll.push(d[i].imageid);
        }
        var tmRegistNums = tmRegistNumsAll.slice(from, end);
        console.log(tmRegistNums);
        for (var i = 0; i < tmRegistNums.length; i++) {
          var regNum = tmRegistNums[i];
          var data = {
            tmRegistNum: regNum
          };
          var tms = await this.GsbTmSearchApi.fqImageSearch(data);
          if (tms.status == 0 && tms.data.length > 0) {
            var tm = tms.data[0];
            var source = {
              sbmc: tm.tm_name,//商标名称
              sbpy: tm.tm_name_py,//商标拼音
              sbyw: tm.tm_name_en,//商标英文
              gjfl: tm.ncl_one_codes,//国际分类
              sbzch: tm.tm_regist_num,//商标注册号
              sblx: this.tm_type[tm.tm_type],//商标类型  p普通商标、J集体商标、Z证明商标、T特殊商标
              sbzt: this.tm_status[tm.status],//商标状态
              sqrq: this.convertDate(tm.apply_day),//申请日期
              csrq: this.convertDate(tm.first_notice_day),//初审日期
              zcrq: this.convertDate(tm.original_regist_notice_day),//注册日期
              csggym: tm.first_notice_page_num,//初审公告页码
              zcr: tm.applicant_cn,//申请人
              jzrq: this.convertDate(tm.tm_end_day),//截止日期
              csggqh: tm.first_notice_issue == null ? "" : "第" + tm.first_notice_issue + "期",//初审公告（期号）
              zcggqh: tm.regist_notice_issue == null ? "" : "第" + tm.regist_notice_issue + "期",//注册公告
              zcggym: tm.regist_notice_page_num,//注册公告页码
              yzcr: tm.original_applicant_cn,//原申请人
              zcdz: tm.applicant_cn_addr,//申请地址
              dljg: tm.tm_agency,//代理机构
              zxzt: "",//最新状态
              spfwxm: "",
              lcxx: "",
              logo: tm.pic_url,//商标图样
            };
            sources.push(source);
          }
        }
        result.totalSize = tmRegistNumsAll.length;
        result.pageSize = pagesize;
        result.currentPage = currentPage;
        result.list = sources;
        return System.getResult2(result, null);
      }
      return System.getResult2(result, null);
    } catch (e) {
      console.log(e);
      return System.getResult2(result, null);
    }
    return System.getResult2(result, null);
  }
  async ImageSearch(obj) {//商标图像检索接口
    var data = await this.checkKey(obj.appKey);
    if (data && data.status && data.status == -1) {
      return data;
    }
    var result = { totalSize: 0,data: [] };
    var sources = [];
    var key = settings.apiconfig.imageQueryKey;
    var tmUrl = obj.imageUrl;
    var url = this.imageQueryUrl + "?imageurl=" + encodeURIComponent(tmUrl) + "&appkey=" + key;
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execGet({}, url);
      var data = JSON.parse(rtn.stdout);
      console.log(data);
      if (data[0].length && data[0].length > 0 && data[0] != undefined) {
        var d = data[0];
        result.totalSize = d.length;
        result.data = d;
        return System.getResult2(result, null);
      }
      return System.getResult2(result, null);
    } catch (e) {
      console.log(e);
      return System.getResult2(result, null);
    }
    return System.getResult2(result, null);
  }

}
module.exports = FqTmSearchApi;
