const AppServiceBase = require("../../app.base");
var settings = require("../../../../config/settings");
const system = require("../../../system");

//此类用来db中配置来进行调用-主要功能是推送阿里商标业务
class UtilsTmAliyunService extends AppServiceBase {
  constructor() {
    super();
    //ICON 图标图样，CARD 身份证，ATTORNEY　授权书ossKey，PASSPORT 护照，BUSINESS_LICENSE 营业执照，LEGAL_NOTICE 法律声明，SUPPLEMENT 补正图片的上传
    this.aliOssFileType = { ICON: "ICON", CARD: "CARD", ATTORNEY: "ATTORNEY", PASSPORT: "PASSPORT", BUSINESS_LICENSE: "BUSINESS_LICENSE", LEGAL_NOTICE: "LEGAL_NOTICE", SUPPLEMENT: "SUPPLEMENT" };
  }
  //推送委托书模板邮件(阿里云)
  async sendAliWtsEmail(pobj) {
    var ab = pobj.actionBody;
    if (!ab.email) {
      return system.getResult(null, "邮箱地址不能为空");
    }
    if (!ab.type) {
      return system.getResult(null, "邮件类型不能为空");
    }
    var mailCilent = system.getObject("util.mailClient");
    var url = "";
    if (ab.type == "1") {
      var sendRes = await mailCilent.sendMsg(ab.email, "商标代理委托书", "see", "商标代理委托书", null, null, [
        { filename: '商标代理委托书', path: 'http://gsb-zc.oss-cn-beijing.aliyuncs.com/igirl_channel_tmwtsdemo001.doc' }
      ]);
      return system.getResultSuccess(sendRes);
    } else if (ab.type == "2") {
      var sendRes = await mailCilent.sendMsg(ab.email, "阿里云商标代理委托书", "see", "阿里云商标代理委托书", null, null, [
        { filename: '阿里云商标代理委托书', path: 'http://gsb-zc.oss-cn-beijing.aliyuncs.com/tmwtu2020041811188516gcjhvjwts.docx' }
      ]);
      return system.getResultSuccess(sendRes);
    } else if (ab.type == "3") {
      var sendRes = await mailCilent.sendMsg(ab.email, "阿里云声明文件", "see", "阿里云声明文件", null, null, [
        { filename: '阿里云声明文件', path: 'http://gsb-zc.oss-cn-beijing.aliyuncs.com/tm_smwj202004181626725onjdaliyun.doc' }
      ]);
      return system.getResultSuccess(sendRes);
    } else {
      return system.getResult(null, "邮件类型错误");
    }


  }
  async tmCreateApplicant(pobj) {//创建商标申请人信息
    var verifyResult = await this.opAliyunRpcVerifyParam(pobj);
    var apply = pobj.actionBody.delivery_content.apply;
    var orderContact = pobj.actionBody.delivery_content.orderContact;
    var orderInfo = pobj.actionBody.order_info;
    var tmInfo = pobj.actionBody.delivery_content.tm;
    if (!orderInfo) {
      verifyResult = system.getResult(null, "orderInfo data is empty，100450");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (Number(orderInfo.orderStatus) != 2) {
      verifyResult = system.getResult(null, "orderInfo status is error，100453");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!apply) {
      verifyResult = system.getResult(null, "apply data is empty，100455");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (apply.customerType != "ent" && !apply.identityCardPic) {
      verifyResult = system.getResult(null, "identityCardPic can not be empty，100456");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (apply.customerType == "ent" && !apply.businessLicensePic) {
      verifyResult = system.getResult(null, "businessLicensePic can not be empty，100457");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!apply.gzwtsUrl) {
      verifyResult = system.getResult(null, "gzwtsUrl can not be empty，100458");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!tmInfo) {
      verifyResult = system.getResult(null, "tmInfo data is empty，100460");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!tmInfo.picUrl) {
      verifyResult = system.getResult(null, "tm picUrl data is empty，100461");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    var rpcParam = verifyResult.data;
    var idCardOssKey = "";
    var businessLicenceOssKey = "";
    var legalNoticeOssKey = "";
    var picUrl = "";
    var authorizationOssKey = "";

    if (verifyResult.status == 0) {
      if (apply.customerType != "ent" && apply.identityCardPic) {
        idCardOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.CARD, apply.identityCardPic, rpcParam);
        if (!idCardOssKey) {
          verifyResult = system.getResult(null, "identityCardPic ali oss upload is error，100462");
        }
      }
      if (apply.customerType == "ent" && apply.businessLicensePic) {
        businessLicenceOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.BUSINESS_LICENSE, apply.businessLicensePic, rpcParam);
        if (!businessLicenceOssKey) {
          verifyResult = system.getResult(null, "businessLicensePic ali oss upload is error，100464");
        }
      }
      if (verifyResult.status == 0) {
        if (apply.smwjUrl) {
          legalNoticeOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.LEGAL_NOTICE, apply.smwjUrl, rpcParam);
          if (!legalNoticeOssKey) {
            verifyResult = system.getResult(null, "smwjUrl ali oss upload is error，100466");
          }
        }
        if (tmInfo.picUrl) {
          picUrl = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.ICON, tmInfo.picUrl, rpcParam);
          if (!picUrl) {
            verifyResult = system.getResult(null, "picUrl ali oss upload is error，100467");
          }
        }
        if (apply.gzwtsUrl) {
          authorizationOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.ATTORNEY, apply.gzwtsUrl, rpcParam);
          if (!authorizationOssKey) {
            verifyResult = system.getResult(null, "gzwtsUrl ali oss upload is error，100468");
          }
        }
      }
    }
    if (verifyResult.status != 0) {
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.NEWRPC);
    }
    var actionBody = {
      ContactName: orderContact.contactName || "",//String 	否 	张三 	联系人姓名
      ContactNumber: orderContact.mobile || "",//String 	否 	18611112222 	联系人电话
      ContactEmail: orderContact.email || "",//String 	否 	test@alibaba.com 	联系人邮箱
      ContactZipcode: apply.zipCode || "",//String 	否 	100000 	联系人邮编
      ContactAddress: apply.applyAddr,//String 	否 	北京市朝阳区绿地中心A座 	联系人地址

      ApplicantType: apply.customerType && apply.customerType == "ent" ? 2 : 1,//Integer 	否 	1 	申请人类型 1, "个人"；2, "企业"
      ApplicantRegion: 1,//Integer 	否 	1 	阿拉伯数字 1, "中国大陆"；2, "中国香港"；3, "中国澳门"；4, "中国台湾"；5, "国外"			
      ApplicantName: apply.name,//String 	否 	张三 	申请人名称
      CardNumber: apply.customerType && apply.customerType == "ent" ? apply.code : apply.identityCardNo,//String 	否 	123456 	证件号码
      Address: apply.applyAddr,//String 	否 	北京市朝阳区绿地中心A座 	申请人地址
      IdCardOssKey: idCardOssKey,//String 	否 	1219541161213057/card/ujd8hthwfdk.png 	身份证ossKey
      BusinessLicenceOssKey: businessLicenceOssKey,//String 	否 	1219541161213057/business_license/gmzl6cvbk48.png 	营业执照ossKey
      LegalNoticeOssKey: legalNoticeOssKey//String 	否 	1219541161213057/legal_notice/mlnpsjmaed.jpg 	法律声明ossKey

      // Province: apply.,//String 	否 	安徽省 	省份
      // EName: apply.,//String 	否 	zhang san 	英文名称
      // EAddress: apply.,//String 	否 	bei jing shi 	英文地址
      // Country: apply.,//String 	否 	2096 	国家
      // PassportOssKey: apply.,//String 	否 	1219541161213057/pass_port/gmzl16cvbk48.png 	护照ossKey
      // AuthorizationOssKey: apply.,//String 	否 	1219541161213057/attorney/gy378w6btam.jpg 	授权书ossKey--联系了开发，创建申请人时不用填写，在创建商标时填写
    };
    var params = {
      action: rpcParam.action,
      reqbody: actionBody,
      rpcParam: rpcParam
    }
    var applicantResult = await this.opAliyunRpcReq(pobj, params);
    if (applicantResult.status != 0) {
      applicantResult = await this.opAliyunRpcReq(pobj, params);
      if (applicantResult.status != 0) {
        return await this.disposePushResultFail(pobj, applicantResult, "ali->tmCreateApplicant->applicantResult", this.pushlogFailType.NEWRPC);
      }
    }

    actionBody.ApplicantId = applicantResult.data.ApplicantId;
    actionBody.product_id = pobj.actionBody.product_info.id;
    var addActionBody = {
      appInfo: { uapp_id: pobj.appInfo.uapp_id, uapp_key: pobj.appInfo.uapp_key },
      apply: actionBody,
      tm: []//商标信息
    }
    var classificationsResult = system.getResultSuccess();
    var tmCreateResult = system.getResultSuccess();
    var addtmCreate = 0;
    var self = this;
    for (let i = 0; i < pobj.actionBody.delivery_content.nclones.length; i++) {
      const nclonesItem = pobj.actionBody.delivery_content.nclones[i];
      classificationsResult = await self.getClassifications(pobj, nclonesItem, rpcParam);
      if (classificationsResult.status != 0) {
        classificationsResult = await self.getClassifications(pobj, nclonesItem, rpcParam);
        if (classificationsResult.status != 0) {
          classificationsResult.msg = "获取阿里尼斯数据为空，100469->" + classificationsResult.msg;
          pobj.dbNclonesItem = nclonesItem;
          self.disposePushResultFail(pobj, classificationsResult, "ali->tmCreateApplicant->classificationsResult", self.pushlogFailType.FAILLOG);
          break;
        }//第二次调用失败则尼斯调用失败
      }
      tmCreateResult = await self.tmCreate(pobj, tmInfo, rpcParam, picUrl, authorizationOssKey, classificationsResult.data, applicantResult.data.ApplicantId);
      if (tmCreateResult.status != 0) {
        tmCreateResult = await self.tmCreate(pobj, tmInfo, rpcParam, picUrl, authorizationOssKey, classificationsResult.data, applicantResult.data.ApplicantId);
        if (tmCreateResult.status != 0) {
          tmCreateResult.msg = "创建阿里商标数据为空，10471->" + tmCreateResult.msg;
          pobj.dbTmInfo = tmInfo;
          self.disposePushResultFail(pobj, tmCreateResult, "ali->tmCreateApplicant->classificationsResult", self.pushlogFailType.FAILLOG);
          break;
        }//第二次调用失败则创建商标失败
      }
      //保存渠道申请人及商标数据
      addtmCreate++;
      tmCreateResult.data.tmInfo.Classifications = classificationsResult.data;
      tmCreateResult.data.tmInfo.tbCode = nclonesItem.tbCode;
      tmCreateResult.data.tmInfo.AuthorizationOssKey = authorizationOssKey;
      tmCreateResult.data.tmInfo.OrderId = tmCreateResult.data.OrderId.tostring();
      addActionBody.tm.push(tmCreateResult.data.tmInfo);
    }
    if (addtmCreate == pobj.actionBody.delivery_content.nclones.length) {
      self.addAliChannelTmApplicant(pobj, addActionBody);
      return await self.disposePushResult(pobj, tmCreateResult, "ali->tmCreateApplicant->tmCreateResult", this.pushlogFailType.NEWRPC);
    }//更新数据库渠道商标
    else {
      tmCreateResult = system.getResult(null, "创建ali商标申请人信息出错，10472");
      return await self.disposePushResultFail(pobj, tmCreateResult, "ali->tmCreateApplicant->tmCreateResult", self.pushlogFailType.NEWRPC);
    }
  }
  async updateAliTmApplicant(pobj) {//更新商标申请人信息
    var verifyResult = await this.opAliyunRpcVerifyParam(pobj);
    var apply = pobj.actionBody.apply;

    var dbApplyResult = await this.getAliChannelTmDelivery(pobj);
    if (dbApplyResult.status != 0) {
      if (dbApplyResult.status == -130) {
        var getAddParamResult = await this.getOrderProductDeliveryByOrderNo(pobj);
        if (getAddParamResult.status == 0) {
          getAddParamResult.data.actionBody.orderNo = pobj.actionBody.orderNo;
          getAddParamResult.data.appInfo = pobj.appInfo;
          getAddParamResult.data.interface_params = pobj.interface_params;
          return await this.tmCreateApplicant(getAddParamResult.data);
        }
      }//为空则进行创建提交到阿里
      verifyResult = dbApplyResult + "，100540";
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!apply.gzwtsUrl) {
      verifyResult = system.getResult(null, "gzwtsUrl can not be empty，100541");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    var dbApply = dbApplyResult.data.apply;
    var dbTm = dbApplyResult.data.tm;
    if (!dbApply) {
      verifyResult = system.getResult(null, "tmInfo data is empty，100542");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (!dbTm) {
      verifyResult = system.getResult(null, "dbTm data is empty，100543");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (verifyResult.status != 0) {
      return await this.disposePushResultFail(pobj, verifyResult, "ali->updateAliTmApplicant->verifyResult", this.pushlogFailType.NEWRPC);
    }
    var rpcParam = verifyResult.data;
    var idCardOssKey = "";
    var businessLicenceOssKey = "";
    var legalNoticeOssKey = "";
    var authorizationOssKey = "";
    if (verifyResult.status == 0) {
      if (apply.customerType != "ent" && apply.identityCardPic) {
        idCardOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.CARD, apply.identityCardPic, rpcParam);
        if (idCardOssKey && idCardOssKey != dbApply.IdCardOssKey) {
          dbApply.IdCardOssKey = idCardOssKey;
        }
      }
      if (apply.customerType == "ent" && apply.businessLicensePic) {
        businessLicenceOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.BUSINESS_LICENSE, apply.businessLicensePic, rpcParam);
        if (businessLicenceOssKey && businessLicenceOssKey != dbApply.BusinessLicenceOssKey) {
          dbApply.BusinessLicenceOssKey = businessLicenceOssKey;
        }
      }
      if (apply.smwjUrl) {
        legalNoticeOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.LEGAL_NOTICE, apply.smwjUrl, rpcParam);
        if (legalNoticeOssKey && legalNoticeOssKey != dbApply.LegalNoticeOssKey) {
          dbApply.LegalNoticeOssKey = legalNoticeOssKey;
        }
      }
      authorizationOssKey = await this.getAliOssFileUrl("trade-mark-user-upload", pobj, this.aliOssFileType.ATTORNEY, apply.gzwtsUrl, rpcParam);
      if (!authorizationOssKey) {
        authorizationOssKey = dbApply.AuthorizationOssKey;
      }
    }
    if (apply.zipCode && apply.zipCode != dbApply.ContactZipcode) {
      dbApply.ContactZipcode = apply.zipCode;
    }
    if (apply.applyAddr && apply.applyAddr != dbApply.ContactAddress) {
      dbApply.ContactAddress = apply.applyAddr;
    }
    if (apply.name && apply.name != dbApply.ApplicantName) {
      dbApply.ApplicantName = apply.name;
    }
    if (apply.applyAddr && apply.applyAddr != dbApply.Address) {
      dbApply.Address = apply.applyAddr;
    }
    dbApply.CardNumber = apply.customerType && apply.customerType == "ent" ? apply.code : apply.identityCardNo;//String 	否 	123456 	证件号码
    dbApply.ApplicantType = apply.customerType && apply.customerType == "ent" ? 2 : 1;//Integer 	否 	1 	申请人类型 1, "个人"；2, "企业"

    // ContactName: orderContact.contactName || "",//String 	否 	张三 	联系人姓名
    // ContactNumber: orderContact.mobile || "",//String 	否 	18611112222 	联系人电话
    // ContactEmail: orderContact.email || "",//String 	否 	test@alibaba.com 	联系人邮箱

    if (apply.customerType != "ent" && !dbApply.IdCardOssKey) {
      verifyResult = system.getResult(null, "identityCardPic can not be empty，100544");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }
    if (apply.customerType == "ent" && !dbApply.BusinessLicenceOssKey) {
      verifyResult = system.getResult(null, "businessLicensePic can not be empty，100545");
      return await this.disposePushResultFail(pobj, verifyResult, "ali->tmCreateApplicant->verifyResult", this.pushlogFailType.FAILLOG);
    }

    if (dbApply.ApplicantId) {
      delete dbApply["ApplicantId"];
    }
    var params = {
      action: rpcParam.action,
      reqbody: dbApply,
      rpcParam: rpcParam
    }
    var applicantResult = await this.opAliyunRpcReq(pobj, params);
    if (applicantResult.status != 0) {
      applicantResult = await this.opAliyunRpcReq(pobj, params);
      if (applicantResult.status != 0) {
        applicantResult.msg = "创建阿里商标申请人出错，100546->" + applicantResult.msg;
        return await this.disposePushResultFail(pobj, applicantResult, "ali->updateAliTmApplicant->CreateApplicant->applicantResult", this.pushlogFailType.NEWRPC);
      }
    }

    //绑定商标的oss委托书信息
    dbApply.ApplicantId = applicantResult.data.ApplicantId;
    dbApplyResult.data.apply = dbApply;
    //授权委托书
    var self = this;
    var updateTm = 0;
    var opUpdateTmResult = system.getResultSuccess();
    for (let j = 0; j < dbApplyResult.data.tm.length; j++) {
      var tmItem = dbApplyResult.data.tm[j];
      if (tmItem) {
        var bizId = ""
        if (!tmItem.BizId) {
          var getDingTmStatusResult = await self.getAliTmInfo(pobj, tmItem.OrderId, rpcParam);
          if (getDingTmStatusResult.status != 0) {
            pobj.dbTm = tmItem;
            getDingTmStatusResult.msg = "查询阿里商标状态出错，100547->" + getDingTmStatusResult.msg;
            self.disposePushResultFail(pobj, getDingTmStatusResult, "ali->updateAliTmApplicant->getDingTmStatusResult", self.pushlogFailType.FAILLOG);
            break;
          }
          if (getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].ApplicationStatus != 2) {
            getDingTmStatusResult.status = -1;
            getDingTmStatusResult = "更新商标申请人信息失败，阿里商标状态不是阿里云审核不通过，不能进行修改，100558->" + getDingTmStatusResult.msg;
            self.disposePushResultFail(pobj, getDingTmStatusResult, "ali->updateAliTmApplicant->getDingTmStatusResult", self.pushlogFailType.FAILLOG);
            continue;
          }
          bizId = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].BizId;
          dbApplyResult.data.tm[j].BizId = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].BizId;
          dbApplyResult.data.tm[j].ApplicationStatus = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].ApplicationStatus;
          dbApplyResult.data.tm[j].Note = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].Note;
          dbApplyResult.data.tm[j].TotalPrice = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].TotalPrice;
        }//处理ali 商标状态查询
        else {
          bizId = tmItem.BizId;
        }
        //绑定商标申请人信息（绑定授权书Oss文件）
        dbApplyResult.data.tm[j].AuthorizationOssKey = authorizationOssKey;
        var bindAliTmApplicantGzwtsUrlResult = await this.bindAliTmApplicantGzwtsUrl(pobj, rpcParam, dbApply.ApplicantId, bizId, authorizationOssKey);
        if (bindAliTmApplicantGzwtsUrlResult.status != 0) {
          pobj.dbTm = tmItem;
          bindAliTmApplicantGzwtsUrlResult.msg = "绑定授权书Oss文件出错，100559->" + bindAliTmApplicantGzwtsUrlResult.msg;
          self.disposePushResultFail(pobj, bindAliTmApplicantGzwtsUrlResult, "ali->updateAliTmApplicant->bindAliTmApplicantGzwtsUrlResult", self.pushlogFailType.FAILLOG);
          break;
        }
        updateTm++;
      }
    }
    if (updateTm == dbTm.length) {
      self.updateAliChannelTmApplicant(pobj, dbApplyResult.data);
      return await self.disposePushResult(pobj, opUpdateTmResult, "ali->updateAliTmApplicant->opUpdateTmResult", self.pushlogFailType.NEWRPC);
    }//更新数据库渠道商标
    else {
      opUpdateTmResult = system.getResult(null, "更新ali商标申请人信息出错，100548");
      return await self.disposePushResultFail(pobj, opUpdateTmResult, "ali->updateAliTmApplicant->opUpdateTmResult", self.pushlogFailType.NEWRPC);
    }
  }


  //--------------------------------------------------内部辅助方法-------------------start-----------------

  async tmCreate(pobj, tmInfo, rpcParam, picUrl, authorizationOssKey, classifications, applicantId) {//创建商标申请信息-内部使用－配合tmCreateApplicant方法使用
    // 商标类型形式： 3: 字, 4: 图, 5: 字图
    var trademarkNameType = 1;
    if (tmInfo.tmFormType == "4") {
      trademarkNameType = 2;
    }
    if (tmInfo.tmFormType == "5") {
      trademarkNameType = 3;
      tmInfo.tmName = tmInfo.tmName + "及图";
    }
    var actionBody = {
      AutoPay: true,
      TrademarkNameType: trademarkNameType,//String 	否 	1 	商标申请类型 1-文字 2-图形 3-文字及图形
      TrademarkName: tmInfo.tmName,//String 	是 	pop-test 	商标名称
      TrademarkComment: tmInfo.tmName,//String 	否 	测试 	商标说明  
      TrademarkIcon: picUrl,//String 	是 	1219541161213057/icon/gii9s4oyg8.jpg 	商标对应图案的ossKey,有彩色图标请填写彩色图标，没有请填写黑白图标
      BlackAndWhiteIcon: picUrl,//String 	否 	1219541161213057/icon/gii9s4oyg8.jpg
      ApplicationType: 1,//Integer 	否 	1 	固定值1
      ApplicantId: applicantId,//String 	否 	111 	申请人ID，通过申请人API创建申请人获得，或者通过申请人列表查询接口获得
      Classifications: JSON.stringify(classifications),//String 	是 	{"38":"380005,380024,380050,380040,38020148,380004,38010007,38020149,38020141,380053"} 	商标分类

      AuthorizationOssKey: authorizationOssKey,//String 	否 	1219541161213057/attorney/9cgvhk2yd1l.JPG 	授权书ossKey
      Channel: "aliTmH5"//String 	否 	pop接口测试 	通道，调用方填写，独立标志，用于区分来源－自己随便定义
    };
    var params = {
      action: "CreateTrademarkApplication",
      reqbody: actionBody,
      rpcParam: rpcParam
    }
    var tmCreateReslut = await this.opAliyunRpcReq(pobj, params);
    if (tmCreateReslut.status == 0) {
      tmCreateReslut.data.tmInfo = actionBody;
    }
    return tmCreateReslut;
    // return system.getResultSuccess({ "orderId": "204426185080629" });
  }
  async bindAliTmApplicantGzwtsUrl(pobj, rpcParam, applicantId, bizId, authorizationOssKey) {//绑定商标申请人信息-(绑定授权书Oss文件)---内部使用
    if (!authorizationOssKey) {
      return system.getResult(null, "gzwtsUrl param is empty，100503");
    }
    var params = {
      action: "BindApplicant",
      reqbody: { ApplicantId: applicantId, AuthorizationOssKey: authorizationOssKey, BizId: bizId },
      rpcParam: rpcParam
    }
    //BizId-----报 BizId is mandatory for this action－－BizId是此操作的强制命令
    var result = await this.opAliyunRpcReq(pobj, params);
    if (result.status != 0) {
      result = await this.opAliyunRpcReq(pobj, params);
    }
    return result;
  }
  async getAliOssFileUrl(bucketName, pobj, fileType, selfFileUrl, rpcParam) {
    var fileUrl = "";
    var resultInfo = await this.getAliOssInfo(pobj, fileType, rpcParam);
    if (resultInfo.status != 0) {
      resultInfo = await this.getAliOssInfo(pobj, fileType, rpcParam);
      if (resultInfo.status != 0) {
        return fileUrl;
      }
    }
    let lastHostLength = resultInfo.data.Host.lastIndexOf('/');
    let lastFileLength = selfFileUrl.lastIndexOf('/');
    var params = {
      "ossurl": selfFileUrl,
      "endpoint": "https:" + resultInfo.data.Host.substring(0, lastHostLength),
      "accessKeyId": resultInfo.data.AccessId,
      "bucketName": bucketName,//"trade-mark-user-upload",
      "filedir": resultInfo.data.FileDir,
      "objectName": selfFileUrl.substring(lastFileLength + 1, selfFileUrl.length),
      "encodePolicy": resultInfo.data.EncodedPolicy,
      "signature": resultInfo.data.Signature
    }
    var ossFileResult = await this.getAliossjavaFileUrl(pobj, params);
    if (ossFileResult.status == 0) {
      fileUrl = ossFileResult.data;
    }
    return fileUrl;
  }
  async getAliOssInfo(pobj, fileType, rpcParam) {
    var params = {
      action: "GenerateUploadFilePolicy",
      reqbody: { FileType: fileType },
      rpcParam: rpcParam
    }
    var resultInfo = await this.opAliyunRpcReq(pobj, params);
    return resultInfo;
  }
  async getClassifications(pobj, nclones, rpcParam) {
    var self = this;
    var aliNclThreesList = {};
    var aliNclTwosList = [];
    const nclOneItem = nclones;
    var nclThreeList = nclOneItem.nclThree;
    var getAliThreeList = [];
    for (let j = 0; j < nclThreeList.length; j++) {
      const nclThreeItem = nclThreeList[j];
      var aliThreeList = null;
      var aliNclTwosListIndex = aliNclTwosList.findIndex(f => f.pcode === nclThreeItem.pcode);
      if (aliNclTwosListIndex < 0) {
        var aliNclDataResult = await self.getAliNclInfo(pobj, nclThreeItem.pcode, rpcParam);
        if (aliNclDataResult.status == 0) {
          aliThreeList = aliNclDataResult.data;
          aliNclTwosList.push({
            pcode: nclThreeItem.pcode,
            nclThree: aliThreeList
          });
        }
      }//获取ali 的信息
      else {
        aliThreeList = aliNclTwosList[aliNclTwosListIndex].nclThree;
      }
      if (!aliThreeList) {
        continue;
      }
      for (let k = 0; k < aliThreeList.length; k++) {
        const aliNclThree = aliThreeList[k];
        if (aliNclThree.ClassificationName == nclThreeItem.name) {
          getAliThreeList.push(aliNclThree.ClassificationCode);
          break;
        }
      }
    }//一个大类下小项组装完毕
    if (getAliThreeList.length == 0) {
      return system.getResult(null, "获取阿里尼斯数据失败，100530");
    }
    aliNclThreesList[nclOneItem.code] = getAliThreeList.join(',');
    return system.getResultSuccess(aliNclThreesList)
  }
  async getAliNclInfo(pobj, parentCode, rpcParam) {
    var params = {
      action: "ListClassifications",
      reqbody: { ParentCode: parentCode },
      rpcParam: rpcParam
    }
    var nclInfoResult = await this.opAliyunRpcReq(pobj, params);
    if (nclInfoResult.status != 0 || !nclInfoResult.data || nclInfoResult.data.TotalCount == 0) {
      return system.getResult(null, "ali ncl is empty，100465")
    }
    return system.getResultSuccess(nclInfoResult.data.Classifications.Classification);
  }

  async getAliTmInfo(pobj, orderId, rpcParam) {//通过阿里订单号获取阿里商标申请信息--内部调用
    var tmStatusParams = {
      action: "ListTrademarkApplications",
      reqbody: { OrderId: orderId },
      rpcParam: rpcParam
    }
    var getDingTmStatusResult = await this.opAliyunRpcReq(pobj, tmStatusParams);
    if (getDingTmStatusResult.status != 0) {
      getDingTmStatusResult = await this.opAliyunRpcReq(pobj, tmStatusParams);
    }
    return getDingTmStatusResult;
  }

  //-------------------------操作渠道商标信息

  async addAliChannelTmApplicant(pobj, actionBody) {//新增ali渠道商标交付信息
    var tmpPobj = {
      actionType: "addAliChannelTmApplicant",
      appInfo: pobj.appInfo,
      actionBody: { deliveryData: actionBody, orderNo: pobj.actionBody.orderNo }
    }
    var reqUrl = settings.centerOrderUrl() + "opaction/opOrder/springBoard";
    var result = await this.restPostUrl(tmpPobj, reqUrl);
    if (result.status != 0) {
      return await this.disposePushResultFail(tmpPobj, result, "ali->tmCreateApplicant->addChannelTmApplicantResult->新增ali渠道商标交付信息失败", this.pushlogFailType.FAILLOG);
    }
    return result;
  }
  async updateAliChannelTmApplicant(pobj, actionBody) {//新增ali渠道商标交付信息
    var tmpPobj = {
      actionType: "updateAliChannelTm",
      appInfo: pobj.appInfo,
      actionBody: { deliveryData: actionBody, orderNo: pobj.actionBody.orderNo }
    }
    var reqUrl = settings.centerOrderUrl() + "opaction/opOrder/springBoard";
    var result = await this.restPostUrl(tmpPobj, reqUrl);
    if (result.status != 0) {
      return await this.disposePushResultFail(tmpPobj, result, "ali->tmCreateApplicant->addChannelTmApplicantResult->新增ali渠道商标交付信息失败", this.pushlogFailType.FAILLOG);
    }
    return result;
  }
  async getAliChannelTmDelivery(pobj) {//查询ali渠道商标交付信息
    var tmpPobj = {
      actionType: "getAliChannelTmDelivery",
      appInfo: pobj.appInfo,
      actionBody: { orderNo: pobj.actionBody.orderNo }
    }
    var reqUrl = settings.centerOrderUrl() + "opaction/opOrder/springBoard";
    var result = await this.restPostUrl(tmpPobj, reqUrl);
    return result;
  }
  async getAllAliChannelTmDelivery(pobj) {//查询ali渠道商标交付信息－内部方法
    var tmpPobj = {
      actionType: "getAllAliChannelTmDelivery",
      appInfo: {},
      actionBody: {}
    }
    var reqUrl = settings.centerOrderUrl() + "opaction/opOrder/springBoard";
    var result = await this.restPostUrl(tmpPobj, reqUrl);
    return result;
  }
  async getOrderProductDeliveryByOrderNo(pobj) {//获取订单产品及交付信息--用于钉钉商标推送
    var tmpPobj = {
      actionType: "getOrderProductDeliveryByOrderNo",
      appInfo: pobj.appInfo,
      actionBody: { orderNo: pobj.actionBody.orderNo }
    }
    var reqUrl = settings.centerOrderUrl() + "opaction/opOrder/springBoard";
    var result = await this.restPostUrl(tmpPobj, reqUrl);
    return result;
  }
  //--------------------------------------------------内部辅助方法-------------------end-----------------

  //--------------------------------------------------供外部调用方法-----------------start---------------

  async opAliDingInterfaceManage(pobj) {//操作阿里钉钉接口管理---外部调用
    var verifyResult = await this.opAliyunRpcVerifyParam(pobj);
    if (verifyResult.status != 0) {
      return await this.disposePushResultFail(pobj, verifyResult, "ali->opAliDingInterfaceManage->verifyResult", this.pushlogFailType.FAILLOG);
    }
    var rpcParam = verifyResult.data;
    var params = {
      action: pobj.action,
      reqbody: pobj.actionBody,
      rpcParam: rpcParam
    }
    var result = await this.opAliyunRpcReq(pobj, params);
    if (result.status != 0) {
      result = await this.opAliyunRpcReq(pobj, params);
    }
    return result;
  }

  async taskAliTmUpdate() {//操作阿里商标更新任务---外部调用
    var pobj = { actionBody: {} };
    var dbAliAllTmListResult = await this.getAllAliChannelTmDelivery(pobj);
    if (dbAliAllTmListResult.status != 0) {
      dbAliAllTmListResult.msg = "操作阿里商标更新任务，查询的数据为空，100550->" + dbAliAllTmListResult.msg;
      return await this.disposePushResultFail(pobj, dbAliAllTmListResult, "ali->opAliTmUpdateTask->dbAliAllTmListResult", this.pushlogFailType.FAILLOG);
    }
    var opResult = system.getResultSuccess();
    var rpcParam = null;
    var self = this;
    for (let index = 0; index < dbAliAllTmListResult.data.length; index++) {
      const element = dbAliAllTmListResult.data[index];
      if (element) {
        if (opResult.status != 0) {
          break;
        }
        pobj.actionBody.orderNo = element.sourceOrderNo;
        if (!rpcParam) {
          pobj.appInfo = element.deliveryContent.appInfo;
          var pushInterfaceResult = await self.getOpInterfaceByProductId(element.deliveryContent.appInfo, element.deliveryContent.product_id);
          if (pushInterfaceResult.status != 0) {
            pushInterfaceResult.msg = "操作阿里商标更新任务，查询的产品接口数据为空，100553->" + pushInterfaceResult.msg;
            opResult = pushInterfaceResult;
            self.disposePushResultFail(pobj, pushInterfaceResult, "ali->opAliTmUpdateTask->pushInterfaceResult", self.pushlogFailType.FAILLOG);
            break;
          }
          var interface_list_temp = pushInterfaceResult.data.filter(f => f.op_type == "createAliTmApply");
          if (!interface_list_temp || interface_list_temp.length == 0) {
            opResult = system.getResult(null, "暂无【createAliTmApply】的推送配置，100555");
            self.disposePushResultFail(pobj, opResult, "ali->opAliTmUpdateTask->interface_list_temp", self.pushlogFailType.FAILLOG);
            break;
          }
          rpcParam = JSON.parse(interface_list_temp[0].params);
        }
        var tmUpdate = 0;
        for (let i = 0; i < element.deliveryContent.tm.length; i++) {
          const tmItem = element.deliveryContent.tm[i];
          if (tmItem) {
            var getDingTmStatusResult = await self.getAliTmInfo(pobj, tmItem.OrderId, rpcParam);
            if (getDingTmStatusResult.status != 0 || getDingTmStatusResult.data.TotalCount == 0) {
              getDingTmStatusResult.msg = "操作阿里商标更新任务，查询的阿里商标数据错误，100557->" + getDingTmStatusResult.msg;
              opResult = getDingTmStatusResult;
              self.disposePushResultFail(pobj, getDingTmStatusResult, "ali->opAliTmUpdateTask->getDingTmStatusResult", self.pushlogFailType.FAILLOG);
              break;
            }
            var noteStr = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].Note;
            if (noteStr) {
              if (noteStr.lastIndexOf('}') < 0) {
                element.deliveryContent.tm[i].Note = noteStr;
              }
              else {
                var opNoteInfo = JSON.parse(noteStr);
                if (opNoteInfo.txt) {
                  var txtList = opNoteInfo.txt.split('\n');
                  var txtStr = "";
                  for (let l = 0; l < txtList.length; l++) {
                    const temptxtStr = txtList[l];
                    if (temptxtStr) {
                      txtStr = txtStr + temptxtStr;
                    }
                  }
                  element.deliveryContent.tm[i].Note = txtStr;
                }
              }
            }
            element.deliveryContent.tm[i].BizId = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].BizId;
            element.deliveryContent.tm[i].ApplicationStatus = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].ApplicationStatus;
            element.deliveryContent.tm[i].TotalPrice = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].TotalPrice;
            if (getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].SupplementStatus) {
              element.deliveryContent.tm[i].SupplementStatus = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].SupplementStatus;
              if (getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].SupplementId) {
                element.deliveryContent.tm[i].SupplementId = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].SupplementId;
              }
            }
            tmUpdate++;
            //异步操作启服通商标状态更新
            self.opSelfTmStatusUpdate(pobj, getDingTmStatusResult, element.deliveryContent.tm[i].Note, tmItem.tbCode, element.sourceOrderNo);
          }
        }
        if (tmUpdate > 0) {
          self.updateAliChannelTmApplicant(pobj, element.deliveryContent);
        }
      }
    }
    return opResult;
  }

  async opSelfTmStatusUpdate(pobj, getDingTmStatusResult, opNotes, tbCode, orderNo) {//异步操作启服通商标状态更新
    var aliStatusResult = await this.aliStatusInfo(getDingTmStatusResult);
    if (aliStatusResult.status != 0) {
      aliStatusResult.msg = "异步操作启服通商标状态更新->阿里状态码表匹配失败->" + aliStatusResult.msg;
      this.disposePushResultFail(pobj, aliStatusResult, "ali->opSelfTmStatusUpdate->aliStatusResult", this.pushlogFailType.FAILLOG);
      return aliStatusResult;
    }
    var actionBody = {
      orderNo: orderNo,
      tbCode: tbCode,
      tmStatus: aliStatusResult.data
    }
    if (opNotes) {
      actionBody.opNotes = opNotes;
    }
    var reqUrl = settings.centerOrderUrl() + "notifyaction/internalCallsNotify/updateTmStatus";
    var opResult = await this.execPostUrl(actionBody, reqUrl);
    if (opResult.status != 0) {
      opResult.msg = "异步操作启服通商标状态更新失败->" + opResult.msg;
      this.disposePushResultFail(pobj, opResult, "ali->opSelfTmStatusUpdate->opResult", this.pushlogFailType.FAILLOG);
    }
    return opResult;
  }

  async aliStatusInfo(getDingTmStatusResult) {
    // "1": "商标注册申请书", "2": "商标注册申请补正通知书", "3": "商标注册申请受理通知书", "4": "商标注册申请不予受理通知书", "5": "商标注册同日申请补送使用证据通知书",
    // "6": "商标注册同日申请协商通知书商标注册同日申请抽签通知书", "7": "商标驳回通知书", "8": "商标部分驳回通知书", "9": "商标注册申请初步审定公告通知书",
    // "10": "商标异议答辩通知书", "11": "异议裁定书", "12": "纸质版商标注册证", "13": "电子版商标注册证",
    // "16": "已失败退款", "200": "已补正", "201": "超时未补正", "202": "补正已递交到商标局",
    // "dsccl": "待上传材料", "dqrfa": "待确认方案", "fabtg": "方案不通过", "dsh": "待审核", "shbtg": "审核不通过", "ddj": "待递交", "ydj": "已递交", "djyc": "递交异常"
    var self = this;
    var aliStatus = system.getResult(null, "阿里状态码表对照有误！");
    var supplementStatus = getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].SupplementStatus;
    if (supplementStatus && supplementStatus > 2) {
      switch (pobj.supplementStatus) {
        case 2://需要补正，fileUrl为商标局补正文件
          aliStatus.status = 0;
          aliStatus.data = "2";
          break;
        case 4://已补正
          aliStatus.status = 0;
          aliStatus.data = "200";
          break;
        case 5://超时未补正
          aliStatus.status = 0;
          aliStatus.data = "201";
          break;
        case 6://补正已递交到商标局
          aliStatus.status = 0;
          aliStatus.data = "202";
          break;
        default:
          break;
      }
    } else {
      switch (getDingTmStatusResult.data.TrademarkApplications.TrademarkApplication[0].ApplicationStatus) {
        case 1://待阿里审核(已支付)
          aliStatus.status = 0;
          aliStatus.data = "dsh";
          break;
        case 2://阿里云审不通过
          aliStatus.status = 0;
          aliStatus.data = "shbtg";
          break;
        case 3://阿里审核通过
          aliStatus.status = 0;
          aliStatus.data = "ddj";
          break;
        case 4://已失败退款(阿里)
          aliStatus.status = 0;
          aliStatus.data = "16";
          break;
        case 20://-已提交到商标局
          aliStatus.status = 0;
          aliStatus.data = "ydj";
          break;
        case 21://商标局已接受（⽂件：商标局回执）
          aliStatus.status = 0;
          aliStatus.data = "1";
          break;
        case 22://商标局不予受理 （⽂件：不予受理通知书）
          aliStatus.status = 0;
          aliStatus.data = "4";
          break;
        case 23://商标局受理通过（⽂件：受理通知书）
          aliStatus.status = 0;
          aliStatus.data = "3";
          break;
        case 29://-商标局部分驳回 （⽂件：部分驳回通知书）
          aliStatus.status = 0;
          aliStatus.data = "8";
          break;
        case 30://商标局驳回 （⽂件：驳回通知书）
          aliStatus.status = 0;
          aliStatus.data = "7";
          break;
        case 31://商标局审核通过 （⽂件：审核通过通知书）----初步审定公告
          aliStatus.status = 0;
          aliStatus.data = "9";
          break;
        case 99://申请成功结束 （⽂件：商标证通知书）---已下发商标注册证
          aliStatus.status = 0;
          aliStatus.data = "13";
          break;
        default:
          break;
      }
    }
    return aliStatus;
  }

  //--------------------------------------------------供外部调用方法-----------------end---------------



}
module.exports = UtilsTmAliyunService;
