const system = require("../../system");
const ServiceBase = require("../sve.base");
const settings = require("../../../config/settings");
const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
const logCtl = system.getObject("web.oplogCtl");
const uuidv4 = require('uuid/v4');
const fs = require("fs");

class TrademarkService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(TrademarkService));
    this.orderDao = system.getObject("db.orderDao");
    this.calcDao = system.getObject("db.calculatepriceDao");
    this.tmapplierinfoDao = system.getObject("db.tmapplierinfoDao");
    this.trademarkDao = system.getObject("db.trademarkDao");
    this.tmcustomerinfoDao = system.getObject("db.tmcustomerinfoDao");
    this.tmflowDao = system.getObject("db.tmflowDao");
    this.connectionbh = system.getObject("db.connection").getConhb();
    this.userDao = system.getObject("db.userDao");
    this.restClient = system.getObject("util.restClient");
    this.ossClient = system.getObject("util.ossClient");
    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": "方案不通过"
    };
  }

  //获取提包的缓存key
  async getTbCacheKey(key) {
    return "tbKey_" + key;
  }
  async getTbCacheKeyKeyAllotData(key) {
    return "tbKeyAllotData_" + key;
  }
  async findAndCountAll(obj) {
    var apps = await this.dao.findAndCountAll(obj);
    var rows = apps.rows;
    var count = rows.length;
    var dataList = [];//type=1为申请人信息,2为联系人信息
    for (var i = 0; i < count; i++) {
      if (rows[i].dataValues.orderNum != "" && rows[i].dataValues.orderNum != null) {
        //处理申请人信息
        var applierFilterList = dataList.filter(f => f.orderNum == rows[i].dataValues.orderNum && f.type == 1);
        if (applierFilterList && applierFilterList.length > 0) {
          apps.rows[i].dataValues.applier = applierFilterList[0].data;
        } else {
          var applier = await this.tmapplierinfoDao.findItemByOrderNum(rows[i].dataValues.orderNum);
          if (applier) {
            dataList.push({
              orderNum: rows[i].dataValues.orderNum,
              type: 1,
              data: applier
            });
            apps.rows[i].dataValues.applier = applier;
          }
        }
        //处理联系人信息
        var tmcustomerFilterList = dataList.filter(f => f.orderNum == rows[i].dataValues.orderNum && f.type == 2);
        if (tmcustomerFilterList && tmcustomerFilterList.length > 0) {
          apps.rows[i].dataValues.tmcustomer = tmcustomerFilterList[0].data;
        } else {
          var tmcustomerItem = await this.tmcustomerinfoDao.findItemByOrderNum(rows[i].dataValues.orderNum);
          if (tmcustomerItem) {
            dataList.push({
              orderNum: rows[i].dataValues.orderNum,
              type: 2,
              data: tmcustomerItem
            });
            apps.rows[i].dataValues.tmcustomer = tmcustomerItem;
          }
        }
      }
    }
    return apps;
  }

  async getAutoSubList(keyCodeList, keyCode) {
    //通过数据key获取数据
    var datakey = await this.getTbCacheKey(keyCode);
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(datakey);
    if (tbDataList && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      return { code: 200, message: "获取数据成功！", data: tmpResult };
    }
    //通过缓存中key的分页数据获取提报数据
    var allotKeyData = await this.getTbCacheKeyKeyAllotData(keyCode);
    var allotDataOne = await this.cacheManager["TmSubCache"].getTmSubListByCache(allotKeyData);
    if (allotDataOne && allotDataOne.length > 0) {
      var tmpAllotDataOne = JSON.parse(allotDataOne);
      return await this.getTmSubData(datakey, tmpAllotDataOne.pageSize, tmpAllotDataOne.from);
    }
    //设置多key的分页缓存数据
    var ttReult = await this.setAllotKey(keyCodeList, keyCode);
    if (ttReult.code != 1) {
      return ttReult;
    }
    //通过缓存中key的分页数据获取提报数据
    var allotDataTwo = await this.cacheManager["TmSubCache"].getTmSubListByCache(allotKeyData);
    if (allotDataTwo && allotDataTwo.length > 0) {
      var tmpAllotDataTwo = JSON.parse(allotDataTwo);
      return await this.getTmSubData(datakey, tmpAllotDataTwo.pageSize, tmpAllotDataTwo.from);
    }
    return { code: -203, message: "key分页数据有误", data: [] };
  }
  //设置多key的分页缓存数据-本类中getAutoSubList方法用
  async setAllotKey(keyCodeList, keyCode) {
    //设置key的分页数据
    var allotKeyList = keyCodeList.split(',');
    if (allotKeyList.findIndex(f => f == keyCode) < 0) {
      return { code: -201, message: "传递的keyCode参数有误", data: [] };
    }
    //keyTotal=key总数 //currentKey=当前key（第几个）//keyCode=key码
    //WAITCOMMIT  FILLEXCEPTION
    // var tmpWhere={where:{[this.dao.db.Op.or]: [{tmStatus: 'WAITCOMMIT'}, {tmStatus: 'FILLEXCEPTION'}] }};
    var tmpWhere = { where: { [this.dao.db.Op.or]: [{ tmStatus: 'WAITCOMMIT' }] } };
    var dataCount = await this.dao.findCount(tmpWhere);
    if (dataCount == 0) {
      return { code: -202, message: "目前没有待提报的商标数据", data: [] };
    }
    var keyTotal = allotKeyList.length;
    //分配每个key的分页数据信息
    var tPageSize = keyTotal == 1 ? Number(dataCount) : Number(dataCount / keyTotal);
    for (var i = 0; i < keyTotal; i++) {
      var tmpAllotkey = allotKeyList[i];
      var allotResult = { pageSize: parseInt(tPageSize), from: i };
      var tmpAllotKeyData = await this.getTbCacheKeyKeyAllotData(tmpAllotkey);
      //设置缓存
      var allotStr = JSON.stringify(allotResult);
      await this.cacheManager["TmSubCache"].setTmSubList(tmpAllotKeyData, allotStr);
    }
    return { code: 1, message: "success", data: [] };
  }
  //获取提报商标数据-本类中getAutoSubList方法用
  async getTmSubData(datakey, pageSize, from) {
    var sql = "SELECT a.`orderNum`,a.`partnerMobile`,a.`proxyCode`,b.`type` AS appTypeId,a.`sealAuthorizeStuff`,b.`creditCode`,b.`applyName`,b.`applyAddr`,c.`customerContact`,"
      + "c.`mobile`,c.`fax`,c.`zipCode`,b.`businessLicensePic`,b.`identityCard`,b.`identityCardPic`,a.`tmFormType`,a.`voiceUrl`,a.`tmName`,a.`nclOneCodes`,a.`nclSmallCodes`,"
      + "a.`picUrl`,a.`colorizedPicUrl`,a.`descUrl` "
      + " FROM `h_trade_mark` AS a,`h_tmapplier_info` AS b,`h_tmcustomer_info` AS c "
      + " WHERE a.`orderNum`=b.`orderNum` AND a.`orderNum`=c.`orderNum` and a.tmSourceType IN ('16', '64', '128', '256','512','1024','2048','4096','8192') "
      + " AND a.`deleted_at` IS NULL AND a.`tmStatus` = 'WAITCOMMIT' ORDER BY a.id ASC LIMIT " + pageSize + " OFFSET " + from;

    var tmpdbResult = await this.dao.customQuery(sql);
    var tmpi = tmpdbResult.length;
    if (tmpi <= 0) {
      return { code: 200, message: "success", data: [] };
    }
    var result = { code: 200, message: "获取数据成功！", data: [] };
    try {
      for (let i = 0; i < tmpi; i++) {
        var tmpItem = tmpdbResult[i];
        if (tmpItem != null) {
          //获取单个提报数据-以大类为一个
          var params = await this.setTbItem(tmpItem);
          result.data.push(params);
        }
      }
    } catch (e) {
      console.log("TmSub->autosub方法请求出错，error：");
      console.log(e);
      result.code = -200;
      result.message = "请求异常"
      result.data = [];
      return result;
    }
    //设置缓存
    var stringStr = JSON.stringify(result.data);
    await this.cacheManager["TmSubCache"].setTmSubList(datakey, stringStr);
    return result;
  }
  //获取提报数据-本类中getAutoSubList方法用
  async setTbItem(obj) {
    var params = {
      "status": "",
      "errorCount": 0,
      //申请人手机号
      "mobile": obj.partnerMobile == null ? "" : obj.partnerMobile,
      "msg": "",
      //--代理号
      "corpTrademarkId": obj.proxyCode,
      "step1": null,
      "step2": null,
      "step3": null,
      "step4": null,
      "step5": null,
      "step6": null,
      "step7": null
    };
    params.step1 = {
      "appTypeId": obj.appTypeId == 'ent' ? "法人或其它组织" : "自然人",
      "appGjdq": "中国大陆"
    };


    params.step2 = {
      //代理号
      "agentFilenum": obj.proxyCode,
      //代理人=XXX公司（提报key中已写死）+XXX公司的负责人，所以这个为XXX公司的负责人
      "agentPerson": "张飞龙",
      //盖章后的代理委托书
      "agentBookPath": obj.sealAuthorizeStuff == null ? "" : obj.sealAuthorizeStuff,
      "agentBookName": obj.sealAuthorizeStuff == null ? "" : obj.sealAuthorizeStuff.substring(obj.sealAuthorizeStuff.lastIndexOf('/') + 1),
      //申请人信用代码
      "certCode": obj.creditCode == null ? "" : obj.creditCode,
      //申请人名称
      "appCnName": obj.applyName == null ? "" : obj.applyName,
      //申请人地址
      "appCnAddr": obj.applyAddr == null ? "" : obj.applyAddr,
      //申请人联系人
      "appContactPerson": obj.customerContact == null ? "" : obj.customerContact,
      //申请人联系人电话
      "appContactTel": obj.mobile == null ? "" : obj.mobile,
      //申请人联系人传真
      "appContactFax": obj.fax == null ? "" : obj.fax,
      //申请人联系人邮编
      "appContactZip": obj.zipCode == null ? "" : obj.zipCode,
      //申请人营业执照附件
      "certFilePath": obj.businessLicensePic == null ? "" : obj.businessLicensePic,
      "certFileName": obj.businessLicensePic == null ? "" : obj.businessLicensePic.substring(obj.businessLicensePic.lastIndexOf('/') + 1),
      //自然人—>证件名称--身份证,护照，其他====>目前只有身份证
      "appCertificateId": obj.appTypeId != 'person' ? "" : "身份证",
      //自然人—>证件号
      "appCertificateNum": obj.appTypeId != 'person' ? "" : obj.identityCard == null ? "" : obj.identityCard,
      //自然人--->证件文件路径
      "appCertFilePath": obj.appTypeId != 'person' ? "" : obj.identityCardPic == null ? "" : obj.identityCardPic,
      "appCertFileName": obj.appTypeId != 'person' ? "" : obj.identityCardPic == null ? "" : obj.identityCardPic.substring(obj.identityCardPic.lastIndexOf('/') + 1),
    };
    //商标类型形式：1立体、2声音、3文字、4图形、5文字及图形、6颜色组合、7彩色
    params.step3 = {
      //商标类型：tmType1=一般，tmType2=集体，tmType3=证明，用默认tmType1
      "tmType": "tmType1",
      //是否三维标志-商标类型为立体
      "ifSolidTm": obj.tmFormType == '1' ? "ifSolidTm" : "ifSolidTm1",
      //是否颜色组合
      "colourSign": obj.tmFormType == '6' ? "colourSign2" : "colourSign1",
      //声音商标
      "tmFormType": obj.tmFormType == '2' ? "true" : "false",
      //声音文件的全URL
      "tmFormTypeFilePath": obj.tmFormType != '2' ? "" : obj.voiceUrl == null ? "" : obj.voiceUrl,
      "tmFormTypeFileName": obj.tmFormType != '2' ? "" : obj.voiceUrl == null ? "" : obj.voiceUrl.substring(obj.voiceUrl.lastIndexOf('/') + 1),
      //商标说明-商标名称
      "tmDesignDeclare": obj.tmName
    };

    params.step4 = {
      //否共同申请，默认否，ifShareTm1=否，ifShareTm=是，用默认ifShareTm1
      "ifShareTm": "ifShareTm1"
    };

    params.step5 = {
      //优先权声明，priorityType1=无，priorityType2=在先优先权，priorityType3展会优先权，用默认priorityType1
      "priorityType": "priorityType1"
    };
    if (obj.nclSmallCodes && obj.nclSmallCodes.indexOf("nclthree") < 0) {
      params.step6 = await this.setNewNclData(obj.nclOneCodes, obj.nclSmallCodes);
    } else {
      params.step6 = await this.setNclData(obj.nclOneCodes, obj.nclSmallCodes);
    }

    // params.step6={
    //       "goods": [
    //           {
    //               "classes": "28",
    //               "group": "2801",
    //               "nameList": [
    //                   "游戏器具",
    //                   "游戏机控制器",
    //                   "视频游戏操纵杆",
    //                   "便携式游戏机屏幕专用保护膜"
    //               ]
    //           },
    //           {
    //               "classes": "28",
    //               "group": "2803",
    //               "nameList": [
    //                   "棋",
    //                   "宾果游戏牌",
    //                   "纸牌"
    //               ]
    //           },
    //           {
    //               "classes": "28",
    //               "group": "2802",
    //               "nameList": [
    //                   "激光启动的玩具",
    //                   "智能玩具",
    //                   "玩具"
    //               ]
    //           }
    //       ]
    // };

    params.step7 = {
      //图样URL
      "picPath": obj.tmFormType != '7' ?
        obj.picUrl == null ? "" : obj.picUrl :
        obj.colorizedPicUrl == null ? "" : obj.colorizedPicUrl,
      "picName": obj.tmFormType != '7' ?
        obj.picUrl == null ? "" : obj.picUrl.substring(obj.picUrl.lastIndexOf('/') + 1) :
        obj.colorizedPicUrl == null ? "" : obj.colorizedPicUrl.substring(obj.colorizedPicUrl.lastIndexOf('/') + 1),
      //黑白稿，这个表示填报页面的黑白按钮是否启用,,true是黑白商标，false彩色商标---->商标类型为7彩色则为false，则blackPath、blackName两个有值
      "isBlack": obj.tmFormType != '7' ? "true" : "false",
      "blackPath": obj.tmFormType != '7' ? "" : obj.picUrl == null ? "" : obj.picUrl,
      "blackName": obj.tmFormType != '7' ? "" : obj.picUrl == null ? "" : obj.picUrl.substring(obj.picUrl.lastIndexOf('/') + 1),
      //是否肖像商标
      "isPersonPhoto": "false",
      //肖像商标url
      "personPhotoPath": "",
      "personPhotoName": "",
      //说明文件url
      "commentPath": obj.descUrl == null ? "" : obj.descUrl,
      "commentName": obj.descUrl == null ? "" : obj.descUrl.substring(obj.descUrl.lastIndexOf('/') + 1)
    };
    return params;
  }
  //设置尼斯大类及二类-本类中getAutoSubList方法用
  async setNewNclData(tmpNclOneCodes, tmpNclSmallCodes) {
    var nclParams = {
      "goods": []
    };
    var nclInfo = JSON.parse(tmpNclSmallCodes);
    if (nclInfo.length <= 0) {
      return nclParams;
    }
    var hash = {};
    const newArr = nclInfo.reduceRight((item, next) => {
      hash[next.pcode] ? '' : hash[next.pcode] = true && item.push(next);
      return item
    }, []);
    //去重后的数据二级类
    for (let i = 0; i < newArr.length; i++) {
      var tItem = newArr[i];
      if (tItem != null) {
        var tParams = {
          "classes": tmpNclOneCodes,
          "group": tItem.pcode,
          "nameList": await this.setNclThree(tItem.pcode, nclInfo)
        };
        nclParams.goods.push(tParams);
      }
    }
    return nclParams;
  }
  //设置尼斯大类及二类-本类中getAutoSubList方法用
  async setNclData(tmpNclOneCodes, tmpNclSmallCodes) {
    var nclParams = {
      "goods": []
    };
    var nclInfo = JSON.parse(tmpNclSmallCodes);
    if (nclInfo.length <= 0) {
      return nclParams;
    }
    var nclthreeList = nclInfo.nclthree;
    var hash = {};
    const newArr = nclthreeList.reduceRight((item, next) => {
      hash[next.pcode] ? '' : hash[next.pcode] = true && item.push(next);
      return item
    }, []);
    //去重后的数据二级类
    for (let i = 0; i < newArr.length; i++) {
      var tItem = newArr[i];
      if (tItem != null) {
        var tParams = {
          "classes": tmpNclOneCodes,
          "group": tItem.pcode,
          "nameList": await this.setNclThree(tItem.pcode, nclthreeList)
        };
        nclParams.goods.push(tParams);
      }
    }
    return nclParams;
  }
  //设置尼斯小类-本类中getAutoSubList方法用
  async setNclThree(pcode, nclthreeList) {
    var newArr = nclthreeList.filter(function (item) {
      return item.pcode == pcode;
    })
    var rtnArr = [];
    if (newArr.length <= 0) {
      return rtnArr;
    }
    for (let i = 0; i < newArr.length; i++) {
      var tNewItem = newArr[i];
      if (tNewItem != null) {
        rtnArr.push(tNewItem.name);
      }
    }
    return rtnArr;
  }

  //更新提报错误-api用---暂停使用
  async setUpdateErrorCount(proxyCode, errorCount, keyCode) {
    var key = await this.getTbCacheKey(keyCode);
    //处理缓存
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(key);
    if (tbDataList && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      if (tmpResult && tmpResult.length > 0) {
        tmpResult.filter(function (ele) {
          if (ele.corpTrademarkId == proxyCode) {
            ele.errorCount = errorCount;
          }
        });
        //设置缓存
        var stringStr = JSON.stringify(tmpResult);
        await this.cacheManager["TmSubCache"].setTmSubList(key, stringStr);
      }
    }
    return { code: 200, message: "success", data: null };
  }

  //更新提报数据的缓存
  async updateTmCache(proxyCode, keyCode) {
    var key = await this.getTbCacheKey(keyCode);
    //处理缓存
    var tbDataList = await this.cacheManager["TmSubCache"].getTmSubListByCache(key);
    if (tbDataList && tbDataList.length > 0) {
      var tmpResult = JSON.parse(tbDataList);
      if (tmpResult && tmpResult.length > 0) {
        //移除整个缓存
        if (tmpResult.length == 1) {
          var allotKeyData = await this.getTbCacheKeyKeyAllotData(keyCode);
          this.cacheManager["TmSubCache"].delCache(key);
          this.cacheManager["TmSubCache"].delCache(allotKeyData);
        }
        else {
          //移除单个数据
          tmpResult.splice(tmpResult.findIndex(v => v.corpTrademarkId === proxyCode), 1);
          //设置缓存
          var stringStr = JSON.stringify(tmpResult);
          await this.cacheManager["TmSubCache"].setTmSubList(key, stringStr);
        }
      }
    }
    this.dao.updateByWhere({ tmStatus: "ROBOTPAY", tbKey: keyCode }, { where: { proxyCode: proxyCode } });
    return { code: 200, message: "success", data: null };
  }
  //更新商标状态-api用
  async setUpdateState(proxyCode, errorCount, stateCode, keyCode, errorMsg) {//机器人把数据正常提交到商标局-----已提交-ROBOT
    var self = this;
    try {
      await this.db.transaction(async function (t) {
        // var param = { tbKey: keyCode, tbErrorCount: errorCount, submitTime: new Date() };
        var param = { tbKey: keyCode, submitTime: new Date() };
        if (stateCode && stateCode == "ROBOT") {
          param["tmStatus"] = "ROBOT";
          param["tmStatusName"] = "已提交";
          param["opRemarkInfo"] = "已提交";
          self.tmflowDao.create({ proxyCode: proxyCode, tmStatus: "ROBOT", tmStatusName: "已提交", opType: "machine" }, t)
        } else {
          param["tmStatus"] = "FILLEXCEPTION";
          param["tmStatusName"] = "填报异常";
          if (errorMsg) {
            param["opRemarkInfo"] = errorMsg;
          }
        }
        self.dao.updateByWhere(param, { where: { proxyCode: proxyCode } }, t);
        if (keyCode && param.tmStatus) {
          self.dao.model.findOne({
            where: { proxyCode: keyCode }, raw: true
          }).then(tm => {
            if (tm && tm.id) {
              var judgeSource = self.dao.judgeTmSourceType(tm.tmSourceType);
              if (judgeSource) {
                var pushObj = {
                  proxyCode: keyCode,
                  channelCode: judgeSource,
                  tmStatus: param.tmStatus,
                  channelOrderNum: tm.channelOrderNum
                }
                if (param.submitTime) {
                  pushObj["submitTime"] = param.submitTime;
                }
                if (errorMsg) {
                  pushObj["opNotes"] = errorMsg;
                } else {
                  pushObj["opNotes"] = "已提交";
                }
                if (tm.tmSourceType == "1024" || tm.tmSourceType == "2048" || tm.tmSourceType == "4096" || tm.tmSourceType == "8192") {//center-channel
                  var channelPushObj = {
                    orderNo: tm.channelOrderNum,
                    tbCode: keyCode,
                    tmStatus: param.tmStatus,
                    tmStatusName: this.tm_submit_status[param.tmStatus]
                  }
                  if (param.submitTime) {
                    channelPushObj["submitTime"] = param.submitTime;
                  }
                  self.channelreceiveDao.updateChannelTmStatus(channelPushObj);
                } else {
                  self.updateChannelTmStatus(pushObj);
                }
                // self.updateChannelTmStatus(pushObj);
              }
            }
            // if(tm && tm.id && tm.tmSourceType == "64"){
            //   var pushObj={
            //     proxyCode:keyCode,
            //     channelCode:"1688",
            //     tmStatus:param.tmStatus,
            //     channelOrderNum:tm.channelOrderNum
            //   }
            //   if(param.submitTime){
            //     pushObj["submitTime"]=param.submitTime;
            //   }
            //   if(errorMsg){
            //     pushObj["opNotes"]=errorMsg;
            //   }else{
            //     pushObj["opNotes"]="已提交";
            //   }
            //   self.updateChannelTmStatus(pushObj);
            // }
            // if(tm && tm.id && tm.tmSourceType == "128"){
            //   var pushObj={
            //     proxyCode:keyCode,
            //     channelCode:"jd",
            //     tmStatus:param.tmStatus,
            //     channelOrderNum:tm.channelOrderNum
            //   }
            //   if(param.submitTime){
            //     pushObj["submitTime"]=param.submitTime;
            //   }
            //   if(errorMsg){
            //     pushObj["opNotes"]=errorMsg;
            //   }else{
            //     pushObj["opNotes"]="已提交";
            //   }
            //   self.updateChannelTmStatus(pushObj);
            // }
          });
        }

      });
      //钉钉通知
      this.pushReceiptDingTalkMsg(proxyCode, stateCode, errorMsg);
      return { code: 200, message: "success", data: null };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "机器人返回的参数更新商标状态执行异常error",
        op: "/base/service/impl/trademarkSve.js/setUpdateTradeMarkCode",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "RECVCOMMIT update failure", data: null };
    }
  }

  async setUpdateTradeMarkCode(proxyCode, code, stateCode) {//更新商标注册号和状态-api用
    //处理数据库
    var param = {};
    var self = this;
    try {
      if (proxyCode && stateCode && code && stateCode == 'RECVCOMMIT') {
        await this.db.transaction(async function (t) {
          self.dao.updateByWhere({ tmRegistNum: code, tmStatus: stateCode, tmStatusName: "已收提交" }, { where: { proxyCode: proxyCode } }, t);
          // self.tmflowDao.create({ proxyCode: proxyCode, tmRegistNum: code, tmStatus: stateCode, tmStatusName: "已收提交", opType: "machine" }, t);

        });
        if (proxyCode && stateCode) {
          self.dao.model.findOne({
            where: { proxyCode: proxyCode }, raw: true
          }).then(tm => {
            if (tm && tm.id) {
              var judgeSource = self.dao.judgeTmSourceType(tm.tmSourceType);
              if (judgeSource) {
                var pushObj = {
                  proxyCode: proxyCode,
                  channelCode: judgeSource,
                  tmStatus: stateCode,
                  channelOrderNum: tm.channelOrderNum,
                  tmRegistNum: code
                }
                if (tm.tmSourceType == "1024" || tm.tmSourceType == "2048" || tm.tmSourceType == "4096" || tm.tmSourceType == "8192") {//center-channel
                  var channelPushObj = {
                    orderNo: tm.channelOrderNum,
                    tbCode: proxyCode,
                    tmStatus: stateCode,
                    tmStatusName: this.tm_submit_status[stateCode],
                    registNumInfo: {
                      tmRegistNum: code,//商标申请号
                    }
                  }
                  self.channelreceiveDao.updateChannelTmStatus(channelPushObj);
                  // self.channelreceiveDao.updateChannelTmStatus(pushObj);
                } else {
                  self.updateChannelTmStatus(pushObj);
                }

              }
            }
            // if(tm && tm.id && tm.tmSourceType == "64"){
            //   var pushObj={
            //     proxyCode:proxyCode,
            //     channelCode:"1688",
            //     tmStatus:stateCode,
            //     channelOrderNum:tm.channelOrderNum,
            //     tmRegistNum: code
            //   }
            //   self.updateChannelTmStatus(pushObj);
            // }
            // if(tm && tm.id && tm.tmSourceType == "128"){
            //   var pushObj={
            //     proxyCode:proxyCode,
            //     channelCode:"jd",
            //     tmStatus:stateCode,
            //     channelOrderNum:tm.channelOrderNum,
            //     tmRegistNum: code
            //   }
            //   self.updateChannelTmStatus(pushObj);
            // }
          });
        }
        //钉钉通知
        this.pushReceiptDingTalkMsg(proxyCode, stateCode, null);
        return { code: 200, message: "success", data: null };
      }
      //日志记录
      logCtl.info({
        optitle: "机器人返回的参数没有执行更新商标注册号和状态",
        op: "/base/service/impl/trademarkSve.js/setUpdateTradeMarkCode",
        content: "参数：proxyCode=" + proxyCode + "，tmRegistNum=" + code + "，stateCode=" + stateCode,
        clientIp: ""
      });
      return { code: -1, message: "RECVCOMMIT update failure", data: null };
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "更新商标注册号和状态执行异常error",
        op: "/base/service/impl/trademarkSve.js/setUpdateTradeMarkCode",
        content: e.stack,
        clientIp: ""
      });
      return { code: -1, message: "RECVCOMMIT update failure!!!", data: null };
    }
  }
  //根据订单号查询商标
  async findByOrderNum(orderNum) {
    return this.dao.getTmByOrderNum(orderNum);
  }
  async findByPayUserId(payUserId) {
    var sql = "SELECT * FROM	h_trade_mark WHERE	orderNum IN (	SELECT DISTINCT	orderNum	FROM	h_order_info	WHERE	payUserId = " + payUserId + ") ORDER BY created_at desc ";
    var tmpResult = await this.dao.customQuery(sql);
    return tmpResult;
  }
  async findTmFlowByProxyCode(proxyCode) {
    return this.tmflowDao.findByProxyCode(proxyCode);
  }
  async getOrderDetail(orderNum, tmStatus) {
    var applier = await this.tmapplierinfoDao.findOneByOrderNum(orderNum);
    var customer = await this.tmcustomerinfoDao.findOneByOrderNum(orderNum);
    var tms = await this.dao.getTmByOrderNumStatus(orderNum, tmStatus);
    return { applier: applier, customer: customer, tms: tms };
  }

  async getSealAuthorizeStuffByOrderNum(orderNum) {//获取委托书
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@getSealAuthorizeStuffByOrderNum");
    var sql = "SELECT DISTINCT nclCalc_id, sealAuthorizeStuff, tmFormTypeName, tmName " +
      "FROM h_trade_mark WHERE orderNum = '" + orderNum + "'";
    console.log(sql);
    var tms = await this.dao.customQuery(sql);
    return tms;
  }

  async getBhtminfo() {
    var self = this;
    var sql = "SELECT t1.CODE tm_regist_num, t1.proxy_code proxyCode, t1.nclone_id nclOneCodes, t1.momo tmName, t1.mark_state tmStatus, t1.selected_ncltow_str nclSmallCodes, t1.applier applyName, t1.update_time,t1.trade_mark_type tm_type,t1.whether_third_space,	t1.whether_color_group,t1.has_color,t1.trade_mark_type,iua.file_url picUrl"
    sql += " FROM ( SELECT itm.id tid, itmc.id cid, itm. CODE, itm.proxy_code, itm.nclone_id, itm.momo, itm.mark_state, itm.selected_ncltow_str, itmc.applier, itm.update_time, itm.share_group, itm.trade_mark_type,itm.whether_third_space, itm.whether_color_group, itm.has_color,itm.whether_sound "
    sql += "FROM `ig_trade_mark` itm JOIN ig_trade_mark_case itmc ON itm.trade_mark_caseid = itmc.id ) t1 LEFT JOIN ig_up_attachment iua ON t1.cid = iua.trade_mark_caseid AND iua.share_group = t1.share_group WHERE iua.attachment_cat = 1;"
    var tminfos = await this.connectionbh.query(sql);
    var sumtm = 0;
    if (tminfos) {
      var newtms = [];
      for (var i = 0; i < tminfos[0, 0].length; i++) {
        var tminfo = tminfos[0, 0][i];
        tminfo.applyName = tminfo.applyName == null ? '' : tminfo.applyName;
        tminfo.applyName = await self.getConvertSemiangleStr(tminfo.applyName);
        var status = "READY";
        switch (tminfo.tmStatus) {
          case 0:
            status = 'READY'; break;
          case 1:
            status = 'DOCFINISH'; break;
          case 2:
            status = "WAITCOMMIT"; break;
          case 3:
            status = 'COMMITED'; break;
          case 4:
            status = 'RECVCOMMIT'; break;
          case 5:
            status = '3'; break;
          case 6:
            status = '8'; break;
          case 7:
            status = '7'; break;
          case 8:
            status = '10'; break;
          case 9:
            status = 'ROBOT'; break;
          case 10:
            status = '13'; break;
          case 11:
            status = 'FILLEXCEPTION'; break;
          case 12:
            status = 'FILELIST'; break;
          case 13:
            status = '4'; break;
          case 14:
            status = 'ENVLOPE'; break;
          case 15:
            status = '2'; break;
          case 16:
            status = '9'; break;
          case 17:
            status = '11'; break;
          case 18:
            status = 'NOTAPPROVAL'; break;
          case 19:
            status = 'APPROVAL'; break;
          case 20:
            status = '6'; break;
          case 21:
            status = '5'; break;
          default:
            break;
        }
        await this.db.transaction(async function (t) {
          var tm = await self.dao.findOne({ proxyCode: tminfo.proxyCode }, t);
          if (tm) {
            tm.tmStatus = status;
            await self.dao.update(tm.dataValues, t);
          } else {
            var tft = '3';
            if (tminfo.whether_third_space) {
              tft = '1';
            } else if (tminfo.has_color) {
              tft = '7';
            } else if (tminfo.whether_color_group) {
              tft = '6';
            } else {
              tft = '3';
            }
            var sncl = tminfo.nclSmallCodes;
            var nclthrees = [];
            var stss = sncl.split("\n");
            for (var j = 0; j < stss.length; j++) {
              var sts = stss[j].split(":");
              var nclthree = {};
              if (sts[3] != null && sts[3] != "" && sts[3] != "undefined") {
                var sqlncl = "SELECT * FROM `ig_base_ncltwo` where id=" + sts[3];
                var sqlncls = await self.connectionbh.query(sqlncl);
                if (sqlncls[0, 0]) {
                  nclthree = { "code": sqlncls[0, 0][0].third_code, "name": sqlncls[0, 0][0].name, "pcode": sqlncls[0, 0][0].code };
                  nclthrees.push(nclthree);
                }
              }
            }
            var allnclthree = { nclthree: nclthrees };
            var ac = JSON.stringify(allnclthree);
            var newtm = {
              tmRegistNum: tminfo.tm_regist_num,
              proxyCode: tminfo.proxyCode,
              nclOneCodes: tminfo.nclOneCodes,
              tmName: tminfo.tmName,
              tmStatus: status,
              nclSmallCodes: ac,
              tmFormType: tft,
              tmType: "p",
              picUrl: tminfo.picUrl,
              applyName: tminfo.applyName,
              created_at: tminfo.update_time,
              updated_at: tminfo.update_time,
              tmSourceType: '8'
            }
            await self.dao.model.create(newtm, t);
            sumtm += 1;
          }
        });
      }
    }
    return { code: 1, msg: "success", data: sumtm }
  }

  async getConvertSemiangleStr(str) {
    var result = "";
    str = str.replace(/\s+/g, "");
    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 getItemById(id, businessId) {
    var paramAttributes = ["id", "orderNum", "tmType", "tmFormType", "caseType", "nclOneCodes", "nclSmallCodes",
      "tmName", "picUrl", "tmNamePy", "tmNameEn", "tmNamePyjc", "known", "tmValue", "coOwner", "submitTime",
      "proxyCode", "tmRegistNum", "creatAuthorizeStuff", "sealAuthorizeStuff", "voiceUrl", "tmStatus", "user_id",
      "colorizedPicUrl", "descUrl", "partnerMobile", "userName", "applyName", "parentProxyCode", "parentTmRegistNum",
      "newProxyCode", "newTmRegistNum", "remarkInfo", "opRemarkInfo", "channelOrderNum", "app_code", "tmSourceType",
      "channelUserId", "mobile", "channelPayStatus", "businessId", "needId", "channelOrderListInfo", "principal"];
    var sqlWhere = null;
    if (id) {
      sqlWhere = { where: { id: id }, attributes: paramAttributes, raw: true };
    }
    if (businessId) {
      sqlWhere = { where: { businessId: businessId }, attributes: paramAttributes, raw: true };
    }
    return await this.dao.model.findOne(sqlWhere);
  }
  async getListByIds(ids) {
    var paramAttributes = ["id", "orderNum", "tmType", "tmFormType", "caseType", "nclOneCodes", "nclSmallCodes",
      "tmName", "picUrl", "tmNamePy", "tmNameEn", "tmNamePyjc", "known", "tmValue", "coOwner", "submitTime",
      "proxyCode", "tmRegistNum", "creatAuthorizeStuff", "sealAuthorizeStuff", "voiceUrl", "tmStatus", "user_id",
      "colorizedPicUrl", "descUrl", "partnerMobile", "userName", "applyName", "parentProxyCode", "parentTmRegistNum",
      "newProxyCode", "newTmRegistNum", "remarkInfo", "opRemarkInfo", "channelOrderNum", "app_code", "tmSourceType",
      "channelUserId", "mobile", "channelPayStatus", "businessId", "needId", "channelOrderListInfo", "principal"];
    var sqlWhere = { where: { id: { [this.db.Op.in]: ids } }, paramAttributes, raw: true };
    return await this.dao.model.findAll(sqlWhere);
  }
  //修改商标状态
  async putStatusById(params) {
    await this.dao.update(params);
    return { code: 1 }
  }
  async findByChannelOrderNum(channelOrderNum, type, orderNum) {
    var paramAttributes = ["id", "orderNum", "tmType", "tmFormType", "caseType", "nclOneCodes", "nclSmallCodes",
      "tmName", "picUrl", "tmNamePy", "tmNameEn", "tmNamePyjc", "known", "tmValue", "coOwner", "submitTime",
      "proxyCode", "tmRegistNum", "creatAuthorizeStuff", "sealAuthorizeStuff", "voiceUrl", "tmStatus", "user_id",
      "colorizedPicUrl", "descUrl", "partnerMobile", "userName", "applyName", "parentProxyCode", "parentTmRegistNum",
      "newProxyCode", "newTmRegistNum", "remarkInfo", "opRemarkInfo", "channelOrderNum", "app_code", "tmSourceType",
      "channelUserId", "mobile", "channelPayStatus", "businessId", "needId", "channelOrderListInfo", "principal"];
    if (type == "1") {
      return this.dao.model.findAll({ where: { channelOrderNum: channelOrderNum }, paramAttributes, raw: true });
    }
    if (type == "2") {
      return this.dao.model.findAll({ where: { channelOrderNum: channelOrderNum, orderNum: { [this.db.Op.ne]: orderNum } }, paramAttributes, raw: true });
    }
  };
  async findCountByChannelOrderNum(channelOrderNum, needId, tmStatus, notInTmStatus) {
    var sqlWhere = { where: { channelOrderNum: channelOrderNum, needId: needId } };
    if (tmStatus) {
      sqlWhere.where["tmStatus"] = tmStatus;
    }
    if (notInTmStatus && notInTmStatus.length > 0) {
      sqlWhere.where["tmStatus"] = { [this.db.Op.notIn]: notInTmStatus };
    }
    return await this.dao.findCount(sqlWhere);
  };
  async findListByChannelOrderNum(channelOrderNum, needId) {
    var paramAttributes = ["id", "tmStatus"];
    return await this.dao.model.findAll({ where: { channelOrderNum: channelOrderNum, needId: needId }, paramAttributes, raw: true });
  };
  //更新商标状态-api用
  async putChannelPayStatus(channelOrderNum, channelPayStatus) {
    var param = { channelPayStatus: channelPayStatus };
    var sqlWhere = { where: { channelOrderNum: channelOrderNum } };
    await this.dao.updateByWhere(param, sqlWhere)
    return { code: 1, message: "success", data: null };
  }

  //商标业务员转移
  async tmtransfer(obj) {
    var user = obj.user;
    var mobile = obj.mobile;
    var channelOrderNums = obj.channelOrderNums;
    if (!mobile) {
      return { code: -1, msg: "mobile参数错误" };
    }
    if (mobile == user.mobile) {
      return { code: -6, msg: "不能转移给自己" };
    }
    if (!channelOrderNums || channelOrderNums.length < 1) {
      return { code: -2, msg: "channelOrderNums参数错误" };
    }

    var salesman = await this.userDao.model.findOne({ where: { mobile: mobile, app_id: 23 } });
    if (!salesman) {
      return { code: -3, msg: "接收用户不存在" };
    }

    for (var i = 0; i < channelOrderNums.length; i++) {
      var tm = await this.dao.model.findOne({
        where: {
          channelOrderNum: channelOrderNums[i],
          [this.dao.db.Op.or]: [{ user_id: user.id }, { mobile: user.mobile }]
        },
        attributes: ["id"],
        raw: true
      });
      if (!tm) {
        return { code: -4, msg: "商标信息不存在" };
      }

    }
    var self = this;
    return this.db.transaction(async function (t) {
      // ar_5c936b9c8580bc4e08e08657_gsb_zcsubmit
      var channelUserId = "";
      var onlyCode = salesman.onlyCode;
      if (onlyCode) {
        channelUserId = onlyCode.split("_gsb_zcsubmit")[0].split("ar_")[1] || "";
      }
      if (!channelUserId) {
        return { code: -5, msg: "channelUserId错误" };
      }
      var param = { mobile: salesman.mobile, channelUserId: channelUserId, user_id: salesman.id, onlyCode: salesman.onlyCode, userName: salesman.userName, app_id: salesman.app_id };
      var sqlWhere = {
        where: {
          channelOrderNum: {
            [self.dao.db.Op.in]: channelOrderNums
          }
        }
      };
      var updateTm = await self.dao.updateByWhere(param, sqlWhere, t);
      console.log(updateTm);
      var updateOrder = await self.orderDao.updateByWhere(param, sqlWhere, t);
      console.log(updateOrder);
      return { code: 1 };
    })

  }

  //根据渠道订单号查询尼斯数据
  async getHistoryNclByChannelOrderNum(obj) {
    var user = obj.user;
    var channelOrderNum = obj.channelOrderNum;
    if (!channelOrderNum) {
      return { code: -1, msg: "订单号不能为空", err: "channelOrderNum参数错误" };
    }
    var tms = await this.dao.model.findAll({
      where: {
        channelOrderNum: channelOrderNum,
        [this.dao.db.Op.or]: [{ user_id: user.id }, { mobile: user.mobile }]
      },
      attributes: ["nclOneCodes", "nclSmallCodes"],
      raw: true
    });
    if (!tms || tms.length < 1) {
      return { code: -2, msg: "未查到该订单数据", err: "未查到该订单数据" };
    } else {
      return { code: 1, data: tms };
    }
  }

  async ddSend(obj) {
    this.pushReceiptDingTalkMsg(obj.proxyCode, obj.stateCode, obj.errorMsg)
  }

  async pushReceiptDingTalkMsg(proxyCode, stateCode, errorMsg) {
    var tm_submit_status = uiconfig.config.pdict.tm_submit_status;
    if (tm_submit_status[stateCode] && tm_submit_status[stateCode] != "undefined") {
      var tm = await this.dao.model.findOne({ where: { proxyCode: proxyCode }, attributes: ["applyName", "tmName", "nclOneCodes", "channelOrderNum"], raw: true });
      if (tm) {
        var msg = " 公司名称:" + tm.applyName + " \n商标名称:" + tm.tmName + " \n国际分类：" + tm.nclOneCodes +
          " \n申请状态更新为：【" + tm_submit_status[stateCode] + "】";
        if (errorMsg && stateCode != "ROBOT") {
          msg = msg + " \n错误信息为：" + errorMsg;
        }
        else if (errorMsg) {
          msg = msg + " \n" + errorMsg;
        }

        msg = msg + "，请您查看";
        var obj = {
          content: msg,
          send_msg: "",
          is_send: -1,
          order_no: tm.channelOrderNum
        };
        this.notifyDingTalkMsg(obj);
      }
    }
  }
  async getUUId(userId) {
    var myDate = new Date();
    return myDate.getFullYear() + "" + myDate.getMonth() + "" + myDate.getDate() + "" + myDate.getHours() + "" + myDate.getMinutes() + "" + myDate.getSeconds() + "" + myDate.getMilliseconds() + "" + Math.round(Math.random() * 500) + "" + userId;
  }
  async putTmAndAddTm(putTmStatus, item) {
    var result = { code: 1, data: null };
    var self = this;
    await this.db.transaction(async function (t) {
      var key = await self.getUUId(item.user_id);
      var tmobj = {
        "applyName": item.applyName,
        "tmRegistNum": "",
        "partnerMobile": item.mobile,
        "app_id": item.app_id,
        "user_id": item.user_id,
        "userName": item.userName,
        "onlyCode": item.onlyCode,
        "orderNum": item.orderNum,
        "tmType": "p",
        "tmFormType": item.tmFormType,
        "nclOneCodes": item.code,
        "tmStatus": "DOCFINISH",
        "colorizedPicUrl": item.colorizedPicUrl,
        "nclSmallCodes": item.nclSmallCodes,
        "tmName": item.tmName,
        "picUrl": item.picUrl,
        "proxyCode": key,
        "sealAuthorizeStuff": item.sealAuthorizeStuff,
        "channelOrderNum": item.channelOrderNum || "",
        "channelUserId": item.channelUserId || "",
        "channelPayStatus": "wzf",
        "tmSourceType": item.tmSourceType || "1",
        "needId": item.needId || "",
        "channelOrderListInfo": item.channelOrderListInfo || "",
      };
      if (putTmStatus == "DISCARDED") {
        await self.dao.delete({ id: item.id });
      } else {
        await self.dao.updateByWhere({ tmStatus: putTmStatus }, { where: { id: item.id } }, t);
      }
      var addItem = await self.dao.create(tmobj, t);
      result.data = addItem;
    });
    return result;
  }

  //.........................................................操作阿里云...............开始

  async closeAliTmStatus(item) {//关闭阿里云的状态
    var rc = system.getObject("util.aliyunClient");
    try {
      if (!item.businessId) {
        await this.dao.updateByWhere({ opRemarkInfo: "表中的businessId为空，不能进行关闭状态" }, { where: { id: item.id } });
      }
      var param = {
        BizId: item.businessId,
        serviceOrderNo: item.channelOrderNum,
        reqOnlyCode: item.reqOnlyCode,
      };
      var closeTm = await rc.post("CloseTradeMarkProduct", param);
      if (closeTm.Code == "200") {
        await this.dao.delete({ id: item.id });
        return { code: 1, msg: "操作成功" };
      }
      this.opSaveLog("请求阿里关闭商标接口返回错误----error", param, item, closeTm);
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "请求关闭接口异常----error",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/closeAliTmStatus",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "请求关闭阿里接口异常:" + e.stack }
    }
  }

  async putAliTmStatus(item) {//修改阿里云的状态
    var applier = await this.tmapplierinfoDao.findOneByOrderNum(item.orderNum);
    var customer = await this.tmcustomerinfoDao.findOneByOrderNum(item.orderNum);
    if (!applier) {
      return { code: -160, msg: "订单对应的申请人信息为空", data: null }
    }
    if (!customer) {
      return { code: -163, msg: "订单对应的联系人信息为空", data: null }
    }
    var result = await this.opAliTm(item, applier, customer);
    return result;
  }

  async opAliTm(item, applier, customer) {//阿里提交注册⽅案-商标信息---本类用
    var rc = system.getObject("util.aliyunClient");
    try {
      var threeList = [];
      var tmpNclList = JSON.parse(item.nclSmallCodes);
      if (tmpNclList.length > 0) {
        for (let index = 0; index < tmpNclList.length; index++) {
          const element = tmpNclList[index];
          if (element) {
            threeList.push(element.name);
            // if (element.code) {
            //   threeList.push(element.code);
            // } else {
            //   threeList.push(element.name);
            // }
          }
        }
      }
      var principalName = 1;
      var tmNameType = 1;//1：⽂字 2：图⽚ 3：图⽂

      if (item.principal && item.principal == "知域互联科技有限公司") {
        principalName = 2;
      }
      if (item.tmFormType == "4") {
        tmNameType = 2;
      } else if (item.tmFormType == "5") {
        tmNameType = 3;
      }
      var subParam = {
        BizId: item.businessId || "",
        IntentionBizId: item.needId,
        TmName: item.tmName,
        TmIcon: item.tmFormType == "7" ? item.colorizedPicUrl : "",//商标图样（彩⾊）
        GrayIcon: item.picUrl || "",//商标图样（⿊⽩）
        ClassificationCode: item.nclOneCodes,
        TmCode: threeList.join(','),//"350005,350071,350106,350120,350065,350082,350096,350119,350092",//threeList.join(','),
        TmComment: item.tmName,//商标说明
        serviceOrderNo: item.channelOrderNum,
        reqOnlyCode: item.reqOnlyCode,
        PrincipalName: principalName,
        // TmNameType: tmNameType,//TODO:暂时先不上，等阿里那边优化后在放开此参数
      };
      var submitTm = await rc.post("SaveTradeMarkProductSolution", subParam);
      //返回值
      // {
      //   "Code": "200",
      //   "RequestId": "24F6A368-51EE-4275-9B69-9C0C39CE69E1",
      //   "Success": true,
      //   "BizId": "TM_20190725110830000001",
      //   "OrderPrice": 360
      // }
      var result = { code: 1, msg: "ok" };
      this.opSaveLog("请求阿里提交商标接口返回错误----error", subParam, item, submitTm);
      if (submitTm.Code == "200") {
        // "SUBALITM": "已提交阿里(待补全信息)",
        await this.dao.updateByWhere({ businessId: submitTm.data.BizId, tmStatus: "SUBALITM", channelPric: submitTm.OrderPrice || 0 }, { where: { id: item.id } });
        var tmApplyInfo = await this.opAliTmApplyInfo(submitTm, item, applier, customer, rc, principalName);
        if (tmApplyInfo.Code == "200") {
          // "SUBALITMOK": "已补全信息(待确认商标)",
          await this.dao.updateByWhere({ tmStatus: "SUBALITMOK" }, { where: { id: item.id } });
        }
        else {
          result.code = -170;
          result.msg = "阿里补全信息返回：errorCode=" + tmApplyInfo.errorCode + "errorMsg=" + tmApplyInfo.errorMsg;
        }
      }
      else {
        if (item.businessId && submitTm.errorCode == "TRADEMARK.PRODUCT.DUPLICATE") {
          submitTm.data["BizId"] = item.businessId;
          if (item.tmStatus == "SUBALITM") {
            var tmApplyInfo = await this.opAliTmApplyInfo(submitTm, item, applier, customer, rc, principalName);
            if (tmApplyInfo.Code == "200") {
              // "SUBALITMOK": "已补全信息(待确认商标)",
              await this.dao.updateByWhere({ tmStatus: "SUBALITMOK" }, { where: { id: item.id } });
              return { code: 1, msg: "操作成功" };
            }
            else {
              result.code = -180;
              result.msg = "阿里补全信息返回-BizId" + item.businessId + "：errorCode=" + tmApplyInfo.errorCode + "errorMsg=" + tmApplyInfo.errorMsg;
            }
          }
        }//已存在相同的商标申请信息
        else {
          //记录错误
          result.code = -190;
          result.msg = "阿里提交返回：errorCode=" + submitTm.errorCode + "errorMsg=" + submitTm.errorMsg;
        }
      }
      return result;
    } catch (e) {
      console.log(e.stack, "请求阿里提交注册⽅案-商标信息接口异常................error.............")
      //日志记录
      logCtl.error({
        optitle: "请求阿里接口异常----error",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/opAliTm",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "请求阿里接口异常:" + e.stack }
    }
  }
  async opSaveLog(descStr, param, item, returnResult) {//保存操作错误日志---本类用
    if (returnResult && (!returnResult.Code || returnResult.Code != "200")) {
      //日志记录
      logCtl.info({
        optitle: descStr,
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/opAliTm",
        content: "tmid:" + JSON.stringify(item) + "，表中阿里业务businessId=" + item.businessId + "，请求参数：" + JSON.stringify(param) + "，返回值：" + JSON.stringify(returnResult),
        clientIp: ""
      });
      await this.dao.updateByWhere({ opRemarkInfo: "阿里返回：errorCode=" + returnResult.errorCode + "errorMsg=" + returnResult.errorMsg }, { where: { id: item.id } });
    }
  }
  async opAliTmApplyInfo(submitTm, item, applier, customer, rc, principalName) {//阿里补全注册⽅案-申请⼈信息---本类用
    var bizIDList = [submitTm.data.BizId];
    var reqParam = {
      BizIds: JSON.stringify(bizIDList),
      Type: applier.type == "ent" ? 2 : 1,
      Region: 1,//申请⼈地区("中国⼤陆:1","中国⾹港:2","中国澳⻔:3","中国台湾:4","国外:5")
      ContactName: customer.customerContact,
      ContactNumber: customer.mobile,
      ContactAddress: customer.contactAddress,
      ContactEmail: customer.email && customer.email.indexOf("@") >= 0 ? customer.email : "gsb@gongsibao.com",
      ContactZipcode: customer.zipCode || "100000",
      LoaOssKey: item.sealAuthorizeStuff,//授权书OSSKey，TODO:需要设置生成文件失效时间
      Name: applier.applyName,
      CardNumber: applier.type == "ent" ? applier.creditCode : applier.identityCard,
      Province: "",
      City: "",
      Town: "",
      Address: applier.applyAddr,
      EngName: "",
      EngAddress: "",
      IdCardOssKey: applier.type == "ent" ? "" : applier.identityCardPic,//TODO:需要设置生成文件失效时间
      BusinessLicenceOssKey: applier.businessLicensePic,//TODO:需要设置生成文件失效时间
      PassportOssKey: "",
      LegalNoticeOssKey: item.descUrl || "",//法律声明
      serviceOrderNo: item.channelOrderNum,
      PrincipalName: principalName,
    };
    var tmDetailResult = await rc.post("SaveTradeMarkMaterialDetail", reqParam);
    this.opSaveLog("请求阿里补全商标接信息接口返回错误----error", reqParam, item, tmDetailResult);
    return tmDetailResult;
  }
  async opAliVerifyTm(channelOrderNum, needId, setStatus, tmIdList) {//阿里确认商标需求信息
    var rc = system.getObject("util.aliyunClient");
    try {
      var putWhere = { where: {} };
      if (tmIdList && tmIdList.length > 0) {
        putWhere.where["id"] = { [this.db.Op.in]: tmIdList };
      } else {
        putWhere.where["channelOrderNum"] = channelOrderNum;
        putWhere.where["needId"] = needId;
      }
      var param = { IntentionBizId: needId, serviceOrderNo: channelOrderNum };
      var tmVerify = await rc.post("ConfirmTradeIntention", param);
      if (tmVerify.Code == "200") {
        await this.dao.updateByWhere({ tmStatus: setStatus }, putWhere);
        return { code: 1, msg: "succeed" };
      }
      else {
        //日志记录
        logCtl.info({
          optitle: "请求阿里确认商标接口返回错误----error",
          op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/opAliVerifyTm",
          content: "tmIdList=" + JSON.stringify(tmIdList) + "channelOrderNum:" + channelOrderNum + "，表中阿里需求业务needId=" + needId + "，请求参数：" + JSON.stringify(param) + "，返回值：" + JSON.stringify(tmVerify),
          clientIp: ""
        });
        await this.dao.updateByWhere({ opRemarkInfo: "阿里返回：errorCode=" + tmVerify.errorCode + "errorMsg=" + tmVerify.errorMsg }, putWhere);
        return { code: -100, msg: "请求阿里操作错误" };
      }
    } catch (e) {
      //日志记录
      logCtl.error({
        optitle: "请求阿里确认商标需求信息接口异常----error",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/opAliVerifyTm",
        content: e.stack,
        clientIp: ""
      });
      return { code: -200, msg: "请求阿里操作异常" };
    }
  }

  async opAliUseRticklingNotify(payStatus, tmStatus, pObj) {//阿里客户有反馈，需求被驳回通知
    if (!pObj.intentionBizId) {
      return { code: -100, msg: "intentionBizId参数不能为空" };
    }
    if (tmStatus != "ALICUSTOMERREJECTED" && tmStatus != "DISCARDED") {
      return { code: -110, msg: "修改的状态有误" };
    }
    if (tmStatus == "DISCARDED") {
      await this.dao.delete({ needId: pObj.intentionBizId });
      return { code: 1, msg: "ok" };
    }//关闭需求
    var setParam = {};
    setParam.tmStatus = tmStatus;// "ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)",
    setParam.opRemarkInfo = pObj.description || "";
    await this.dao.updateByWhere(setParam, { where: { needId: pObj.intentionBizId } });
    return { code: 1, msg: "ok" };
  }


  async opAliNotify(payStatus, tmStatus, pObj) {//阿里通知
    var self = this;
    var opDownFileResult = {};
    if (pObj.fileUrl) {
      var opUrlResult = {
        code: 1,
        message: "success",
        data: {}
      };
      opDownFileResult = await self.opDownFileInfo(pObj.fileUrl, opUrlResult);
      //日志记录
      logCtl.info({
        optitle: "阿里云返回的通知url操作文件url下载返回结果",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/trademarkSve.js/opAliNotify",
        content: "请求参数：" + JSON.stringify(pObj) + "，结果信息：" + JSON.stringify(opDownFileResult),
        clientIp: ""
      });
    }
    var item = await this.getItemById(null, pObj.bizId);
    if (!item) {
      return { code: -100, msg: "没有相关业务id对应的商标信息" };
    }
    var setParam = {};
    if (payStatus && payStatus == "0") {
      setParam.channelPayStatus = "yzf";
      setParam.payTime = new Date();
    }
    if (tmStatus == "ALIPAYREFUND") {
      setParam.channelPayStatus = "ysbtk";
    }
    if (tmStatus == "ROBOT") {
      setParam.submitTime = new Date();
    }
    setParam.tmStatus = tmStatus;//待阿里审核(已支付)
    setParam.opRemarkInfo = pObj.remark || "";

    if (!item.tmRegistNum || !item.tmRegistNum != pObj.applyNo) {
      setParam.tmRegistNum = pObj.applyNo;
    }
    var official_type = uiconfig.config.pdict.tm_submit_status;
    var official_type_name = official_type[tmStatus];
    //默认失败
    var opResult = { code: 1, msg: "succeed" };
    var updateTmStatus = 0;
    try {
      await this.db.transaction(async function (t) {
        if (item.tmStatus != tmStatus) {
          await self.dao.updateByWhere(setParam, { where: { proxyCode: item.proxyCode } }, t);
          opResult.msg = "succeed";
          opResult.code = 1;
          updateTmStatus = 1;
        }
        if (pObj.applyNo || ["ALIPAPERS2", "RECVCOMMIT", "3", "4", "7", "8", "9", "13"].indexOf(tmStatus) >= 0) {//操作回执
          var fileName = official_type_name + "_" + item.tmName + "_" + item.nclOneCodes;
          var flowWhere = { where: { tmRegistNum: pObj.applyNo, tmStatus: tmStatus } };
          var flowCount = await self.tmflowDao.findCount(flowWhere);

          var params = {
            tmStatus: tmStatus,
            uploadFileName: fileName,
            // returnReceiptUrl: pObj.fileUrl,//TODO:需要下载下来重新保存
            tmRegistNum: pObj.applyNo,
          };
          if (pObj.fileUrl) {
            // var opUrlResult = {
            //   code: 1,
            //   message: "success",
            //   data: {}
            // };
            // var opDownFileResult = await self.opDownFileInfo(pObj.fileUrl, opUrlResult);
            // //日志记录
            // logCtl.info({
            //   optitle: "阿里云返回的通知url操作文件url下载返回结果",
            //   op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/trademarkSve.js/opAliNotify",
            //   content: "请求参数：" + JSON.stringify(pObj) + "，结果信息：" + JSON.stringify(opDownFileResult),
            //   clientIp: ""
            // });
            params["returnReceiptUrl"] = opDownFileResult.code == 1 ? opDownFileResult.data.url : pObj.fileUrl;
          }

          if (flowCount > 0) {
            await self.tmflowDao.updateByWhere(params, flowWhere, t);
          } else {
            await self.tmflowDao.create(params, t);
          }
          opResult.msg = "succeed";
          opResult.code = 1;
        }
      });
    } catch (error) {
      //日志记录
      logCtl.error({
        optitle: "阿里通知更新状态异常",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/trademarkSve.js/opAliNotify",
        content: "请求参数：" + JSON.stringify(pObj) + "，error信息：" + e.stack,
        clientIp: ""
      });
      opResult.msg = "failure error";
      opResult.code = -110;
    }

    if (updateTmStatus == 1) {
      var msg = "阿里商标申请，阿里业务ID：" + item.businessId + "\n申请人：" + item.applyName + "\n商标名称：" + item.tmName + "\n申请状态变更为：" + official_type_name;
      var obj = {
        content: msg,
        send_msg: "",
        is_send: -1,
        order_no: item.channelOrderNum
      };
      self.notifyDingTalkMsg(obj);
    }//发送钉钉消息
    return opResult;
  }


  async opDownFileInfo(docUrl, result) {  //从oss下载到本地并上传到自己oss，之后删除本地文件
    /*docUrl下载链接，全路径，如：https://gsb-zc.oss-cn-beijing.aliyuncs.com/zc_colorizedPicUrl71322019721564722335553.jpg */
    try {
      var fileName = docUrl.substring(docUrl.lastIndexOf("/") + 1, docUrl.lenght);
      if (fileName.indexOf("?") >= 0) {
        fileName = fileName.substring(0, fileName.lastIndexOf("?"));
      }
      var fileType = fileName.substring(fileName.lastIndexOf("."), docUrl.lenght);
      //解码后的文件全名:xxx.pdf
      var fileAllName = decodeURIComponent(fileName);//为xxx.pdf
      var saveFilePath = '/tmp/' + fileAllName;
      // 下载文件到指定的路径
      var tmpp = await this.restClient.execDownload("'" + docUrl + "'", saveFilePath);
      //上传 saveFilePath的文件 到ossClient
      var uuid = uuidv4();
      var u = uuid.replace(/\-/g, "");
      var upFileName = "zc_zxy_" + u + fileType;
      var rtn = await this.ossClient.upfile(upFileName, saveFilePath);
      result.data = rtn;
      //删除本地文件
      fs.unlink(saveFilePath, function (err) { });
    } catch (e) {
      result.code = -200;
      result.message = "通过flowId获取到的文件url下载操作异常异常error";
      console.log(e.stack);
      //日志记录
      logCtl.error({
        optitle: "阿里云返回的通知url操作文件url下载操作异常异常error",
        op: "/usr/node-dev/OMC/fqboss/app/base/service/impl/trademarkSve.js/opDownFileInfo",
        content: "请求参数：docUrl=" + docUrl + "，异常信息error：" + e.stack,
        clientIp: ""
      });
    }
    return result;
  }

  //.........................................................操作阿里云...............结束

  //---------------------------------1688商标状态修改 开始------------------------------------------------------
  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 updateChannelTmStatus(obj) {
    try {
      var proxyCode = obj.proxyCode;
      var channelCode = obj.channelCode;
      var tmStatus = obj.tmStatus;
      var channelOrderNum = obj.channelOrderNum;
      if (!proxyCode) {
        return { code: -100, msg: "proxyCode参数错误" };
      }
      var judgeRes = this.dao.judgeChannelCode(channelCode);
      // if(!channelCode || (channelCode!="1688" && channelCode!="jd")){
      //   return {code:-101,msg:"channelCode参数错误"};
      // }
      if (!judgeRes) {
        return { code: -101, msg: "channelCode参数错误" };
      }
      if (!tmStatus) {
        return { code: -102, msg: "tmStatus参数错误" };
      }
      if (!channelOrderNum) {
        return { code: -103, msg: "channelOrderNum参数错误" };
      }
      var token = await this.getToken(channelCode);
      if (!token || token.status != 0) {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: "推送渠道辅助注册商标数据---获取token失败",
          op: "trademarkSve/updateChannelTmStatus",
          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": "updateAssistTmStatus",
        "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: channelCode + "商标状态修改---成功",
          op: reqUrl,
          content: JSON.stringify(reqObj),
          resultinfo: JSON.stringify(rtn),
          clientIp: ""
        });
      } else {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: channelCode + "商标状态修改---失败",
          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: "trademarkSve/updateChannelTmStatus",
        content: JSON.stringify(e.stack),
        clientIp: ""
      });
      return { code: -400, msg: "操作失败", err: e.stack };
    }
  }

  //商标信息查询-tm信息推送接口
  async queryTmInfoForPush() {
    try {
      let sql = "SELECT id,orderNum,tmFormType,tmName,picUrl,nclOneCodes,nclSmallCodes,principal,tmRegistNum,tmStatus,tmStatusName,tmSourceTypeName,channelOrderListInfo, businessId,`updated_at`,lastUp FROM `h_trade_mark` WHERE channelOrderListInfo NOT LIKE  '%,%' AND channelOrderListInfo NOT LIKE '%，%' AND channelOrderListInfo IS NOT NULL AND channelOrderListInfo !='' AND isPushed!=1 LIMIT 200;";
      let tmResult = await this.dao.customQuery(sql);
      return tmResult;
    } catch (e) {
      console.log('queryTmInfoForPush查询失败');
      return e;
    }
  }

  //联系人信息查询-tm信息推送接口 
  async queryTmCustomerInfoForPush(orderNum) {
    try {
      let sql = "SELECT * FROM `h_tmcustomer_info` WHERE orderNum='" + orderNum + "';";
      let customerResult = await this.dao.customQuery(sql);
      return customerResult;
    } catch (e) {
      console.log('queryTmCustomerInfoForPush查询失败');
      return e;
    }
  }

  //商标信息查询(bussinessId)-联系人地址信息推送接口
  async queryTmInfo(orderNum) {
    try {
      let sql = "SELECT  businessId FROM `h_trade_mark` WHERE orderNum = '" + orderNum + "' AND tmSourceType = '32';";
      let tmResult = await this.dao.customQuery(sql);
      return tmResult;
    } catch (e) {
      console.log('queryTmInfo查询失败');
      return e;
    }
  }

  //联系人信息查询-联系人地址信息推送接口 
  async queryTmCustomerInfo() {
    try {
      let sql = "SELECT orderNum,contactAddress,customerContact,mobile,email,zipCode FROM `h_tmcustomer_info`  WHERE contactAddress != '' AND addressIsPushed = '0' LIMIT 50;";
      let customerResult = await this.dao.customQuery(sql);
      return customerResult;
    } catch (e) {
      console.log('queryTmCustomerInfo查询失败');
      return e;
    }
  }

  //联系人信息更新-更新推送状态为1(已推送)
  async updateTmCustomerInfo(orderNum) {
    try {
      let sql = "UPDATE `h_tmcustomer_info` SET  addressIsPushed = '1'  WHERE orderNum = '" + orderNum + "';";
      let updateResult = await this.dao.customUpdate(sql);
      return updateResult;
    } catch (e) {
      console.log('updateTmCustomerInfo更新失败');
      return e;
    }
  }

  async queryTmFlowInfoForPush(tmRegistNum) {
    try {
      let sql = "SELECT * FROM `h_tm_flow` WHERE tmRegistNum='" + tmRegistNum + "';";
      let tmFlowResult = await this.dao.customQuery(sql);
      return tmFlowResult;
    } catch (e) {
      console.log('queryTmFlowInfoForPush查询失败');
      return e;
    }
  }

  async updateIsPushed(id) {
    // try {
    //   let setObj = { isPushed: '1' };
    //   let whereObj = { where: { id: id } };
    //   let tmResult = await this.dao.updateByWhere(setObj, whereObj);
    //   return tmResult;
    // } catch (e) {
    //   console.log('updateIsPushed更新失败', e);
    // }
    try {
      let sql = "UPDATE h_trade_mark SET isPushed='1' WHERE id='" + id + "';";
      let updateResult = await this.dao.customUpdate(sql);
      return updateResult;
    } catch (e) {
      console.log('updateIsPushed更新失败', e);
      return e;
    }
  }

  //----------------------------------1688商标状态修改 结束----------------------------------------------------------------
  async getApplyNameByChannelOrderNo(pobj) {
    if (!pobj || !pobj.channelOrderNo) {
      return { code: -100, msg: "channelOrderNo is empty!" }
    }
    var tm = await this.dao.model.findOne({
      where: { channelOrderListInfo: { [this.db.Op.like]: "%" + pobj.channelOrderNo + "%" } },
      attributes: ["applyName"],
      raw: true
    });
    if (tm && tm.applyName) {
      return { code: 1, data: tm.applyName }
    }
    return { code: -101, msg: "未知申请人" };
  }
}
module.exports = TrademarkService;
// var task = new TrademarkService();
// var opUrlResult = {
//   code: 1,
//   message: "success",
//   data: {}
// };
// task.opDownFileInfo("https://trade-mark-user-upload.oss-cn-beijing.aliyuncs.com/sbj-notice/register-notice-42616081SHANG_BIAO_ZHU_CE_SHEN_QING_SHOU_LI_TONG_ZHI_SHU1576696857513.pdf?Expires=1576789472&OSSAccessKeyId=hObpgEXoca42qH3V&Signature=D3pSlc4ERLf69SlAMcKAMz10%2FWA%3D",opUrlResult).then(d=>{
//   console.log(d,"dddddddddddddddddddddddd");
// })
