var System=require("../../system");
var settings=require("../../../config/settings");
const logCtl=System.getObject("web.oplogCtl");
//商标查询操作
class UtilsTmService{
  constructor(){
    this.tmSearchUrl=settings.apiconfig.tmSearchUrl();
    this.tmFlowUrl=settings.apiconfig.tmFlowUrl();
    this.tmNclUrl=settings.apiconfig.tmNclUrl();
    this.nclUrl=settings.apiconfig.nclUrl();
  }
  /*查询某一个申请人名下有多少条商标(applicant_cn:申请人-精确)
  auther:sy
返回值：
{
    "status": 0,
    "msg": "操作成功",
    "total": 2,----总条数
    "data": [],
    "bizmsg": "empty"
}
  */
  async tmCountByApplicantCn(obj,opName){
   var applicantCn=obj.applicant_cn==null||obj.applicant_cn==""||obj.applicant_cn=="undefined"?"":obj.applicant_cn;
   if(applicantCn==""){
     return System.getResult2(null,null,null,"申请人信息不能为空");
   }
   applicantCn=await this.getConvertSemiangleStr(applicantCn);
    var reqUrl=this.tmSearchUrl;
    var params ={
        "size":0,
        "query" : {
            "term" : { "applicant_cn" :applicantCn }
        }
    };
    return this.returnResult(params,reqUrl,opName,"tmCountByApplicantCn");
  }
  async tmShortListByRegistNums(obj,opName){
    var registNums=obj.registNums==null||obj.registNums==""||obj.registNums=="undefined"?[]:obj.registNums;
    var pagesize=obj.page_size==null||obj.page_size==""||obj.page_size=="undefined"?20:obj.page_size;
    if(pagesize>100){
      pagesize=20;
    }
    var from=obj.current_page==null||obj.current_page==""||obj.current_page=="undefined"?0:Number((obj.current_page-1)*pagesize);

    if(!registNums || registNums.length<1){
      return System.getResult2(null,null,null,"注册号不能为空");
    }
    var shouldList=[];
    for(var i=0;i<registNums.length;i++){
      if(registNums[i]){
        var obj= {"term" : { "tm_regist_num" : registNums[i] }};
        shouldList.push(obj);
      }
    }
    // applicantCn=await this.getConvertSemiangleStr(applicantCn);
     var reqUrl=this.tmSearchUrl;
     var params ={
          "query" : {
            "bool": {
              "should": shouldList
            } 
          },
         "from": from,
         "size": pagesize,
         "_source": [
      	 "ncl_one_codes",
      	 "status",
      	 "tm_type",
      	 "tm_regist_num",
      	 "tm_name",
      	 "apply_day",
      	 "regist_notice_day",
      	 "tm_end_day",
         "pic_url",
         "applicant_cn"
         ],
         "sort": [
           {
             "apply_day": "desc"
           }
         ]
      };
    return this.returnResult(params,reqUrl,opName,"tmShortListByApplicantCn");
  }
  /*查询某一个申请人名下有商标列表(applicant_cn:申请人-精确、page_size:每页大小、current_page:当前第几页)
  auther:sy
  返回值：
  {
    "status": 0,
    "msg": "操作成功",
    "total": 2,
    "data": [
        {
            "tm_end_day": 1740632400,
            "tm_name": "图形",
            "tm_type": "T",
            "apply_day": 1387170000,
            "ncl_one_codes": "43",
            "regist_notice_day": 1425013200,
            "tm_regist_num": "13739653",
            "pic_url": "http://43.247.184.94:7170/Img/000/137/396/53A/068d5558-be1d-4f2c-94db-61808c8316ad.jpg",
            "status": 3
        }
    ],
    "bizmsg": "empty"
}
返回值说明:status为0则为成功，否则为查询有误
        "ncl_one_codes"               国际分类
        "status"                      商标状态 1:有效；2:无效；3:待审；4:不定  5-未知状态
    	"tm_regist_num"	              注册号
        "tm_name"                     商标中文
        "apply_day"                   申请日期----格式为return System.getResult2(null,null,null,"openid参数有误");时间戳，转换后的格式为2018-08-21
        "pic_url"                     商标图样url
        “regist_notice_day”          注册公告日期
        “tm_type”                   商标类别：p普通商标、J集体商标、Z证明商标、T特殊商标
        “tm_end_day”                商标截至时间
		"total"						  总条数
  */
  async tmShortListByApplicantCn(obj,opName){
    var applicantCn=obj.applicant_cn==null||obj.applicant_cn==""||obj.applicant_cn=="undefined"?"":obj.applicant_cn;
    var pagesize=obj.page_size==null||obj.page_size==""||obj.page_size=="undefined"?20:obj.page_size;
    if(pagesize>100){
      pagesize=20;
    }
    var from=obj.current_page==null||obj.current_page==""||obj.current_page=="undefined"?0:Number((obj.current_page-1)*pagesize);

    if(applicantCn==""){
      return System.getResult2(null,null,null,"申请人信息不能为空");
    }
    applicantCn=await this.getConvertSemiangleStr(applicantCn);
     var reqUrl=this.tmSearchUrl;
     var params ={
          "query" : {
              "term" : { "applicant_cn" : applicantCn }
          },
         "from": from,
         "size": pagesize,
         "_source": [
      	 "ncl_one_codes",
      	 "status",
      	 "tm_type",
      	 "tm_regist_num",
      	 "tm_name",
      	 "apply_day",
      	 "regist_notice_day",
      	 "tm_end_day",
         "pic_url",
         "applicant_cn"
         ],
         "sort": [
           {
             "apply_day": "desc"
           }
         ]
      };
    return this.returnResult(params,reqUrl,opName,"tmShortListByApplicantCn");
  }
  /*商标查询参数(tm_name:商标名称-模糊、reg_num:注册号-精确、applier:申请人-精确、page_size:每页大小、current_page:当前第几页，从1开始)
  auther:sy
返回值：
{
  "status": 0,
  "msg": "操作成功",
  "total": 4835,
  "data": [
    {
	"ncl_one_codes": "40",
	"status": 3,
	"tm_regist_num": "26316702",
	"tm_name": "洋河",
	"applicant_en_addr": null,
	"applicant_cn": "江苏洋河酒厂股份有限公司",
	"applicant_cn_addr": "江苏省宿迁市洋河中大街118号",
	"original_applicant_en": null,
	"apply_day": 1504843200,
	"original_applicant_cn": null,
	"applicant_en": null,
	"pic_url": "http://43.247.184.94:7170/Img/000/143/154/66A/original.jpg"

    }
  ],
  "bizmsg": "empty"
}
返回值说明:status为0则为成功，否则为查询有误
        "ncl_one_codes"               国际分类
        "status"                      商标状态 1:有效；2:无效；3:待审；4:不定  5-未知状态
    	"tm_regist_num"	              注册号
        "tm_name"                     商标中文
        "apply_day"                   申请日期----格式为时间戳，转换后的格式为2018-08-21
        "applicant_cn"                申请人中文
        "applicant_en"                申请人英文
		"original_applicant_cn",      原申请人中文
		"original_applicant_en",	  原申请人英文
		"applicant_cn_addr",		  申请人中文地址
		"applicant_en_addr",		  申请人英文地址
        "pic_url"                     商标图样url
		"total"						  总条数
  */
  async tmSearch(obj,opName){
    var tmName=obj.tm_name==null||obj.tm_name==""||obj.tm_name=="undefined"?"":obj.tm_name;
    var regNum=obj.reg_num==null||obj.reg_num==""||obj.reg_num=="undefined"?"":obj.reg_num;
    var applicantCn=obj.applicant_cn==null||obj.applicant_cn==""||obj.applicant_cn=="undefined"?"":obj.applicant_cn;
    var pagesize=obj.page_size==null||obj.page_size==""||obj.page_size=="undefined"?20:obj.page_size;
    if(pagesize>100){
      pagesize=20;
    }
    var from=obj.current_page==null||obj.current_page==""||obj.current_page=="undefined"?0:Number((obj.current_page-1)*pagesize);

   if(tmName=="" && regNum=="" && applicantCn==""){
     return System.getResult2(null,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"
         ],
         "sort": [
           {
             "apply_day": "desc"
           }
         ]
       };
       if(tmName!=""){
         var param=  {
               "match": {
                 "tm_name": tmName
               }
         }
         params.query.bool.must.push(param)
       }
       if(regNum!=""){
         var param=  {
               "term": {
                 "tm_regist_num": regNum
               }
         }
         params.query.bool.must.push(param)
       }
       if(applicantCn!=""){
         applicantCn=await this.getConvertSemiangleStr(applicantCn);
         var param=  {
               "term": {
                 "applicant_cn": applicantCn
               }
         }
         params.query.bool.must.push(param)
       }
       if(tmName=="" && regNum=="" && applicantCn==""){
         params.query= { "match_all": {} };
       }
       return this.returnResult(params,reqUrl,opName,"tmSearch");
  }

  /*商标流程参数（reg_num：注册号-精确）
  auther:sy
  返回值：
  {
      "status": 0,
      "msg": "操作成功",
      "total": 2,
      "data": [
          {
              "notice_type_name": "商标注册公告（一）",
              "notice_data": 1211860800,
              "link_url": "http://sbggwj.saic.gov.cn:8000/tmann/group1/M00/1B/4B/yBQCH1mEmQWAVEbpAAGe8w8mrJE224.jpg"
          }
      ],
      "bizmsg": "empty"
  }
  返回值说明:status为0则为成功，否则为查询有误
          "notice_type_name"        公告类型名称
          "notice_data"             日期
      	  "link_url"	              文档链接
  */
  async getTmFlow(obj,opName){
    var regNum=obj.reg_num==null||obj.reg_num==""||obj.reg_num=="undefined"?"":obj.reg_num;
    if(regNum==""){
      return System.getResult2(null,null,null,"商标注册号不能为空");
    }
    var reqUrl=this.tmFlowUrl;
    var params = {
         "query": {
           "term": {
             "tm_regist_num": regNum
           }
         },
         "from": 0,
         "size": 500,
         "_source": [
           "notice_data",
           "notice_type_name",
           "link_url"
         ],
         "sort": [
           {
             "notice_data": "desc"
           }
         ]
       };
       return this.returnResult(params,reqUrl,opName,"getTmFlow");
  }

  /*商标小类(reg_num：注册号-精确、nclone_code:大类号-精确)
  auther:sy
  返回值：
  {
      "status": 0,
      "msg": "操作成功",
      "total": 10,
      "data": [
          {
              "ncl_one": "2:颜料油漆",
              "ncl_last": "020059:颜料"
          },
          {
              "ncl_one": "2:颜料油漆",
              "ncl_last": "020008:绘画用铝粉"
          }
      ],
      "bizmsg": "empty"
  }
  返回值说明:status为0则为成功，否则为查询有误
          "ncl_one"               国际分类编码及名称
          "ncl_last"              小类编码及名称
  		"total"					总条数
  */
  async getTmNclSmallCodes(obj,opName){
    var regNum=obj.reg_num==null||obj.reg_num==""||obj.reg_num=="undefined"?"":obj.reg_num;
    var nclOneCode=obj.nclone_code==null||obj.nclone_code==""||obj.nclone_code=="undefined"?"":obj.nclone_code;
    if(regNum==""){
      return System.getResult2(null,null,null,"商标注册号不能为空");
    }
    if(nclOneCode==""){
      return System.getResult2(null,null,null,"商标大类不能为空");
    }
    var reqUrl=this.tmNclUrl;
    var params = {
         "query": {
           "bool": {
             "must": [
               {
                 "term": {
                   "reg_num": regNum
                 }
               },
               {
                 "wildcard": {
                   "ncl_one": nclOneCode+":*"
                 }
               }
             ]
           }
         },
         "from": 0,
         "size": 500,
         "_source": [
           "ncl_one",
           "ncl_two",
           "ncl_last"
         ]
       };
       return this.returnResult(params,reqUrl,opName,"getTmNclSmallCodes");
  }
  //××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××××商标群组信息-开始*********************************
  /*商标群组信息(reg_num：注册号-精确、nclone_code:大类号-精确)
  auther:sy
  返回值：
  {
      "status": 0,
      "msg": "操作成功",
      "total": 10,
      "data": [
          {
              "ncl_one": "2:颜料油漆",
              "ncl_last": "020059:颜料"
          },
          {
              "ncl_one": "2:颜料油漆",
              "ncl_last": "020008:绘画用铝粉"
          }
      ],
      "bizmsg": "empty"
  }
  返回值说明:status为0则为成功，否则为查询有误
          "ncl_one"               国际分类编码及名称
          "ncl_last"              小类编码及名称
  		"total"					总条数
  */
  async getGroupNclNumList(obj,opName){
    var regNum=obj.reg_num||"";
    var nclOneCode=obj.nclone_code||"";
    if(regNum==""){
      return System.getResult2(null,null,null,"商标注册号不能为空");
    }
    if(nclOneCode==""){
      return System.getResult2(null,null,null,"商标大类不能为空");
    }
    var small_list=await this.getTmNclSmallCodes(obj,opName);
    if(small_list.status!=0 || small_list.data.length==null || small_list.data.length==0 ){
        return System.getResult2(null,null,null,"查询数据为空");
    }
    var retsultData={
      exist:[],
    }
    var self=this;
    for (var i = 0; i < small_list.data.length; i++) {
      var item=small_list.data[i];
      if(item!=null){
        var exist_two_code=item.ncl_two||"";
        // var small_code=item.ncl_last||"";
        var exist_data={};
        if(exist_two_code!=null && exist_two_code!=""){
          //处理存在的二级类
          var twoList=exist_two_code.split(':');
          exist_data.code=twoList.length==2?twoList[0]:exist_two_code;

          if(retsultData.exist.findIndex(v => v.code ===exist_data.code)<0){
            retsultData.exist.push(exist_data);
          }
        }
      }
    }
    retsultData.exist.sort(self.keysort('code',false));
    return System.getResult2(retsultData,"ok");
  }
  async getGroupNclInfo(obj,opName){
    var regNum=obj.reg_num||"";
    var nclOneCode=obj.nclone_code||"";
    if(regNum==""){
      return System.getResult2(null,null,null,"商标注册号不能为空");
    }
    if(nclOneCode==""){
      return System.getResult2(null,null,null,"商标大类不能为空");
    }
    var small_list=await this.getTmNclSmallCodes(obj,opName);
    if(small_list.status!=0 || small_list.data.length==null || small_list.data.length==0 ){
        return System.getResult2(null,null,null,"查询数据为空");
    }
    //获取大类下的所有二级类
    var two_nclList=await this.getNclInfo({nclcode:nclOneCode,level:2},opName);
    if(two_nclList.status!=0 || two_nclList.data.length==null || two_nclList.data.length==0 ){
        return System.getResult2(null,null,null,"查询二级类数据为空");
    }
    var tmp_twoNclDataList=two_nclList.data;
    var retsultData={
      exist:[],
      not_exist:[]
    }
    var self=this;
    for (var i = 0; i < small_list.data.length; i++) {
      var item=small_list.data[i];
      if(item!=null){
        var exist_two_code=item.ncl_two||"";
        var small_code=item.ncl_last||"";
        var exist_data={};
        //处理三级类
        if(small_code!=null && small_code!=""){
            var smallList=small_code.split(':');
            exist_data.small_name=smallList.length==2?smallList[1]:small_code;
        }
        if(exist_two_code!=null && exist_two_code!=""){
          //处理存在的二级类
          var twoList=exist_two_code.split(':');
          exist_data.code=twoList.length==2?twoList[0]:exist_two_code;
          retsultData.exist.push(exist_data);

          var delIndex=tmp_twoNclDataList.findIndex(v => v.code ===exist_data.code);
          if(delIndex>=0){
            //移除单个数据
            tmp_twoNclDataList.splice(delIndex, 1);
          }
        }
      }
    }
    retsultData.not_exist=tmp_twoNclDataList;
    retsultData.exist.sort(self.keysort('code',false));
    retsultData.not_exist.sort(self.keysort('code',false));
    return System.getResult2(retsultData,"ok");
  }
  /**
    * 排序有倒序 对数组中的对象，按对象的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 getNclInfo(obj,opName){
    var nclcode=obj.nclcode==null?"":obj.nclcode;
    var level=obj.level==null?"":obj.level;
    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!=""){
       if(nclcode.length==1){
         nclcode="0"+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)
     }
     return this.returnResult(params,reqUrl,opName,"getNclInfo");
  }

  async getConvertSemiangleStr(str){
    var result = "";
    var len = str.length;
    for(var i=0;i<len;i++)
    {
        var cCode = str.charCodeAt(i);
        //全角与半角相差（除空格外）：65248（十进制）
        cCode = (cCode>=0xFF01 && cCode<=0xFF5E)?(cCode - 65248) : cCode;
        //处理空格
        cCode = (cCode==0x03000)?0x0020:cCode;
        result += String.fromCharCode(cCode);
    }
   return result;
  }

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


}
module.exports=UtilsTmService;
