var System = require("../../system");
var settings = require("../../../config/settings");
const logCtl = System.getObject("web.oplogCtl");
//商标查询操作
class UtilsTmTaskTradeService {
  constructor() {
    // this.tmFlowUrl = settings.apiconfig.tmFlowUrl();
    // this.tmNclUrl = settings.apiconfig.tmNclUrl();
    // this.nclUrl = settings.apiconfig.nclUrl();
    this.tmSearchUrl = settings.apiconfig.tmSearchUrl();
    this.opTmTransactionUrl = settings.apiconfig.opTmTransactionUrl();
    this.tmTransactionUrl = settings.apiconfig.tmTransactionUrl();
    this.trademarktransactionDao = System.getObject("db.trademarktransactionDao");
    this.orderSve = System.getObject("service.orderSve");
    this.tmNclUrl = settings.apiconfig.tmNclUrl();
  }
  async getAuditList(pageIndex, pageSize) {
    //publish_status===:tm_transaction_publish_status": { "audit": "审核中", "fail": "审核不通过", "success": "审核通过", "uppershelf": "上架", "lowershelf": "下架" }
    var whereObj = { publish_status: "audit" };
    return this.trademarktransactionDao.getPageList(pageIndex, pageSize, whereObj, [["created_at", 'desc']], null);
  }
  buildDate(date) {
    var date = new Date(date);
    var time = Date.parse(date);
    time = time / 1000;
    return time;
  }
  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 opAuditData() {
    var self = this;
    var rc = System.getObject("util.execClient");
    var list = await self.getAuditList(1, 101);
    if (!list || list.rows.length == 0) {
      return "no";
    }
    var codeList = [];
    for (let i = 0; i < list.rows.length; i++) {
      const codeItem = list.rows[i];
      if (codeItem) {
        codeList.push(codeItem.code);
      }
      if (codeList.length == 100) {
        await self.opEsQuery(list.rows, codeList, self, rc);
        codeList = [];
      }
    }
    if (codeList.length > 0) {
      await self.opEsQuery(list.rows, codeList, self, rc);
    }
    return "ok";
  }
  //订单付款提醒任务（针对未付款订单）
  async orderPaymentReminder() {
    return this.orderSve.orderPaymentReminder();
  }
  async opEsQuery(auditData, codeList, self, rc) {
    var params = {
      "query": {
        "terms": {
          "tm_regist_num": codeList
        }
      },
      "from": 0,
      "size": 500,
      "_source": [
        "pic_url",
        "tm_name",
        "tm_name_en",
        "tm_regist_num",
        "ncl_one_codes",
        "applicant_cn",
        "original_regist_notice_day",
        "tm_end_day",
        "ncl_two_codes",
        "cn_count",
        "en_name_count",
        "regist_notice_day"
      ]
    };
    logCtl.info({
      optitle: "往ES中插入数据查询ES-opEsQuery-info",
      op: "/igirl-web/app/base/service/impl/utilstmtasktradeSve.js/opEsQuery",
      content: JSON.stringify(params),
      clientIp: ""
    });
    var esData = await self.returnResult(params, this.tmSearchUrl, "UtilsTmTaskTradeService", "opEsQuery");
    if (esData.status == 0 && esData.data.length > 0) {
      await self.addEsData(auditData, esData.data, self, rc);
    }
  }
  async addEsData(auditData, esTmList, self, rc) {
    var addDbList = [];
    var rtn = null;
    for (let b = 0; b < esTmList.length; b++) {
      const esItem = esTmList[b];
      var auditList = auditData.filter(a => a.code == esItem.tm_regist_num);
      if (!auditList || auditList.length == 0) {
        continue;
      }
      var params = {
        created_at: self.buildDate(auditList[0].created_at),
        tm_regist_num: esItem.tm_regist_num,
        en_name: esItem.tm_name_en,
        en_name_count: esItem.en_name_count,
        en_name_standard: esItem.tm_name_en,
        tm_name: esItem.tm_name,
        tm_name_standard: esItem.tm_name,
        tm_name_count: Number(esItem.cn_count || "0") + Number(esItem.en_name_count || "0"),
        cn_count: esItem.cn_count,
        pic_url: esItem.pic_url,
        pic_url_user: auditList[0].pic_url || "",
        is_transaction: 1,//--------------------db----是否可以交易
        ncl_one_codes: esItem.ncl_one_codes,
        platform_quoted_price: auditList[0].platform_quoted_price,
        tm_heat: 0,
        tm_introduction: auditList[0].tm_introduction,
      };
      try {
        await self.putDbData(esItem, auditData, addDbList, self);
        var esParams = {
          "query": {
            "bool": {
              "must": [
                {
                  "term": {
                    "ncl_one_codes": esItem.ncl_one_codes
                  }
                },
                {
                  "term": {
                    "tm_regist_num": esItem.tm_regist_num
                  }
                }
              ]
            }
          },
          "from": 0,
          "size": 1,
          "_source": [
            "tm_name"
          ]
        };
        var queryEs = await self.returnResult(esParams, this.tmTransactionUrl, "UtilsTmTaskTradeService", "addEsData");
        if (queryEs.status == 0 && queryEs.data && queryEs.data.length == 0) {
          await rc.execPost(params, self.opTmTransactionUrl);
        }
      } catch (e) {
        logCtl.error({
          optitle: "往ES中插入数据或更新商标交易中的商标异常error",
          op: "/igirl-web/app/base/service/impl/utilstmtasktradeSve.js/addEsData.js",
          content: e.stack,
          clientIp: ""
        });
      }
    }
    if (addDbList.length > 0) {
      await this.trademarktransactionDao.model.bulkCreate(addDbList);
    }
  }
  async putDbData(esItem, auditData, addDbList, self) {//更新数据库
    var putIndex = auditData.findIndex(f => f.code === esItem.tm_regist_num);
    if (putIndex < 0) {
      return;
    }

    //商标小项查询
    var params2 = {
      "query": {
        "term": {
          "reg_num": esItem.tm_regist_num
        }
      },
      "from": 0,
      "size": 500,
      "_source": [
        "ncl_last"
      ]
    };
    var nclthird = [];
    var esData2 = await self.returnResult(params2, this.tmNclUrl, "UtilsTmTaskTradeService", "opEsQuery");
    if (esData2.status == 0 && esData2.data.length > 0) {
      for (let l = 0; l < esData2.data.length; l++) {
        if (esData2.data[l].ncl_last.indexOf(":") != -1) {
          var sptirdncl = esData2.data[l].ncl_last.split(":")[1];
          if (nclthird.indexOf(sptirdncl) < 0) {
            nclthird.push(sptirdncl);
          }
        }
        else {
          if (nclthird.indexOf(esData2.data[l].ncl_last) < 0) {
            nclthird.push(esData2.data[l].ncl_last);
          }
        }
      }
    }
    var filterTmListr = auditData.filter(f => f.code === esItem.tm_regist_num );
    var filterTmList = auditData.filter(f => f.code === esItem.tm_regist_num && f.ncl_one_code === esItem.ncl_one_codes);
    if ((!filterTmListr || filterTmListr.length ==0) &&(!filterTmList || filterTmList.length ==0)) {
      var addParams = {
        code: esItem.tm_regist_num,
        ncl_one_code: esItem.ncl_one_codes,
        name: esItem.tm_name,
        excelName: esItem.tm_name,
        tm_applier: esItem.applicant_cn,
        tm_group: JSON.stringify(esItem.ncl_two_codes),
        pic_url: auditData[putIndex].pic_url || esItem.pic_url,
        business_quoted_price: auditData[putIndex].business_quoted_price,
        platform_quoted_price: auditData[putIndex].platform_quoted_price,
        tm_structure_name: auditData[putIndex].tm_structure_name,
        tm_introduction: auditData[putIndex].tm_introduction,
        publish_status: "uppershelf",
        createcompany_id: auditData[0].createcompany_id,
        createuser_id: auditData[0].createuser_id,
        notes: "add_new",
        tm_regist_day: esItem.regist_notice_day,
        tm_ncl_third:  JSON.stringify(nclthird)
      };
      if (esItem.original_regist_notice_day && esItem.original_regist_notice_day != null) {
        addParams.tm_start_day = self.convertDate(esItem.original_regist_notice_day);
      }
      if (esItem.tm_end_day && esItem.tm_end_day != null) {
        addParams.tm_end_day = self.convertDate(esItem.tm_end_day);
      }
      addDbList.push(addParams);
      return;
    }//大类是有值，则新增数据到db
    auditData[putIndex].ncl_one_code = esItem.ncl_one_codes;
    var setField = {
      ncl_one_code: esItem.ncl_one_codes,
      name: esItem.tm_name,
      tm_applier: esItem.applicant_cn,
      tm_group: JSON.stringify(esItem.ncl_two_codes),
      pic_url: auditData[putIndex].pic_url || esItem.pic_url,
      publish_status: "uppershelf"
    };
    if (esItem.original_regist_notice_day && esItem.original_regist_notice_day != null) {
      setField.tm_start_day = self.convertDate(esItem.original_regist_notice_day);
    }
    if (esItem.tm_end_day && esItem.tm_end_day != null) {
      setField.tm_end_day = self.convertDate(esItem.tm_end_day);
    }
    var sqlWhere = { where: { id: auditData[putIndex].id } };
    var tmpR = await self.trademarktransactionDao.updateByWhere(setField, sqlWhere);
    return;
  }
  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 = UtilsTmTaskTradeService;
