const system = require("../../system");
const ServiceBase = require("../sve.base");
const logCtl = system.getObject("web.oplogCtl");
const settings = require("../../../config/settings")
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
class TmFlowService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(TmFlowService));
    this.trademarkDao = system.getObject("db.trademarkDao");
    this.wxSve = system.getObject("service.wxSve");
    this.userDao = system.getObject("db.userDao");
    this.orderDao = system.getObject("db.orderDao");
    this.connectionbhop = system.getObject("db.connectionbehiveop").getConhbOp();
    this.oplogSve = system.getObject("service.oplogSve");
    this.channelApiUrl = settings.channelApiUrl();
    this.execClient = system.getObject("util.execClient");
    this.channelreceiveDao = system.getObject("db.channelreceiveDao");
    this.tm_submit_status = {
        "WAITARTIFICIALEXAMINE": "等待人工审核",
        "1": "商标注册申请书",
        "2": "补证通知",
        "3": "已受理",
        "4": "不予受理",
        "5": "同日申请补送证据",
        "6": "同日申请协商",
        "7": "全部驳回",
        "8": "部分驳回",
        "9": "初步审定公告",
        "10": "商家异议",
        "11": "裁定通知",
        "12": "已下发纸质注册证",
        "13": "已下发注册证",
        "14": "同日申请抽签",
        "15": "申请审查意见",
        "FILELIST": "交文清单",
        "ENVLOPE": "信封正反面",
        "NOTAPPROVAL": "不予核准",
        "APPROVAL": "核准通知",
        "READY": "资料准备",
        "DOCFINISH": "资料齐全",
        "AWAITCHECK": "等待审核",
        "WAITCOMMIT": "待提交",
        "COMMITED": "人工已提交",
        "ROBOT": "已提交",
        "ROBOTPAY": "已提交(待校验)",
        "RECVCOMMIT": "已收提交",
        "FILLEXCEPTION": "填报异常",
        "DISCARDED": "废弃",
        "ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)",
        "REQALIERROR": "阿里接口错误(需峰擎系统处理)",
        "SUBALITM": "已提交阿里(待补全信息)",
        "SUBALITMOK": "已补全信息(待确认商标)",
        "SUBALIPAY": "已提交阿里(待支付)",
        "WAITALIREVIEW": "待阿里审核(已支付)",
        "ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)",
        "ALIAUDITYES": "阿里审核通过",
        "ALIPAYREFUND": "已失败退款(阿里)",
        "ALIPAPERS2": "需要补正(阿里)",
        "ALIPAPERS4": "已补正(阿里)",
        "ALIPAPERS5": "超时未补正(阿里)",
        "ALIPAPERS6": "补正已递交(阿里)",
        //1688
        "WAITCONFIRM":"等待客户确认",
        "CONFIRMFAIL":"方案不通过"
    };
  }
  async getDetailList(pageIndex, pageSize, registNum, proxyCode = null, parentTmRegistNum = null, parentProxyCode = null) {
    // var tmpWhere={where:{[this.db.Op.and]:[{sender:obj.ukstr},{target:obj.extra}]}};
    // var tmpWhere={[this.db.Op.and]:[{tmRegistNum:registNum}]};
    // console.log("SSS-----01==pageIndex="+pageIndex+"，=pageSize"+pageSize+"，registNum="+registNum+"，proxyCode="+proxyCode+"，parentTmRegistNum="+parentTmRegistNum+"，parentProxyCode="+parentProxyCode);
    var self = this;
    var tmpWhere = {};
    var registNumList = [];
    var proxyCodeList = [];
    if (registNum != null && registNum != "") {
      registNumList.push(registNum);
    }
    if (parentTmRegistNum != null && parentTmRegistNum != "") {
      registNumList.push(parentTmRegistNum);
    }
    if (proxyCode != null && proxyCode != "") {
      proxyCodeList.push(proxyCode);
    }
    if (parentProxyCode != null && parentProxyCode != "") {
      proxyCodeList.push(parentProxyCode);
    }
    if (registNumList.length == 0 && proxyCodeList.length == 0) {
      return { code: "-1", msg: "参数有误", data: null };
    }

    if (registNumList.length > 0 && proxyCodeList.length > 0) {
      tmpWhere = { [self.db.Op.or]: [{ tmRegistNum: { [self.db.Op.in]: registNumList } }, { proxyCode: { [self.db.Op.in]: proxyCodeList } }] };
    }
    else if (registNumList.length > 0) {
      tmpWhere.tmRegistNum = { [self.db.Op.in]: registNumList };
    }
    else if (proxyCodeList.length > 0) {
      tmpWhere.proxyCode = { [self.db.Op.in]: proxyCodeList };
    }
    var attributesObj = ["created_at", "tmRegistNum", "tmStatusName", "uploadFileName", "returnReceiptUrl"];
    var result = await self.dao.getPageList(pageIndex, pageSize, tmpWhere, [["id", 'asc']], attributesObj);
    return { code: "1", msg: "ok", data: result };
  }
  async setReturnReceip(user, obj) {
    var self = this;
    const updateFailed = [];//存放失败数据
    for (let i = 0; i < obj.length; i++) {
      var objItem = obj[i];
      var objNameList = objItem.name.split('-');
      if (objNameList.length != 3) {
        updateFailed.push(objItem.name);
        continue;
      }
      var tempStatus = objNameList[2].split('.')[0];
      var countWhere = { where: { [this.dao.db.Op.and]: [{ tmRegistNum: objNameList[0], tmStatus: tempStatus }] } };
      var checkFlow = await this.dao.findCount(countWhere);

      await this.db.transaction(t => {
        let updateUserPromises = []
        if (checkFlow > 0) {
          //商标流程修改
          var putParams = { opAppId: user.app_id, opUserId: user.id, opUserName: user.userName, returnReceiptUrl: objItem.url, uploadFileName: objItem.name, opType: "person" };
          var sqlWheres = { where: { tmRegistNum: objNameList[0], tmStatus: tempStatus } };
          updateUserPromises.push(
            this.dao.updateByWhere(putParams, sqlWheres, t)
          );
        } else {
          //商标流程增加
          updateUserPromises.push(
            this.dao.create({
              opAppId: user.app_id, opUserId: user.id, opUserName: user.userName, tmRegistNum: objNameList[0],
              returnReceiptUrl: objItem.url, uploadFileName: objItem.name, tmStatus: tempStatus, opType: "person"
            }, t)
          );
        }
        //处理商标状态
        var param = { tmStatus: tempStatus };
        var sqlWhere = { where: { tmRegistNum: objNameList[0] } };
        updateUserPromises.push(
          this.trademarkDao.updateByWhere(param, sqlWhere, t)
        );
        return Promise.all(updateUserPromises)
      }).then(function (result) {
        //"success"
      }).catch(function (err) {
        console.log(err)
        updateFailed.push(obj[i].name);
      })

    }
    return { code: "1", msg: "ok", failed: updateFailed };
    var other = {//事务拆分微粒另一种实现
      //事务拆分微粒：
      // const updateResult = [];//存放事务执行结果
      // const updateFailed = [];//存放失败数据
      // const batchAmount=50;//拆分粒度
      // var tmpDate=new Date();
      //  //事务拆分循环
      //  for(let i = 0;i<Math.ceil(obj.lengthtmRegistNum / batchAmount);i++){
      //
      //      await this.db.transaction(t => {
      //        let updateUserPromises = []
      //        for (let j = i * batchAmount; j < (i + 1) * batchAmount && j < obj.length; j++) {
      //            var objItem=obj[j];
      //            var objNameList=objItem.name.split('-');
      //            if(objNameList.length!=3){
      //              updateFailed.push({indextmRegistNum:i,name:objItem.name});
      //              continue;
      //            }
      //
      //            var tempStatus=objNameList[2].split('.')[0];
      //            //商标流程增加
      //            updateUserPromises.push(
      //              this.dao.create({opAppId:user.app_id,opUserId:user.id,opUserName:user.userName,tmRegistNum:objNameList[0],
      //                               returnRtmRegistNumeceiptUrl:objItem.url,tmStatus:tempStatus,opType:"person"},t)
      //            );
      //            //处理商标状态
      //            var param={tmStatus:tempStatus};
      //            var sqlWhere={where:{tmRegistNum:objNameList[0]}};
      //            updateUserPromises.push(
      //              this.trademarkDao.updateByWhere(param,sqlWhere,t)
      //            );
      //
      //        }
      //        console.log("return Promise*******************************************************************************************");
      //        return Promise.all(updateUserPromises)
      //
      //      }).then(function (result) {
      //        updateResult.push({index:i,name:obj[i].name});
      //      }).catch(function (err) {
      //
      //        console.log(err)
      //        updateFailed.push({index:i,name:obj[i].name});
      //      })
      //
      //    }
      //    console.log("完毕=============-----------updateResult------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
      //    console.log(updateResult);
      //    console.log("完毕=============-----------updateFailed------------------>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
      //    console.log(updateFailed);
      //    return 1;
    }
  }

  async setReturnReceip_new(user, obj, officialType) {//采用新的，bysy---2019.07.09
    var official_type = uiconfig.config.pdict.official_type;
    var official_type_name = official_type[officialType];
    if (!official_type_name || official_type_name == "undefined") {
      return { code: "-100", msg: "操作的状态有误", failed: [] };
    }
    var self = this;
    const updateFailed = [];//存放失败数据
    for (let i = 0; i < obj.length; i++) {
      var objItem = obj[i];
      try {
        var fileinfo = objItem.name.split('.');
        if (fileinfo.length != 2) {
          updateFailed.push(objItem.name);
          continue;
        }
        var reg_code = await self.disposeFileName(objItem.name, officialType, official_type_name);
        if (!reg_code) {
          updateFailed.push(objItem.name);
          continue;
        }
        var tm = await self.trademarkDao.model.findOne({
          where: { tmRegistNum: reg_code },
          attributes: ["proxyCode","onlyCode", "applyName", "tmName", "tmSourceType", "tmRegistNum", "nclOneCodes", "tmStatus", "tmStatusName", "channelOrderNum"],
          raw: true
        });
        var fileType = fileinfo[1];
        var fileName = official_type_name + "_" + reg_code;
        var opBeehiveResult = null;
        var opTmResult = null;
        if (!tm) {
          opBeehiveResult = await self.opBeehiveOfficial(self, updateFailed, user, fileName, fileType, objItem, reg_code, officialType, 1);
        } else {
          opTmResult = await self.opZhiChanOfficial(self, tm, user, fileName, fileType, objItem, reg_code, officialType);
          opBeehiveResult = await self.opBeehiveOfficial(self, updateFailed, user, fileName, fileType, objItem, reg_code, officialType, 2);
        }
        var judgeRes=null;
        if(tm){
          judgeRes = self.trademarkDao.judgeTmSourceType(tm.tmSourceType);
        }
        //处理钉钉消息
        if (tm && tm.tmSourceType == '16') {
          if (opTmResult.code == 1) {
            self.pushReceiptDingTalkMsg(tm, official_type_name, opTmResult.isMobileMsg);
          }
        }//16为gsb渠道
        else if (tm && judgeRes) {
          var pushObj={
            channelCode:judgeRes,
            tbCode:tm.proxyCode,
            deliveryOrderNo:tm.channelOrderNum,
            officialType:officialType,
            tmRegistNum:tm.tmRegistNum,
            officialFileName:fileName + "_" + tm.tmName + "_" + tm.nclOneCodes + "." + fileType,
            officialFileUrl:objItem.url,
          };
          if(tm.tmSourceType=="1024" || tm.tmSourceType=="2048" || tm.tmSourceType=="4096" || tm.tmSourceType=="8192"){//center-channel
            var channelPushObj={
              orderNo:tm.channelOrderNum,
              tbCode:tm.proxyCode,
              tmStatus: officialType,
              tmStatusName:this.tm_submit_status[officialType],
              registNumInfo:{
                tmRegistNum: tm.tmRegistNum,//商标申请号
              },
              officialInfo:{//官文信息
                tmRegistNum: tm.tmRegistNum,//商标申请号
                updated: new Date(),// 创建时间  
                uploadFileName:fileName + "_" + tm.tmName + "_" + tm.nclOneCodes + "." + fileType,//上传文件名称
                returnReceiptUrl: objItem.url //官文回执Url  
              }
            };
            self.channelreceiveDao.updateChannelTmStatus(channelPushObj);
          }else{
            self.pushTmOfficialData(pushObj);
          }
          // self.pushTmOfficialData(pushObj);
        }//igirl-channel渠道
        // else if (tm && tm.tmSourceType == '64') {
        //   var pushObj={
        //     channelCode:"1688",
        //     tbCode:tm.proxyCode,
        //     deliveryOrderNo:tm.channelOrderNum,
        //     officialType:officialType,
        //     tmRegistNum:tm.tmRegistNum,
        //     officialFileName:fileName + "_" + tm.tmName + "_" + tm.nclOneCodes + "." + fileType,
        //     officialFileUrl:objItem.url,
        //   };
        //   self.pushTmOfficialData(pushObj);
        // }//64为1688渠道
        // else if (tm && tm.tmSourceType == '128') {
        //   var pushObj={
        //     channelCode:"jd",
        //     tbCode:tm.proxyCode,
        //     deliveryOrderNo:tm.channelOrderNum,
        //     officialType:officialType,
        //     tmRegistNum:tm.tmRegistNum,
        //     officialFileName:fileName + "_" + tm.tmName + "_" + tm.nclOneCodes + "." + fileType,
        //     officialFileUrl:objItem.url,
        //   };
        //   self.pushTmOfficialData(pushObj);
        // }//128为jd渠道
        else {
          if (opBeehiveResult.code == 1) {
            self.opBeehiveSendMsg(opBeehiveResult.data, reg_code, official_type_name, opBeehiveResult.isMobileMsg);
          }
        }
      } catch (e) {
        updateFailed.push(objItem.name);
        //日志记录
        logCtl.error({
          optitle: "峰擎更新上传官文处理异常error,文件名为：" + objItem.name,
          op: "/fqboss/app/base/service/impl/tmflowSve.js/setReturnReceip_new",
          content: e.stack,
          clientIp: ""
        });
      }
    }
    return { code: "1", msg: "ok", failed: updateFailed };
  }
  async disposeFileName(fileName, officialType, official_type_name) {
    if (officialType == "1") {
      if (fileName.indexOf("TMZC") < 0) {
        return "";
      }
      return fileName.substring(4, fileName.length).split('.')[0];
    }//商标注册申请书
    else if (officialType == "13") {
      if (fileName.indexOf("商标注册证") < 0) {
        return "";
      }
    }//电子版商标注册证
    else if (officialType == "12" || officialType == "10" || officialType == "FILELIST" || officialType == "ENVLOPE" || officialType == "NOTAPPROVAL" || officialType == "APPROVAL") {
      return fileName.split('.')[0];
    }// "12": "纸质版商标注册证","10": "商标异议答辩通知书","FILELIST": "交文清单",
    // "ENVLOPE": "信封正反面", "NOTAPPROVAL": "不予核准", "APPROVAL": "核准通知"//这六个文件名为商标号
    else if (fileName.indexOf(official_type_name) < 0) {
      return "";
    }
    var fileNameList = fileName.split('_');
    if (fileNameList.length != 3) {
      return "";
    }
    return fileNameList[1];
  }
  //----------------------ZhiChan-------------start-------------------------------------------
  async opZhiChanOfficial(self, tm, user, fileName, fileType, objItem, reg_code, officialType) {
    //默认失败
    var opResult = { code: -1, data: null, isMobileMsg: 0 };
    fileName = fileName + "_" + tm.tmName + "_" + tm.nclOneCodes + "." + fileType;
    var flowWhere = { where: { tmRegistNum: reg_code, tmStatus: officialType } };
    var flowCount = await this.dao.findCount(flowWhere);
    //获取tmFlow中回执的最新时间
    let lastUp = await this.getLastUpFromTmFlow(reg_code);
    await this.db.transaction(async function (t) {
      var params = {
        opAppId: user.app_id,
        opUserId: user.id,
        tmStatus: officialType,
        uploadFileName: fileName,
        returnReceiptUrl: objItem.url,
        tmRegistNum: reg_code,
      };
      if (tm.tmStatus != officialType) {
        var param = { tmStatus: officialType };
        param.isPushed = 0;  //tm状态更新
        param.lastUp = lastUp; //回执最后更新时间
        self.trademarkDao.updateByWhere(param, { where: { tmRegistNum: reg_code } }, t);
      }
      if (flowCount > 0) {
        params.isPushed=0;  //官文信息更新的时候tm状态也会更新
        params.lastUp = lastUp; //回执最后更新时间
        self.updateByWhere(params, flowWhere, t);
      } else {
        opResult.isMobileMsg = 1;
        self.dao.create(params, t);
      }
    });
    opResult.code = 1;
    return opResult;
  }
  //微信服务号通知
  async pushReceiptMessage(tmRegistNum) {
    // async pushMessage(){
    // var appobj=await this.cacheManager["AppCache"].cacheApp("wx4c91e81bbb6039cd");
    var tm = await this.trademarkDao.model.findOne({ where: { tmRegistNum: tmRegistNum }, attributes: ["onlyCode", "applyName", "tmName", "tmRegistNum", "nclOneCodes", "tmStatusName"], raw: true });
    var order = await this.orderDao.model.findOne({ where: { orderNum: tm.orderNum }, attributes: ["payUserId", "payAppId"], raw: true });
    var user = await this.userDao.model.findOne({ where: { id: order.payUserId }, attributes: ["openId", "app_id"] });
    if (tm && user) {
      // console.log(date);
      var data = {
        first: { value: tm.applyName + " 您的商标办理进度已更新，请点击查看" },
        keyword1: { value: "商标注册 \n商标名称:" + tm.tmName + " \n注册号：" + tm.tmRegistNum + " \n国际分类：" + tm.nclOneCodes },
        keyword2: { value: tm.tmStatusName }
      };
      //var appkey=user.getApp();
      var appkey = "wx4c91e81bbb6039cd";
      var a = await this.wxSve.sendTmplMsg(user.openId, "VeqWpbYKzdVvtcJoa5JGcWWK_Hl7qoHCxk25KhIxklo", "https://boss.gongsibao.com/mobile#/products/mobiletmlist?from=mobile", data, appkey);
      return a;
    }
  }
  async pushReceiptDingTalkMsg(tm, official_type_name, isMobileMsg) {
    if (tm && tm.channelOrderNum) {
      var msg = "商标名称:" + tm.tmName + " \n注册号：" + tm.tmRegistNum + " \n国际分类：" + tm.nclOneCodes +
        " \n上传了【" + official_type_name + "】的回执文件，请到【峰擎系统】中查看";
      var obj = {
        content: msg,
        send_msg: "",
        is_send: -1,
        order_no: tm.channelOrderNum
      };
      if (isMobileMsg == 1) {
        obj.send_msg = "您的商标“" + tm.tmName + "”第" +
          tm.nclOneCodes + "类，申请号" + tm.tmRegistNum + "，已收到官方下发的" + official_type_name + "，请联系您的知产顾问，订单" + tm.channelOrderNum + "。";
        obj.is_send = isMobileMsg;
      }
      this.notifyDingTalkMsg(obj);
    }
  }
  //----------------------ZhiChan-------------end---------------------------------------------

  //-------------------------------------------------------Beehive---------start--------------
  async opBeehiveOfficial(self, updateFailed, user, fileName, fileType, objItem, reg_code, officialType, opType) {
    //默认失败
    var opResult = { code: -1, data: null, isMobileMsg: 0 };
    var tmList = null;//await this.connectionbhop.query("SELECT id,momo,nclone_id,mark_state,trade_mark_caseid FROM `ig_trade_mark` WHERE `code`='" + reg_code + "' LIMIT 1");
    if (tmList && tmList[0, 0].length > 0) {
      var tmItem = tmList[0, 0][0];
      opResult.code = 1;
      opResult.data = tmItem;
      fileName = fileName + "_" + tmItem.momo + "_" + tmItem.nclone_id + "." + fileType;
      var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
      var getTmStatus = await self.getBeehiveStatus(officialType);
      if (tmItem.mark_state != getTmStatus || getTmStatus == 10) {
        var tmOpSql = "UPDATE `ig_trade_mark` SET `mark_state`=" + getTmStatus + ",`updator_id`=1825,`updator`='刘江涛',`update_time`='" + nowTimeStr + "' WHERE id=" + tmItem.id;
        await self.connectionbhop.query(tmOpSql);
      }
      var tmFlowList = await this.connectionbhop.query("SELECT id FROM sys_attachment WHERE `foreign_key`=" + tmItem.id + " and `name`='" + fileName + "'");
      var opSql = "";
      if (tmFlowList && tmFlowList[0, 0].length > 0) {
        var tmFlowItem = tmFlowList[0, 0][0];
        opSql = "UPDATE `sys_attachment` SET `path`='" + objItem.url + "',`updator_id`=1825,`updator`='刘江涛',`update_time`='" + nowTimeStr + "' WHERE id=" + tmFlowItem.id;
      } else {
        opResult.isMobileMsg = 1;
        opSql = "INSERT INTO `gsb`.`sys_attachment` (" +
          "`path`,`entity_id`,`view_count`,`downLoad_count`,`foreign_key`,`name`,`creator_id`,`creator`,`create_time`" +
          ")VALUES('" +
          objItem.url + "'," +
          "'com.gongsibao.entity.igirl.tm.TradeMark'," +
          0 + "," +
          0 + "," +
          tmItem.id + ",'" +
          fileName + "'," +
          1825 + "," +
          "'刘江涛','" +
          nowTimeStr +
          "')";
      }
      await self.connectionbhop.query(opSql);
    } else {
      if (opType == 1) {
        updateFailed.push(objItem.name);
      }
    }
    return opResult;
  }
  async opBeehiveSendMsg(tmItem, reg_code, official_type_name, isMobileMsg) {
    if (tmItem && tmItem.trade_mark_caseid) {
      var tmCaseList = await this.connectionbhop.query("SELECT id,mobile,contact_name,owner_id FROM `ig_trade_mark_case` WHERE id='" + tmItem.trade_mark_caseid + "' LIMIT 1");
      if (tmCaseList && tmCaseList[0, 0].length > 0) {
        var tmCaseItem = tmCaseList[0, 0][0];
        if (tmCaseItem && tmCaseItem.mobile && tmCaseItem.mobile.length == 11) {
          var msg = "商标名称:" + tmItem.momo + " \n注册号：" + reg_code + " \n国际分类：" + tmItem.nclone_id +
            " \n上传了【" + official_type_name + "】的回执文件，请到【beehive系统】中查看";
          var obj = {
            content: msg,
            send_msg: "",
            is_send: -1,
            op_type: 2,
            customer_mobile: "",
            order_no: tmCaseItem.mobile
          };
          if (isMobileMsg == 1 && tmCaseItem.owner_id) {
            var employeeList = await this.connectionbhop.query("SELECT id,mobile FROM `sys_permission_employee` WHERE id='" + tmCaseItem.owner_id + "' LIMIT 1");
            if (employeeList && employeeList[0, 0].length > 0) {
              var employeeItem = employeeList[0, 0][0];
              if (employeeItem && employeeItem.mobile && employeeItem.mobile.length == 11) {
                obj.is_send = isMobileMsg;
                obj.customer_mobile = employeeItem.mobile;
                obj.send_msg = "您的商标“" + tmItem.momo + "”第" + tmItem.nclone_id + "类，申请号" + reg_code +
                  "，已收到官方下发的" + official_type_name + "，请联系您的知产顾问。";
              }
            }
          }
          this.notifyDingTalkMsg(obj);
        }
      }
    }
  }
  async getBeehiveStatus(officialType) {
    var status = 0;
    switch (officialType) {
      case 'READY':
        status = 0; break;
      case 'DOCFINISH':
        status = 1; break;
      case "WAITCOMMIT":
        status = 2; break;
      case 'COMMITED':
        status = 3; break;
      case 'RECVCOMMIT':
        status = 4; break;
      case '1':
        status = 4; break;
      case '3':
        status = 5; break;
      case '8':
        status = 6; break;
      case '7':
        status = 7; break;
      case '10':
        status = 8; break;
      case 'ROBOT':
        status = 9; break;
      case '12'://纸质版商标注册证
        status = 10; break;
      case '13'://电子版商标注册证
        status = 10; break;
      case 'FILLEXCEPTION':
        status = 11; break;
      case 'FILELIST':
        status = 12; break;
      case '4':
        status = 13; break;
      case 'ENVLOPE':
        status = 14; break;
      case '2':
        status = 15; break;
      case '9':
        status = 16; break;
      case '11':
        status = 17; break;
      case 'NOTAPPROVAL':
        status = 18; break;
      case 'APPROVAL':
        status = 19; break;
      case '6':
        status = 20; break;
      case '5':
        status = 21; break;
      default:
        status = 21; break;
        break;
    }
    return status;
  }
  //-------------------------------------------------------Beehive--------end---------------
  //---------------------------------推送渠道商标回执数据 开始-------------------------------------------------------------
  async getToken(channelCode) {
    var self = this;
    var token = "";
    var channelApiUrl = this.channelApiUrl;
    if(channelCode){
      channelApiUrl = settings.channelApiUrl(channelCode);
    }
    var reqTokenUrl = channelApiUrl + "/auth/accessAuth/getToken";
    try {
      var reqParam = {};
      reqParam = {
        "appkey":"201911131657",
        "secret":"eeb18393aade40149287b024d8ba0850"
      };
      if(channelCode=="jd"){
        reqParam = {
          "appkey":"201911251551",
          "secret":"56006077354d48858026c80c0e10bef6"
        };
      }
      var rtn = await this.execClient.execPost(reqParam, reqTokenUrl);
      if (!rtn.stdout) {
        return {status:-1, msg:"获取token失败"};
      }
      var tokenResult = JSON.parse(rtn.stdout);
      if (tokenResult.status == 0) {
        tokenResult.data.secret = reqParam.secret;
      }
      return tokenResult;
    } catch (e) {
      await this.oplogSve.createDb({
        logLevel:"error",
        optitle: "获取token---异常",
        op: reqTokenUrl,
        content: JSON.stringify(e.stack),
        clientIp: ""
      });
      return {status:-1, msg:"获取token失败"};
    }
    
  }
  //推送渠道商标回执数据
  async pushTmOfficialData(obj){
    try {
      var tbCode = obj.tbCode;
      var channelCode = obj.channelCode;
      var officialType = obj.officialType;
      var deliveryOrderNo = obj.deliveryOrderNo;
      if(!tbCode){
        return {code:-100,msg:"tbCode参数错误"};
      }
      var judgeRes = this.trademarkDao.judgeChannelCode(channelCode);
      if(!judgeRes){
        return {code:-101,msg:"channelCode参数错误"};
      }
      // if(!channelCode || (channelCode!="1688" && channelCode!="jd" )){
      //   return {code:-101,msg:"channelCode参数错误"};
      // }
      if(!officialType){
        return {code:-102,msg:"officialType参数错误"};
      }
      if(!deliveryOrderNo){
        return {code:-103,msg:"deliveryOrderNo参数错误"};
      }
      var token = await this.getToken(channelCode);
      if(!token || token.status!=0){
        await this.oplogSve.createDb({
          logLevel:"error",
          optitle: "推送渠道辅助注册商标数据---获取token失败",
          op: "tmflowSve/pushTmOfficialData",
          content: JSON.stringify(token),
          clientIp: ""
        });
        return {code:-104,msg:"获取token失败"};
      }
      var channelApiUrl = this.channelApiUrl;
      if(channelCode){
        channelApiUrl = settings.channelApiUrl(channelCode);
      }
      var reqUrl = channelApiUrl + "/action/receiveData/springBoard";
      var reqObj={
        "actionBody":obj,
        "actionType":"receiveTmOfficialData",
        "actionProcess": channelCode,
      };
      var rc = system.getObject("util.execClient");
      var rtn = await rc.execPostTK(reqObj, reqUrl,token.data.token);
      if(rtn.status==0){
        await this.oplogSve.createDb({
          logLevel:"info",
          optitle: "推送渠道商标回执数据---成功",
          op: reqUrl,
          content: JSON.stringify(reqObj),
          resultinfo: JSON.stringify(rtn),
          clientIp: ""
        });
      }else{
        await this.oplogSve.createDb({
          logLevel:"error",
          optitle: "推送渠道商标回执数据---失败",
          op: reqUrl,
          content: JSON.stringify(reqObj),
          resultinfo: JSON.stringify(rtn),
          clientIp: ""
        });
        return {code:-200};
      }
      return {code:1};
    } catch (e) {
      await this.oplogSve.createDb({
        logLevel:"error",
        optitle: "推送渠道商标回执数据---异常",
        op: "tmflowSve/pushTmOfficialData",
        content: JSON.stringify(e.stack),
        clientIp: ""
      });
      return {code:-400,msg:"操作失败",err:e.stack};
    }
  }
  //----------------------------------推送渠道商标回执数据 结束----------------------------------------------------------------
  async getLastUpFromTmFlow(tmRegistNum){
      let sql = "SELECT MAX(created_at) FROM `h_tm_flow` WHERE tmRegistNum='" + tmRegistNum +"';";
      let maxCreateTime = await this.dao.customQuery(sql);
      let lastTime = maxCreateTime[0]['MAX(created_at)'];
      console.log('lastTime--------', lastTime);
      return lastTime;
  }
}
module.exports = TmFlowService;
// var task=new TmFlowService();
// task.pushMessage().then(function(result){
//   console.log(result);
// }).catch(function(e){
//   console.log(e);
// });
