var System = require("../../system");
const logCtl = System.getObject("web.oplogCtl");
const trademarkCtl = System.getObject("web.trademarkCtl");
const settings = require("../../../config/settings");
const md5 = require("MD5");
class TmSub {
  constructor() {
    this.cacheManager = System.getObject("db.cacheManager");
    this.trademarkS = System.getObject("service.trademarkSve");
    this.oplogSve = System.getObject("service.oplogSve");
  }
  async checkKey(appKey) {
    let key = await this.cacheManager["InitAppKeyCache"].getAppKeyVal(appKey);
    if (key == null) {
      return { code: -1, message: "请检查您的授权KEY", data: null };
    }
    // if(obj.companyName.replace(/(^s*)|(s*$)/g, "").length ==0)
    // {
    //  return System.getResult2(null,null,"ok","请输入要查询的公司名");
    // }
  }
  async autosub(obj) {//提报数据
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    //keyCode列表，以,隔开
    var keyCodeList = obj.keyCodeList == null ? "" : obj.keyCodeList;
    if (keyCodeList == "") {
      return { code: -1, message: "keyCodeList不能为空", data: null };
    }
    //当前key码
    var keyCode = obj.keyCode == null ? "" : obj.keyCode;
    if (keyCode == "") {
      return { code: -1, message: "keyCode不能为空", data: null };
    }
    try {
      var tmpResult = await this.trademarkS.getAutoSubList(keyCodeList, keyCode);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "提报数据异常",
        op: "base/api/impl/tmsub/autosub",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "TmSub异常", data: [] };
    }
  }
  //机器人提报更新提报错误----暂停使用
  async updateErrorCount(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    //提报号
    var proxyCode = obj.proxyCode == null ? "" : obj.proxyCode;;
    if (proxyCode == "") {
      return { code: -1, message: "proxyCode不能为空", data: null };
    }
    //错误次数
    var errorCount = obj.errorCount == null ? 1 : obj.errorCount;
    //key码-redis用
    var keyCode = obj.keyCode == null ? "" : obj.keyCode;
    if (keyCode == "") {
      return { code: -1, message: "keyCode不能为空", data: null };
    }
    try {
      var tmpResult = await this.trademarkS.setUpdateErrorCount(proxyCode, errorCount, keyCode);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "机器人提报更新提报错误异常",
        op: "base/api/impl/tmsub/updateErrorCount",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "updateErrorCount异常", data: null };
    }
  }
  //修改商标提报缓存数据
  async putCacheData(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    //提报号
    var proxyCode = obj.proxyCode == null ? "" : obj.proxyCode;
    if (proxyCode == "") {
      return { code: -1, message: "proxyCode不能为空", data: null };
    }
    //key码-redis用
    var keyCode = obj.keyCode == null ? "" : obj.keyCode;
    if (keyCode == "") {
      return { code: -1, message: "keyCode不能为空", data: null };
    }

    try {
      var tmpResult = await this.trademarkS.updateTmCache(proxyCode, keyCode);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "机器人修改商标提报缓存数据异常",
        op: "base/api/impl/tmsub/putCacheData",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "putCacheData异常", data: null };
    }
  }
  //机器人提报更新商标状态
  async updateState(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    //提报号
    var proxyCode = obj.proxyCode == null ? "" : obj.proxyCode;
    if (proxyCode == "") {
      return { code: -1, message: "proxyCode不能为空", data: null };
    }
    var errorCount = obj.errorCount == null ? 0 : obj.errorCount;
    //商标状态枚举,传递枚举值
    var stateCode = obj.stateCode == null ? "" : obj.stateCode;
    if (stateCode == "") {
      return { code: -1, message: "stateCode不能为空", data: null };
    }
    //key码-redis用
    var keyCode = obj.keyCode == null ? "" : obj.keyCode;
    if (keyCode == "") {
      return { code: -1, message: "keyCode不能为空", data: null };
    }

    try {
      var tmpResult = await this.trademarkS.setUpdateState(proxyCode, errorCount, stateCode, keyCode, obj.errorMsg);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "机器人提报更新商标状态异常",
        op: "base/api/impl/tmsub/updateState",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "updateState异常", data: null };
    }
  }
  //更新商标code和状态
  async updateTradeMarkCode(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    //提报号
    var proxyCode = obj.proxyCode == null ? "" : obj.proxyCode;
    if (proxyCode == "") {
      return { code: -1, message: "proxyCode不能为空", data: null };
    }
    //商标号
    var code = obj.code == null ? "" : obj.code;
    if (code == "") {
      return { code: -1, message: "code不能为空", data: null };
    }
    //商标状态枚举,传递枚举值
    var stateCode = obj.stateCode == null ? "" : obj.stateCode;
    if (stateCode == "") {
      return { code: -1, message: "stateCode不能为空", data: null };
    }

    try {
      var tmpResult = await this.trademarkS.setUpdateTradeMarkCode(proxyCode, code, stateCode);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "更新商标code和状态异常",
        op: "base/api/impl/tmsub/updateTradeMarkCode",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "updateTradeMarkCode异常", data: null };
    }
  }

  //用于fq调用，更改商标的支付状态
  async putTmChannelPay(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return { code: -1, message: "appKey参数错误", data: null };
    }
    var orderNum = obj.orderNum || "";
    if (!orderNum) {
      return { code: -1, message: "orderNum不能为空", data: null };
    }
    var channelPayStatus = obj.channelPayStatus || "yzf";
    try {
      //日志记录
      logCtl.info({
        optitle: "fq调用，更改商标的支付状态参数",
        op: "base/api/impl/tmsub/putTmChannelPay",
        content: "orderNum=" + orderNum + "，channelPayStatus=" + channelPayStatus,
        clientIp: ""
      });
      var tmpResult = await this.trademarkS.putChannelPayStatus(orderNum, channelPayStatus);
      return tmpResult;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "fq调用，更改商标的支付状态异常",
        op: "base/api/impl/tmsub/putTmChannelPay",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "putTmChannelPay异常", data: null };
    }
  }

  async channelTmNotify(pobj) {//渠道通知商标状态
    // {
    //   "actionProcess": "AliTm",
    //     "appcode": "100099",
    //       "sign": "XXX",
    //         "actionBody": {

    //   }
    // }
    logCtl.info({
      optitle: "渠道通知商标状态参数---info",
      op: "base/api/impl/tmsub/channelTmNotify",
      content: JSON.stringify(pobj),
      clientIp: ""
    });
    var result = { code: 1, msg: "SUCCESS" };
    try {
      var appCode = pobj.appCode || "";//应用编码
      var actionProcess = pobj.actionProcess || "";//作业方
      var sign = pobj.sign || "";//签名信息
      if (!appCode) {
        result.code = -100;
        result.message = "appCode参数错误";
        return result;
      }
      if (!actionProcess) {
        result.code = -110;
        result.message = "actionProcess参数错误";
        return result;
      }
      if (!sign) {
        result.code = -105;
        result.message = "sign参数错误";
        return result;
      }
      let applistCache = await this.cacheManager["ApplistCache"].getListByCache();
      if (applistCache == null || applistCache == "" || applistCache == "undefined") {
        result.code = -110;
        result.message = "缓存app数据有误";
        return result;
      }
      let appList = JSON.parse(applistCache);
      if (appList == null || appList.length == 0) {
        result.code = -120;
        result.message = "缓存app数据有误！！";
        return result;
      }
      var newList = appCode && sign ? appList.filter(item => item.app_code == appCode)
        : appList.filter(item => item.app_code == appCode);//没有签名则用渠道自动提报

      if (newList == null || newList.length == 0) {
        result.code = -130;
        result.message = "通过缓存获取app数据有误";
        return result;
      }
      let appItem = newList[0];
      if (appCode && sign) { // 验证签名
        var signResult = await this.paramsSign(sign, pobj.actionBody, appItem.secret);
        if (signResult.code != 1) {
          result.code = -140;
          result.message = "签名错误，请重试";
          return result;
        }
      }
      if (actionProcess == "AliTm") {
        var reqUrl = settings.channelApiUrl(actionProcess) + "/api/auth/accessAuth/getAppTokenByHosts";
        var reqParam = {
          "actionType": "getAppTokenByHosts",
          "actionBody": {}
        };
        var rc = System.getObject("util.execClient");
        var tokenReqResult = await rc.execPost(reqParam, reqUrl);
        if (!tokenReqResult || !tokenReqResult.stdout) {
          result.code = -150;
        }
        var tokenResult = JSON.parse(tokenReqResult.stdout);
        if (tokenResult.status != 0) {
          result.code = -150;
        }
        if (result.code == -150) {
          var opResult = await this.opAliNotify(pobj.actionBody);
          if (opResult.code != 1) {
            logCtl.info({
              logLevel: "error",
              optitle: "fq渠道商标状态通知处理异常---error",
              op: "base/api/impl/tmsub/channelTmNotify",
              content: "参数：" + JSON.stringify(pobj) + "，返回结果：" + JSON.stringify(opResult),
              clientIp: ""
            });
            result.msg = "渠道商标状态通知异常";
            result.message = "渠道商标状态通知异常";
            return result;
          }
        }
        reqUrl = settings.channelApiUrl(actionProcess) + "/api/action/tmTransaction/springBoard";
        reqParam.actionType = "addPushContent";
        reqParam.actionBody = {
          pushUrl: settings.pushFqBossAliTmNotify(),
          pushContent: pobj,
        };
        await rc.execPostTK(reqParam, reqUrl, tokenResult.data.token);
      }
      return result;
    } catch (e) {
      logCtl.error({
        optitle: "fq渠道商标状态通知异常---error",
        op: "base/api/impl/tmsub/channelTmNotify",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.msg = "渠道商标状态通知异常：" + e.stack;
    }
    return result;
  }
  async channelTmNotifyByAli(pobj) {//渠道通知商标状态-用于阿里   
    logCtl.info({
      optitle: "渠道通知商标状态参数用于阿里---info",
      op: "base/api/impl/tmsub/channelTmNotify",
      content: JSON.stringify(pobj),
      clientIp: ""
    });
    var result = { code: 1, msg: "SUCCESS" };
    try {
      var actionProcess = pobj.actionProcess || "";//作业方
      if (actionProcess == "AliTm") {
        var opResult = await this.opAliNotify(pobj.actionBody);
        if (opResult.code != 1) {
          logCtl.info({
            logLevel: "error",
            optitle: "fq渠道商标状态通知处理用于阿里---error",
            op: "base/api/impl/tmsub/channelTmNotify",
            content: "参数：" + JSON.stringify(pobj) + "，返回结果：" + JSON.stringify(opResult),
            clientIp: ""
          });
          result.code = -150;
          result.status = -150;
          result.msg = "渠道商标状态通知异常用于阿里，返回结果：" + JSON.stringify(opResult);
          result.message = "渠道商标状态通知异常用于阿里";
          return result;
        }
        result.status = 0;
      }
      return result;
    } catch (e) {
      logCtl.error({
        optitle: "fq渠道商标状态通知异常用于阿里---error",
        op: "base/api/impl/tmsub/channelTmNotify",
        content: e.stack,
        clientIp: ""
      });
      result.code = -200;
      result.msg = "渠道商标状态通知异常用于阿里：" + e.stack;
    }
    return result;
  }
  async paramsSign(sign, pobj, app_key) {//进行验签校验
    var rtnResult = { code: 1, msg: "SUCCESS" };
    if (!pobj) {
      rtnResult.code = -310;
      rtnResult.msg = "请求参数为空";
      return rtnResult;
    }
    var signArr = [];
    var keys = Object.keys(pobj).sort();
    if (keys.length == 0) {
      rtnResult.code = -330;
      rtnResult.msg = "请求参数信息为空";
      return rtnResult;
    }
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (tKey != "sign" && pobj[tKey]) {
        signArr.push(tKey + "=" + pobj[tKey]);
      }
    }
    if (signArr.length == 0) {
      rtnResult.code = -350;
      rtnResult.msg = "请求参数组装签名参数信息为空";
      return rtnResult;
    }
    var resultSignStr = signArr.join("&") + "&key=" + app_key;
    var resultTmpSign = md5(resultSignStr).toUpperCase();
    if (sign != resultTmpSign) {
      rtnResult.code = -380;
      rtnResult.msg = "返回值签名验证失败";
      return rtnResult;
    }
    return rtnResult;
  }
  async opAliNotify(pobj) {
    var result = { code: -600, msg: "opAliNotify操作" };
    var self = this;
    if (pobj.supplementStatus) {
      switch (pobj.supplementStatus) {
        case "2":
          result = await self.trademarkS.opAliNotify(null, "ALIPAPERS2", pobj);
          break;
        case "4":
          result = await self.trademarkS.opAliNotify(null, "ALIPAPERS4", pobj);
          break;
        case "5":
          result = await self.trademarkS.opAliNotify(null, "ALIPAPERS5", pobj);
          break;
        case "6":
          result = await self.trademarkS.opAliNotify(null, "ALIPAPERS6", pobj);
          break;
        default:
          break;
      }
    } else {
      switch (pobj.status) {
        case "0"://-已⽀付-----待阿里审核(已支付)
          result = await self.trademarkS.opAliNotify(pobj.status, "WAITALIREVIEW", pobj);
          break;
        case "2"://阿里云审不通过
          result = await self.trademarkS.opAliNotify(null, "ALIAUDITNOT", pobj);
          break;
        case "3"://阿里审核通过
          result = await self.trademarkS.opAliNotify(null, "ALIAUDITYES", pobj);
          break;
        case "4"://已失败退款(阿里)
          result = await self.trademarkS.opAliNotify(null, "ALIPAYREFUND", pobj);
          break;
        case "20"://-已提交到商标局
          result = await self.trademarkS.opAliNotify(null, "ROBOT", pobj);
          break;
        case "21"://商标局已接受（⽂件：商标局回执）
          result = await self.trademarkS.opAliNotify(null, "RECVCOMMIT", pobj);
          break;
        case "22"://商标局不予受理 （⽂件：不予受理通知书）
          result = await self.trademarkS.opAliNotify(null, "4", pobj);
          break;
        case "23"://商标局受理通过（⽂件：受理通知书）
          result = await self.trademarkS.opAliNotify(null, "3", pobj);
          break;
        case "29"://-商标局部分驳回 （⽂件：部分驳回通知书）
          result = await self.trademarkS.opAliNotify(null, "8", pobj);
          break;
        case "30"://商标局驳回 （⽂件：驳回通知书）
          result = await self.trademarkS.opAliNotify(null, "7", pobj);
          break;
        case "31"://商标局审核通过 （⽂件：审核通过通知书）----初步审定公告
          result = await self.trademarkS.opAliNotify(null, "9", pobj);
          break;
        case "99"://申请成功结束 （⽂件：商标证通知书）---已下发商标注册证
          result = await self.trademarkS.opAliNotify(null, "13", pobj);
          break;
        case "888"://阿里客户有反馈，需求被驳回
          result = await self.trademarkS.opAliUseRticklingNotify(null, "ALICUSTOMERREJECTED", pobj);
          break;
        case "999"://关闭需求
          result = await self.trademarkS.opAliUseRticklingNotify(null, "DISCARDED", pobj);
          break;
        default:
          break;
      }
    }
    return result;
  }

  //**********批量更新支付状态---开始 */
  async fqPutPayStatus(obj) {
    if (!obj.appKey1 || obj.appKey1 != "a95ad36efc064343aff200d18be6637d_lmh") {
      return { code: -1, message: "appKey参数错误", data: null };
    }
    var qihao = obj.qihao || 1;
    if (!qihao) {
      return { code: -1, message: "qihao不能为空", data: null };
    }
    try {
      //根据期号拿到商标列表
      var sql = "SELECT f.order_no FROM fq_put_pay AS f WHERE f.qihao = '" + qihao + "'";
      var lists = await this.trademarkS.dao.customQuery(sql);
      var orderNumList = [];
      //将符合条件的商标号添加到数组orderNum
      for (var i = 0; i < lists.length; i++) {
        if (lists[i].order_no) {
          var channelorder = await trademarkCtl.getChannelOrderByOrderNumAliDataSync({ channelOrderNum: lists[i].order_no });
          if (channelorder.code == 1 && channelorder.data.order_pay_state && channelorder.data.order_pay_state == "已付清") {
            orderNumList.push(lists[i].order_no);
          }
        }
      }
      if (orderNumList.length > 0) {
        //批量更改orderNum
        var sql2 = "UPDATE h_trade_mark AS t SET t.channelPayStatus='yzf',t.channelPayStatusName='已支付' WHERE t.channelOrderNum IN (" + orderNumList.join(",") + ")";
        await this.trademarkS.dao.customExecAddOrPutSql(sql2);
        return { code: 200, message: "状态修改成功", data: null };
      }
      return { code: 200, message: "暂时没有查询出已付款的数据", data: null };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "状态修改异常---error",
        op: "base/api/impl/tmsub/fqPutPayStatus",
        content: e.stack,
        clientIp: ""
      });
    }
  }
  async queryAliTmStatus(obj) {
    var data = await this.checkKey(obj.appKey);
    if (data && data.code && data.code == -1) {
      return data;
    }
    if (!obj.methodType) {
      return { code: -1, message: "methodType不能为空", data: null };
    }
    if (!obj.body) {
      return { code: -1, message: "body不能为空", data: null };
    }
    var rc = System.getObject("util.aliyunClient");
    try {
      var submitTm = await rc.post(obj.methodType, obj.body);
      return { code: 200, message: "ok", data: submitTm };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "查询阿里商标状态异常---error",
        op: "base/api/impl/tmsub/queryAliTmStatus",
        content: e.stack,
        clientIp: ""
      });
    }
  }
  //**********批量更新支付状态---结束 */

  //根据渠道订单号获取申请人信息（渠道订单号非渠道交付单号）
  async getApplyNameByChannelOrderNo(pobj){
    try {
      var result = await this.trademarkS.getApplyNameByChannelOrderNo(pobj);
      return result;
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "根据渠道订单号获取申请人信息异常---error",
        op: "base/api/impl/tmsub/getApplyNameByChannelOrderNo",
        content: e.stack,
        clientIp: ""
      });
      return {code:-200,err:e.stack};
    }
  }
}
module.exports = TmSub;
