var System = require("../../system");
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
//商标查询操作
class UtilsTmTransactionService {
  constructor() {
    this.tmSearchUrl = settings.apiconfig.tmSearchUrl();
    this.tmFlowUrl = settings.apiconfig.tmFlowUrl();
    this.tmNclUrl = settings.apiconfig.tmNclUrl();
    this.nclUrl = settings.apiconfig.nclUrl();
    this.tmTransactionUrl = settings.apiconfig.tmTransactionUrl();
    this.tmTransactionUpdateUrl = settings.apiconfig.tmTransactionUpdateUrl();
  }

  /*查询某一个申请人名下有商标列表(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 tmTransactionSearch(obj) {//商标交易检索接口
    console.log("=========================");
    console.log(obj);
    var keyword = obj.keyword;
    var tm_nclcode = obj.tm_nclcode;
    var price_min = obj.price_min;
    var price_max = obj.price_max;
    var tm_structure = obj.tm_structure;
    var tm_word = obj.tm_word;
    var order_field = obj.order_field;
    var sort = obj.sort;
    var pagesize = obj.pagesize;
    var currentpage = obj.currentpage;
    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.tmTransactionUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "range": {
                "platform_quoted_price": {
                  "gte": parseFloat(price_min),
                  "lte": parseFloat(price_max)
                }
              }
            },
            {
              "term": {
                "is_transaction": 1
              }
            }
          ],
          "must_not": []
        }
      },
      "from": from,
      "size": pagesize,
      "_source": [
        "tm_name",
        "tm_regist_num",
        "platform_quoted_price",
        "pic_url",
        "ncl_one_codes",
        "tm_introduction",
        "pic_url_user"
      ]
    };
    if (keyword != null && keyword != "") {
      var param = {
        "wildcard": {
          "tm_name.raw": "*" + keyword + "*"
        }
      }
      params.query.bool.must.push(param)
    }
    if (tm_nclcode && tm_nclcode.length > 0) {
      for(var i=0;i<tm_nclcode.length;i++){
        console.log(tm_nclcode[i]);
        var param = {
          "term": {
            "ncl_one_code_list": tm_nclcode[i]
          }
        }
        params.query.bool.must.push(param)
      }
      var param = {
        "terms": {
          "ncl_one_codes": tm_nclcode
        }
      }
      params.query.bool.must.push(param)
      if(tm_structure=="纯图形"){
        var param = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool.must.push(param)
      }else{
        var param = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool["must_not"]=param;
      }
      params["sort"]={
        "tm_name.raw":"desc"
      }
    }
    //每次都随机查询数据
    if (keyword == "" && !tm_nclcode && tm_nclcode.length == 0 && price_min == "" && price_max == "" && tm_structure == "" && tm_word == "" && order_field == "" && sort == "") {
      console.log("================================++++++++++++++++++++++++++");
      params.sort = {
        "_script": {
          "script": "Math.random()",//随机排序
          "type": "number",
          "order": "asc"
        }
      }
    }
    if (order_field != "" && order_field != null) {
      if (sort != "" && sort != null) {
        if(order_field=="created_at"){
          params.sort={
              "created_at":sort
          }
        }
        if(order_field=="platform_quoted_price"){
          params.sort={
              "platform_quoted_price":sort
          }
        }
      }
    }
    var tiiaojianparams = {
      "bool": {
        "should": []
      }
    };
    if (tm_structure != "" && tm_structure != null) {
      if (tm_structure == "纯中文") {
        var param = {
          "range": {
            "cn_count": {
              "gte": 1
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "lte": 0
            }
          }
        }

        var paramnot = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool.must.push(param)
        params.query.bool.must.push(paramen)
        params.query.bool.must_not.push(paramnot)
      } if (tm_structure == "中文+英文") {
        var param = {
          "range": {
            "cn_count": {
              "gte": 1
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "gte": 1
            }
          }
        }
        var paramnot = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool.must.push(param)
        params.query.bool.must.push(paramen)
        params.query.bool.must_not.push(paramnot)
      } if (tm_structure == "纯英文") {
        var param = {
          "range": {
            "cn_count": {
              "lte": 0
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "gte": 1
            }
          }
        }
        var paramnot = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool.must.push(param)
        params.query.bool.must.push(paramen)
        params.query.bool.must_not.push(paramnot)
      } if (tm_structure == "纯图形") {
        var param = {
          "term": {
            "tm_name.raw": "图形"
          }
        }
        params.query.bool.must.push(param)
      } if (tm_structure == "纯数字") {
        var param = {
          "regexp": {
            "tm_name.raw": "[0-9]*"
          }
        }
        params.query.bool.must.push(param)
      } if (tm_structure == "中文+图形") {
        var param = {
          "range": {
            "cn_count": {
              "gte": 1
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "lte": 0
            }
          }
        }
        // var paramtu = {
        //   "term": {
        //     "tm_name.raw": "图形"
        //   }
        // }
        // tiiaojianparams.bool.should.push(paramtu);
        params.query.bool.must.push(param);
        params.query.bool.must.push(paramen);
        // params.query.bool.must.push(tiiaojianparams)
      } if (tm_structure == "英文+图形") {
        var param = {
          "range": {
            "cn_count": {
              "lte": 0
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "gte": 1
            }
          }
        }
        // var paramtu = {
        //   "term": {
        //     "tm_name.raw": "图形"
        //   }
        // }
        // tiiaojianparams.bool.should.push(paramtu);
        params.query.bool.must.push(param);
        params.query.bool.must.push(paramen);

      } if (tm_structure == "中文+英文+图形") {
        var param = {
          "range": {
            "cn_count": {
              "gte": 1
            }
          }
        }
        var paramen = {
          "range": {
            "en_name_count": {
              "gte": 1
            }
          }
        }
        // var paramtu = {
        //   "term": {
        //     "tm_name.raw": "图形"
        //   }
        // }
        // tiiaojianparams.bool.should.push(paramtu);
        params.query.bool.must.push(param);
        params.query.bool.must.push(paramen);
      }
    }
    if (tm_word != "" && tm_word != null) {
      if (tm_word == "2") {
        var param = {
          "range": {
            "tm_name_count": {
              "lte": tm_word
            }
          }
        }
        params.query.bool.must.push(param)
      }
      if (tm_word == "3") {
        var param = {
          "term": {
            "tm_name_count": tm_word
          }
        }
        params.query.bool.must.push(param)
      }
      if (tm_word == "4") {
        var param = {
          "term": {
            "tm_name_count": tm_word
          }
        }
        params.query.bool.must.push(param)
      }
      if (tm_word == "5") {
        var param = {
          "term": {
            "tm_name_count": tm_word
          }
        }
        params.query.bool.must.push(param)
      }
      if (tm_word == "6") {
        var param = {
          "range": {
            "tm_name_count": {
              "gte": tm_word
            }
          }
        }
        params.query.bool.must.push(param)
      }
    }

    // if(price_min!=""&&price_min!=null){
    //   if(price_max!=""&&price_max!=null){
    //     var param=  {
    //       "range": {
    //         "platform_quoted_price":{
    //           "gte": price_min,
    //           "lte":price_max
    //         }
    //       }
    //     }
    //     params.query.bool.must.push(param)
    //   }else {
    //     var param=  {
    //       "range": {
    //         "platform_quoted_price":{
    //           "gte": price_min
    //         }
    //       }
    //     }
    //     params.query.bool.must.push(param)
    //   }
    // }else{
    //   if(price_max!=""&&price_max!=null){
    //     var param=  {
    //       "range": {
    //         "platform_quoted_price":{
    //           "gte": price_min,
    //           "lte":price_max
    //         }
    //       }
    //     }
    //     params.query.bool.must.push(param)
    //   }
    // }

    if (tiiaojianparams.bool.should.length > 0) {
      params.query.bool.must.push(tiiaojianparams);
    }
    console.log(params);
    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 tmRegistSearchsve(obj) {//通过商标号查询
    var regNum = obj.registNum == null ? "" : obj.registNum;
    regNum = regNum.toString();
    if (regNum == "") {
      return System.getResult2(null, null);
    }
    var reqUrl = this.tmSearchUrl;
    var params = {
      "query": {
        "bool": {
          "must": []
        }
      },
      "size": 45,
      "_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",
        "tm_end_day_format",
        "regist_notice_day_format",
        "applicant_cn",
        "original_applicant_cn",
        "applicant_cn_addr",
        "applicant_en",
        "applicant_en_addr",
        "tm_agency",
        "pic_url",
        "ncl_two_codes"
      ],
    };

    if (regNum != "" && regNum != null) {
      var lastchar = regNum.split("");
      var last = lastchar[lastchar.length - 1];
      if (last == "A") {
        regNum = regNum.substring(0, regNum.length - 1);
      }
      var param = {
        "regexp": {
          "tm_regist_num": "[TG]{0,1}" + regNum + "[A]{0,1}"
        }
      }
      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 tmTransactionDetailsve(obj) {//商标交易详情接口
    console.log("=========================");
    console.log(obj);
    var sbzch = obj.sbzch;
    var gjfl = obj.gjfl;
    var reqUrl = this.tmTransactionUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "is_transaction": 1
              }
            }
          ]
        }
      },
      "_source": [
        "tm_name",
        "tm_regist_num",
        "platform_quoted_price",
        "pic_url",
        "ncl_one_codes",
        "tm_introduction",
        "pic_url_user"
      ]
    };
    if (sbzch != null && sbzch != "") {
      var param = {
        "term": {
          "tm_regist_num": sbzch
        }
      }
      params.query.bool.must.push(param)
    }
    if (gjfl != null && gjfl != "") {
      var param = {
        "term": {
          "ncl_one_codes": parseInt(gjfl)
        }
      }
      params.query.bool.must.push(param)
    }
    console.log(params.query.bool.must);
    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 tmTransactionUpdatesve(obj, rc) {//商标交易修改接口
    if (!rc) {
      rc = System.getObject("util.execClient");
    }
    var sbzch = obj.sbzch;
    var is_transaction = obj.is_transaction;
    var platform_quoted_price = obj.platform_quoted_price;
    var tm_introduction = obj.tm_introduction;
    var pic_url_user = obj.pic_url_user;

    var reqUrl = this.tmTransactionUpdateUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "tm_regist_num": sbzch
              }
          }]
        }
      },
          "script": {
              "inline": "ctx._source.platform_quoted_price = params.platform_quoted_price;ctx._source.tm_introduction = params.tm_introduction;ctx._source.is_transaction = params.is_transaction;ctx._source.pic_url_user = params.pic_url_user",
              "params": {
                  "platform_quoted_price": platform_quoted_price,
                  "tm_introduction":tm_introduction,
                  "is_transaction":is_transaction,
                  "pic_url_user":pic_url_user
              },
              "lang": "painless"
      }
    };

    // console.log(params.query.bool.must);
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      logCtl.info({
        optitle: "商标交易修改接口错误-info",
        op: "/base/service/impl/utilstmTransactionSve.js/tmTransactionUpdatesve",
        content: rtn.stdout,
        clientIp: ""
      });
      var j = JSON.parse(rtn.stdout);
      console.log(j);
      var result = {
        status: 0,
        msg: "修改成功",
        total: j.total
      };
      return result;
    } catch (e) {
      logCtl.error({
        optitle: "商标交易修改接口错误-error",
        op: "/base/service/impl/utilstmTransactionSve.js/tmTransactionUpdatesve",
        content: e.stack,
        clientIp: ""
      });
      var result = {
        status: -1,
        msg: "修改失败",
        total: 0
      };
      return result;
    }
  }
  async tmTransactionUpdateHeatsve(obj) {//商标交易修改热度接口
    // console.log("=========================");
    // console.log(obj);
    var sbzch = obj.sbzch;
    var gjfl = obj.gjfl;
    var heat = obj.heat;
    var reqUrl = this.tmTransactionUpdateUrl;
    var params = {
      "query": {
        "bool": {
          "must": [
            {
              "term": {
                "tm_regist_num": sbzch
              }
            }
          ]
        }
      },
      "script": {
        "source": "ctx._source.platform_quoted_price = params.heat",
        "params": {
          "heat": heat
        }
      }
    };

    console.log(params.query.bool.must);
    var rc = System.getObject("util.execClient");
    var rtn = null;
    try {
      rtn = await rc.execPost(params, reqUrl);
      var j = JSON.parse(rtn.stdout);
      console.log(j);
      var result = {
        status: 0,
        msg: "修改成功",
        total: j.total
      };
      return result;
    } catch (e) {
      var result = {
        status: -1,
        msg: "修改失败",
        total: 0
      };
      return result;
    }
  }





}
module.exports = UtilsTmTransactionService;
