const system = require("../../system");
const settings = require("../../../config/settings");
const uuidv4 = require('uuid/v4');
const logCtl = system.getObject("web.oplogCtl");
class ChannelReceiveService {
  constructor() {
    this.orderSve = system.getObject("service.orderSve");
    this.channelApiUrl = settings.channelApiUrl();
    this.channelreceiveDao = system.getObject("db.channelreceiveDao");
  }
  //--------------接收渠道订单数据---start-------------------------------------------------------------
  //商标自动提报(渠道)
  async createChannelOrder(obj) {
    var self = this;
    var result = { code: "1", msg: "success", order: null };
    var channelOrder = obj.order_info;
    var channelUser = obj.userInfo;
    var channelProduct = obj.product_info;
    var deliveryData = obj.delivery_content;//商标交付信息
    if (!deliveryData || !deliveryData.tm || !deliveryData.apply || !deliveryData.nclones || !deliveryData.orderContact) {
      result.code = "-108";
      result.msg = "商标交付信息错误";
      return result;
    }
    if (!channelProduct || !channelProduct.channel_item_code) {
      result.code = "-109";
      result.msg = "渠道产品错误";
      return result;
    }
    var itemCode = channelProduct.channel_item_code;
    var apply = deliveryData.apply;
    var orderContact = deliveryData.orderContact;
    var tm = deliveryData.tm;
    var nclones = deliveryData.nclones;
    var user = obj.user;
    var app = obj.app;
    var channel = obj.channel;
    var serviceItem = await self.orderSve.servicesitemDao.findOne({ code: itemCode, channelCode: channel.channelCode });//服务项信息
    if (!serviceItem) {
      result.code = "-120";
      result.msg = "渠道产品不存在";
      return result;
    }
    var orderbefore = await this.orderSve.dao.model.findOne({
      where: { app_id: app.id, channelOrderNum: channelOrder.channelServiceNo },
      raw: true
    });
    if (orderbefore && orderbefore.id) {
      result.code = "-121";
      result.msg = "渠道订单已存在";
      return result;
    }
    return this.orderSve.db.transaction(async function (t) {
      var u = await self.orderSve.getCreateOrderNum();//====================订单号生成
      //创建订单对象 orderType:"1",itemCode:"sbzc",
      var orderObj = {
        applyName: apply.name || "",
        remark: deliveryData.notes || "",
        referrerProfit: 0, userName: user.userName, totalPlatformCost: 0,
        platformProfitRatio: 0, referrerProfitRatio: 0,
        platformProfit: 0, userProfit: 0,
        orderNum: u, app_id: app.id, user_id: user.id, onlyCode: user.onlyCode, shopOnlyCode: user.onlyCode,
        nickName: user.nickName,
        customerContact: orderContact.contactName, customerMobile: orderContact.mobile,
        itemOrderNum: nclones.length, itemOrderConsumeNum: nclones.length,
        itemType: serviceItem.itemType,
        itemCode: itemCode,
        orderType: "32",//渠道下单
        orderSourceType: "4",//订单来源类型
        channelCode: channel.channelCode,///////////////////////////////////////////
        channelName: channel.channelName,
        itemName: serviceItem.name, channelOrderNum: channelOrder.channelServiceNo, channelUserId: channelUser.channel_userid,
        totalPublicExpense: 0, totalInvoiceTaxes: 0, orderStatus: "4",
        totalServiceCharge: 0, totalSum: 0, orderSourceType: "1", isSubProduct: 1,
        itemTypeTwoType: 0//和是否提报产品结合使用：服务项目类型的二级类型0没有、1软件著作权、2作品著作权
      };
      tm["channelUserId"] = channelUser.channel_userid || "";
      tm["channelOrderNum"] = channelOrder.channelServiceNo || "";
      // tm["needId"] = channelOrder.channelServiceNo || "";
      tm["channelOrderListInfo"] = channelOrder.channelServiceNo || "";
      tm["channelPayStatus"] = "yzf"; //推过来都是已支付
      orderObj["orderStatus"] = "4";//channelOrder.payStatus == "yfk" ? "4" : "1";//推过来都是已支付
      if (apply.gzwtsUrl && apply.businessLicensePdf && apply.customerType == "ent") {
        orderObj.orderStatus = "32";
        tm["tmStatus"] = "WAITARTIFICIALEXAMINE";
      } else if (apply.gzwtsUrl && apply.businessLicensePdf && apply.customerType == "person" && apply.identityCardPdf) {
        orderObj.orderStatus = "32";
        tm["tmStatus"] = "WAITARTIFICIALEXAMINE";
      }
      if (channel && channel.channelCode) {
        var judgeRes = self.orderSve.trademarkDao.judgeChannelCode(channel.channelCode);//判断渠道码
        if (judgeRes) {
          tm["tmSourceType"] = judgeRes;
        }
      }
      return self.orderSve.dao.create(orderObj, t).then(async function (order) {//订单
        var orderflowObj = {
          app_id: app.id, user_id: user.id, userName: user.userName,
          nickName: user.nickName, orderNum: order.orderNum, opContent: "创建订单"
        };
        var orderflow = await self.orderSve.orderflowDao.create(orderflowObj, t);//订单流程
        //项目类型:ip:商标,ic:版权,pa:专利,iso:海外业务,common:增值服务,icbc:工商注册,zscq:知识产权,cwfw:财务服务,hyzz:行业资质,gqzr:股权转让,xzsp:行政审批
        //商标数据
        await self.createChannelOrderToAddTradeMark(self, user, app, deliveryData, order, t);
        result.order = order;
        return result;
      })
    })

  };
  //添加商标数据
  async createChannelOrderToAddTradeMark(self, user, app, delivery_content, order, t) {
    var tm = delivery_content.tm;
    var nclones = delivery_content.nclones;
    var apply = delivery_content.apply;
    var orderContact = delivery_content.orderContact;
    var customerObj = {
      zipCode: apply.zipCode || "", order_id: order.id, orderNum: order.orderNum,
      customerContact: orderContact.contactName, mobile: orderContact.mobile, email: orderContact.email,
      channelOrderNum: order.channelOrderNum
    };
    var customer = await self.orderSve.tmcustomerinfoDao.create(customerObj, t);//商标联系人
    var applierObj = {
      orderNum: order.orderNum, type: apply.customerType, applyName: apply.name,
      identityCard: apply.identityCardNo, creditCode: apply.code,
      applyAddr: apply.applyAddr, identityCardPic: apply.identityCardPdf,
      businessLicensePic: apply.businessLicensePdf, channelOrderNum: order.channelOrderNum,
      identityCardPic2: apply.identityCardPic,
      businessLicensePic2: apply.businessLicensePic
    };
    if (tm.tmFormType) {
      tm.tmFormType = tm.tmFormType.toString();
    }
    var applier = await self.orderSve.tmapplierinfoDao.create(applierObj, t);//商标申请人信息
    for (var i = 0; i < nclones.length; i++) {
      var nclone = nclones[i];
      var nclthreeobj = nclone.nclThree;
      nclthreeobj = JSON.stringify(nclthreeobj);
      var key = await self.orderSve.getUUId(user.id);
      var tmobj = {
        "applyName": apply.name,
        "tmRegistNum": "",
        "partnerMobile": user.mobile,
        "app_id": app.id,
        "user_id": user.id,
        "userName": user.userName,
        "onlyCode": user.onlyCode,
        "orderNum": order.orderNum,
        "tmType": "p",
        "tmFormType": tm.tmFormType,
        "nclOneCodes": nclone.code,
        "nclCount":nclone.nclCount,
        "nclPublicExpense":nclone.nclPublicExpense,
        "tmStatus": tm.tmStatus || "READY",
        "colorizedPicUrl": tm.colorizedPicUrl,
        "nclSmallCodes": nclthreeobj,
        "tmName": tm.tmName,
        "picUrl": tm.picUrl,
        "descUrl": apply.smwjUrl || "",
        "proxyCode": nclone.tbCode,
        "sealAuthorizeStuff": apply.gzwtsUrl,
        "channelOrderNum": tm.channelOrderNum || "",
        "channelUserId": tm.channelUserId || "",
        "channelPayStatus": tm.channelPayStatus || "wzf",
        "tmSourceType": tm.tmSourceType || "64",
        "needId": tm.needId || "",
        "channelOrderListInfo": tm.channelOrderListInfo || "",

      };
      var trademark = await self.orderSve.trademarkDao.create(tmobj, t);
    }
  }
  //修改商标订单
  async updateChannelTmInfo(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var channelOrder = obj.order_info;
    var channelUser = obj.userInfo;
    var deliveryOrderNo = obj.orderNo;//渠道订单号
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "渠道订单号不能为空");
    }
    // 1.获取交付单信息
    var orderItem = await this.orderSve.dao.model.findOne({
      where: { channelOrderNum: deliveryOrderNo, app_id: app.id },
      raw: true
    });
    if (!orderItem) {
      return { code: -102, msg: "系统中未查到相应订单，无法修改" };
    }
    if (orderItem.user_id != user.id) {
      return { code: -104, msg: "非本人订单，无法修改" };
    }
    var tms = await self.orderSve.trademarkDao.model.findAll({ where: { channelOrderNum: deliveryOrderNo, app_id: app.id }, raw: true });
    var tradem = null;
    for (var i = 0; i < tms.length; i++) {
      tradem = tms[i];
      if (["WAITCONFIRM", "CONFIRMFAIL", "4", "FILLEXCEPTION", "READY", "DOCFINISH", "AWAITCHECK", "WAITARTIFICIALEXAMINE", "WAITCOMMIT", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "SUBALITM", "REQALIERROR", "SUBALITMOK"].indexOf(tradem.tmStatus) < 0) {
        return { code: -103, msg: "存在状态为" + tradem.tmStatusName + "的商标，不能修改" };
      }
    }
    return await self.orderSve.db.transaction(async function (t) {
      var res = { code: -100 };
      if(obj.tm){
        res = await self.updateTm(tms,obj.tm,user,app,deliveryOrderNo,orderItem,self,t);
      }else if(obj.nclones && obj.nclones.length>0){
        res = await self.updateNcl(obj.nclones,app,deliveryOrderNo,orderItem,self,t);
      }else if(obj.apply){
        res = await self.updateApply(tms,obj.apply,app,deliveryOrderNo,orderItem,self,t);
      }
      return res;
    })
  }

  // 商标订单修改-商标信息修改
  async updateTm(tms,tm,user,app,deliveryOrderNo,orderItem,self,t){
    var tmObj = {
      channelOrderNum: deliveryOrderNo
    };
    if ("picUrl" in tm) {//商标图样 黑白
      tmObj["picUrl"] = tm.picUrl;
    }
    if ("colorizedPicUrl" in tm) {//彩色商标图样
      tmObj["colorizedPicUrl"] = tm.colorizedPicUrl;
    }
    if ("tmName" in tm) {//商标名称
      tmObj["tmName"] = tm.tmName;
    }
    if ("tmFormType" in tm) {//商标类型
      tmObj["tmFormType"] = tm.tmFormType.toString();
    }
    var applier2 = await self.orderSve.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    var tmStatus = "READY";
    if (applier2 && applier2.businessLicensePic && (applier2.type = "ent" || (applier2.type = "person" && applier2.identityCardPic))) {
      for (var i = 0; i < tms.length; i++) {
        var tm = tms[i];
        if (tm.sealAuthorizeStuff) {
          tmStatus = "WAITARTIFICIALEXAMINE";
        } else {//资料不齐全 跳出循环 
          tmStatus = "READY";
          break;
        }
      }
    }
    if (tmStatus) {
      tmObj["tmStatus"] = tmStatus;
    }
    await self.orderSve.trademarkDao.model.update(tmObj, { where: { channelOrderNum: tmObj.channelOrderNum, app_id: app.id }, transaction: t });
    return { code: 1 };
  }
  // 商标订单修改-商标尼斯信息修改
  async updateNcl(nclones,app,deliveryOrderNo,orderItem,self,t){
    for(var a=0;a<nclones.length;a++){//参数校验
      var nclone = nclones[a];
      if(!nclone.nclThree || nclone.nclThree.length<1){
        return {code:-300,msg:"尼斯小类参数错误"}
      }
      if(!nclone.tbCode){
        return {code:-301,msg:"商标提报号参数错误"}
      }
      if(!nclone.code){
        return {code:-301,msg:"商标大类编码错误"}
      }
    }
    for(var b=0;b<nclones.length;b++){
      var nclone = nclones[b];
      var nclThree = nclone.nclThree;
      var tbCode = nclone.tbCode;
      var ncloneCode = nclone.code;
      var tm = await self.orderSve.trademarkDao.model.findOne({ where: { channelOrderNum: deliveryOrderNo, proxyCode: tbCode, app_id: app.id }, raw: true });
      if (!tm || !tm.id) {
        return system.getResultFail(-105, "商标信息不存在");
      }
      //获取交付单下其它商标尼斯信息
      var othertm = await this.orderSve.trademarkDao.model.findAll({
        where: {
          channelOrderNum: deliveryOrderNo,
          app_id: app.id,
          proxyCode: { [self.orderSve.db.Op.ne]: tbCode }
        },
        raw: true
      });
      for (var i = 0; i < othertm.length; i++) {//判断重复大类
        var other = othertm[i];
        if (other.nclOneCodes == ncloneCode) {
          return system.getResultFail(-109, "该商标存在重复的尼斯大类");
        }
      }
      var tmObj = {
        id: tm.id,
        nclOneCodes: ncloneCode,
        nclCount:nclone.nclCount,
        nclPublicExpense:nclone.nclPublicExpense,
        nclSmallCodes: JSON.stringify(nclThree)
      };
      var applier2 = await self.orderSve.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderItem.orderNum },
        raw: true
      });
      tmObj["tmStatus"] = "READY";
      if (applier2 && applier2.businessLicensePic && (applier2.type = "ent" || (applier2.type = "person" && applier2.identityCardPic))) {
        if (tm.sealAuthorizeStuff) {
          tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
        }
      }
      await self.orderSve.trademarkDao.update(tmObj, t);//修改商标尼斯信息
    }
    return { code: 1 };
  }
  // 商标订单修改-修改申请人信息|修改交官材料 
  async updateApply(tms,apply,app,deliveryOrderNo,orderItem,self,t){
    var applier = await self.orderSve.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    if (!applier) {
      return { code: -105, msg: "未知申请人" };
    }
    var ciObj = {};
    var cusObj = {};
    var tmObj = {};
    var orderObj = { id: orderItem.id };
    if ("customerType" in apply) {
      ciObj["type"] = apply.customerType;
    }
    if ("name" in apply) {
      ciObj["applyName"] = apply.name;
      orderObj["applyName"] = apply.name;
      await self.orderSve.dao.update(orderObj, t);
    }

    if ("code" in apply) {
      ciObj["creditCode"] = apply.code;
    }
    if ("identityCardNo" in apply) {
      ciObj["identityCard"] = apply.identityCardNo;
    }
    if ("applyAddr"  in apply) {
      ciObj["applyAddr"] = apply.applyAddr;
    }
    if ("zipCode" in apply) {
      ciObj["zipCode"] = apply.zipCode;
      cusObj["zipCode"] = apply.zipCode;
      await self.orderSve.tmcustomerinfoDao.model.update(cusObj, { where: { orderNum: orderItem.orderNum }, transaction: t });
    }
    if ("businessLicensePdf" in apply) {
      ciObj["businessLicensePic"] = apply.businessLicensePdf;
      ciObj["businessLicensePic2"] = apply.businessLicensePic;
    }
    if ("identityCardPdf" in apply) {
      ciObj["identityCardPic"] = apply.identityCardPdf;
      ciObj["identityCardPic2"] = apply.identityCardPic;
    }
    await self.orderSve.tmapplierinfoDao.model.update(ciObj, { where: { orderNum: orderItem.orderNum }, transaction: t });//修改申请人信息

    var applier2 = await self.orderSve.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    for (var i = 0; i < tms.length; i++) {
      var tm = tms[i];
      var tmObj = { id: tm.id };
      if("gzwtsUrl" in apply){
        tmObj["sealAuthorizeStuff"] = apply.gzwtsUrl;
      }
      if("smwjUrl" in apply){
        tmObj["descUrl"] = apply.smwjUrl;
      }
      if (applier2 && applier2.businessLicensePic && (applier2.type = "ent" || (applier2.type = "person" && applier2.identityCardPic))) {
        if (tm.sealAuthorizeStuff || apply.gzwtsUrl) {
          tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
        }
      }
      await self.orderSve.trademarkDao.update(tmObj, t);
    }
    return { code: 1 };
  }

  //修改商标订单联系人
  async updateChannelCustomerInfo(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var channelOrder = obj.order_info;
    var channelUser = obj.userInfo;
    var deliveryOrderNo = obj.orderNo;//渠道订单号
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "渠道订单号不能为空");
    }
    // 1.获取交付单信息
    var orderItem = await this.orderSve.dao.model.findOne({
      where: { channelOrderNum: deliveryOrderNo, app_id: app.id },
      raw: true
    });
    if (!orderItem) {
      return { code: -102, msg: "系统中未查到相应订单，无法修改" };
    }
    if (orderItem.user_id != user.id) {
      return { code: -104, msg: "非本人订单，无法修改" };
    }
    var tms = await self.orderSve.trademarkDao.model.findAll({ where: { channelOrderNum: deliveryOrderNo, app_id: app.id }, raw: true });
    var tradem = null;
    for (var i = 0; i < tms.length; i++) {
      tradem = tms[i];
      if (["WAITCONFIRM", "CONFIRMFAIL", "4", "FILLEXCEPTION", "READY", "DOCFINISH", "AWAITCHECK", "WAITARTIFICIALEXAMINE", "WAITCOMMIT", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "SUBALITM", "REQALIERROR", "SUBALITMOK"].indexOf(tradem.tmStatus) < 0) {
        return { code: -103, msg: "存在状态为" + tradem.tmStatusName + "的商标，不能修改" };
      }
    }
    return await self.orderSve.db.transaction(async function (t) {
      var contactsObj = {};
      var orderObj = { id: orderItem.id };
      var contactinfo = obj.orderContact;
      if ("contacts" in contactinfo) {
        contactsObj["customerContact"] = contactinfo.contacts;
        orderObj["customerContact"] = contactinfo.contacts;
      }
      if ("mobile" in contactinfo) {
        contactsObj["mobile"] = contactinfo.mobile;
        orderObj["customerMobile"] = contactinfo.mobile;
      }
      if ("email" in contactinfo) {
        contactsObj["email"] = contactinfo.email;
      }
      if ("fax" in contactinfo) {
        contactsObj["fax"] = contactinfo.fax;
      }
      if ("notes" in obj) {
        orderObj["remark"] = obj.notes;
      }
      //修改联系人信息
      await self.orderSve.tmcustomerinfoDao.model.update(contactsObj, { where: { orderNum: orderItem.orderNum }, transaction: t });
      await self.orderSve.dao.update(orderObj, t);
      var applier2 = await self.orderSve.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderItem.orderNum },
        raw: true
      });
      for (var i = 0; i < tms.length; i++) {
        var tm = tms[i];
        var tmObj = { id: tm.id };
        tmObj["tmStatus"] = "READY";
        if (tm.sealAuthorizeStuff && applier2 && applier2.businessLicensePic && (applier2.type = "ent" || (applier2.type = "person" && applier2.identityCardPic))) {
          tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
        }
        await self.orderSve.trademarkDao.update(tmObj, t);
      }
      return { code: 1 };
    })
  }

  //渠道商标方案确认
  async channelTmConfirm(obj) {
    var self = this;
    // var user = obj.user;
    // var app = obj.app;
    var serviceNo = obj.serviceNo;
    if (!serviceNo) {
      return system.getResultFail(-101, "serviceNo参数错误");
    }
    var isConfirm = obj.isConfirm;
    if (!isConfirm) {
      return system.getResultFail(-103, "isConfirm参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.orderSve.dao.model.findOne({
      where: { channelOrderNum: serviceNo, channelCode: obj.channelCode },
      raw: true
    });
    if (!orderItem) {
      return { code: -102, msg: "系统中未查到相应订单，无法修改" };
    }
    var tms = await self.orderSve.trademarkDao.model.findAll({ where: { channelOrderNum: serviceNo, orderNum: orderItem.orderNum }, raw: true });
    var tradem = null;
    for (var i = 0; i < tms.length; i++) {
      tradem = tms[i];
      if (tradem.tmStatus != "WAITCONFIRM") {
        return { code: -103, msg: "方案确认失败，存在状态为" + tradem.tmStatusName + "的商标" };
      }
    }
    var tmObj = {
      orderNum: orderItem.orderNum
    };
    if (isConfirm == "0") {
      tmObj["tmStatus"] = "CONFIRMFAIL";
      if (obj.notes) {
        tmObj["remarkInfo"] = obj.notes;
      }
    }
    if (isConfirm == "1") {
      tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
    }
    await this.orderSve.trademarkDao.model.update(tmObj, {
      where: { orderNum: orderItem.orderNum }
    });
    return { code: 1 };
  }

  //--------------接收渠道订单数据---end-------------------------------app----------------------------
  
  //--------------推送渠道订单数据---start-----------------------------app------------------------------
  //推送渠道辅助注册商标数据
  async pushChannelAssistTmData(orderNum, channelCode,channelorder) {
    if (!channelCode) {
      return { code: -200, msg: "渠道参数错误" };
    }
    if (!orderNum) {
      return { code: -201, msg: "订单号参数错误" };
    }
    //获取订单信息
    var order = await this.orderSve.dao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!order || !order.id) {
      return { code: -202, msg: "未知订单" };
    }
    //获取订单所属人信息
    var user = await this.orderSve.userDao.model.findOne({
      where: { id: order.user_id },
      raw: true
    });
    if (!user || !user.id) {
      return { code: -206, msg: "未知用户" };
    }
    //获取商标信息
    var tms = await this.orderSve.trademarkDao.model.findAll({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!tms || tms.length < 1) {
      return { code: -203, msg: "未知商标" };
    }
    //获取申请人信息
    var applier = await this.orderSve.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!applier || !applier.id) {
      return { code: -204, msg: "未知申请人" };
    }
    //获取联系人信息
    var contacts = await this.orderSve.tmcustomerinfoDao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!contacts || !contacts.id) {
      return { code: -205, msg: "未知联系人" };
    }
    var contactsObj = {
      contactName: contacts.customerContact,
      mobile: contacts.mobile,
      email: contacts.email,
      tel: contacts.tel,//座机
      fax: contacts.fax//传真
    };
    var itemCode = order.itemCode;
    var channelOrder = {
      "channelServiceNo": "",
      "channelOrderNo": "",
      "needNo": "",
      "payStatus": "yfk",
      "deliveryOrderNo": order.channelOrderNum
    };
    var tm = tms[0];
    channelOrder.channelServiceNo = tm.channelOrderNum;
    channelOrder.channelOrderNo = tm.channelOrderListInfo;
    channelOrder.needNo = tm.needId;
    channelOrder.nclCount = tm.nclCount || 10;
    var apply = {
      "code": applier.creditCode,
      "name": applier.applyName,
      "smwjUrl": tm.descUrl,
      "zipCode": contacts.zipCode,
      "gzwtsUrl": tm.sealAuthorizeStuff,
      "applyAddr": applier.applyAddr,
      "applyArea": applier.applyArea,
      "customerType": applier.type,
      "identityCardNo": applier.identityCard,
      "identityCardPic": applier.identityCardPic2,
      "identityCardPdf": applier.identityCardPic,
      "businessLicensePic": applier.businessLicensePic2,
      "businessLicensePdf": applier.businessLicensePic
    };
    var tmObj = {
      "colorizedPicUrl": tm.colorizedPicUrl,
      "tmName": tm.tmName,
      "picUrl": tm.picUrl,
      "tmFormType": tm.tmFormType,
    };
    var nclones = [];
    for (var i = 0; i < tms.length; i++) {
      if (tms[i]) {
        var nclthree = tms[i].nclSmallCodes;
        nclthree = JSON.parse(nclthree);
        var nclone = { code: tms[i].nclOneCodes, tbCode: tms[i].proxyCode, name: "", nclThree: nclthree, 
          nclCount:nclthree.length,
          "tmStatus":tms[i].tmStatus,
          "tmStatusName":tms[i].tmStatusName,
          "submitTime":tms[i].created_at,
          "tmRegistNum":"",
          "deliveryType":"10",
          "nclPublicExpense":tms[i].nclPublicExpense
        };
        nclones.push(nclone);
      }
    }
    var reqObj = {
      "serviceNo":order.channelOrderNum,
      "sourceOrderNo":channelorder.idempotent_no || channelorder.needId || "",
      "notes":order.remark,
      "apply": apply,
      "orderContact":contactsObj,
      "tm": tmObj,
      "nclones": nclones,
      "channelCode":channelCode,
      "itemCode":itemCode || "",
      "channelOrder":channelOrder
    };
    await this.channelreceiveDao.pushChannelAssistTmData(reqObj);
    return { code: 1 };
  }
  //推送渠道辅助注册商标修改数据
  async pushEditChannelAssistTmData(orderNum, channelCode,channelorder) {
    if (!channelCode) {
      return { code: -200, msg: "渠道参数错误" };
    }
    if (!orderNum) {
      return { code: -201, msg: "订单号参数错误" };
    }
    //获取订单信息
    var order = await this.orderSve.dao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!order || !order.id) {
      return { code: -202, msg: "未知订单" };
    }
    //获取订单所属人信息
    var user = await this.orderSve.userDao.model.findOne({
      where: { id: order.user_id },
      raw: true
    });
    if (!user || !user.id) {
      return { code: -206, msg: "未知用户" };
    }
    //获取商标信息
    var tms = await this.orderSve.trademarkDao.model.findAll({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!tms || tms.length < 1) {
      return { code: -203, msg: "未知商标" };
    }
    //获取申请人信息
    var applier = await this.orderSve.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!applier || !applier.id) {
      return { code: -204, msg: "未知申请人" };
    }
    //获取联系人信息
    var contacts = await this.orderSve.tmcustomerinfoDao.model.findOne({
      where: { orderNum: orderNum },
      raw: true
    });
    if (!contacts || !contacts.id) {
      return { code: -205, msg: "未知联系人" };
    }
    var contactsObj = {
      contactName: contacts.customerContact,
      mobile: contacts.mobile,
      email: contacts.email,
      tel: contacts.tel,//座机
      fax: contacts.fax//传真
    };
    var itemCode = order.itemCode;
    var channelOrder = {
      "channelServiceNo": "",
      "channelOrderNo": "",
      "needNo": "",
      "deliveryOrderNo": order.channelOrderNum
    };
    var tm = tms[0];
    channelOrder.channelServiceNo = tm.channelOrderNum;
    channelOrder.channelOrderNo = tm.channelOrderListInfo;
    channelOrder.needNo = tm.needId;
    channelOrder.nclCount = tm.nclCount || 10;
    var apply = {
      "code": applier.creditCode,
      "name": applier.applyName,
      "smwjUrl": tm.descUrl,
      "zipCode": contacts.zipCode,
      "gzwtsUrl": tm.sealAuthorizeStuff,
      "applyAddr": applier.applyAddr,
      "applyArea": applier.applyArea,
      "customerType": applier.type,
      "identityCardNo": applier.identityCard,
      "identityCardPic": applier.identityCardPic2,
      "identityCardPdf": applier.identityCardPic,
      "businessLicensePic": applier.businessLicensePic2,
      "businessLicensePdf": applier.businessLicensePic
    };
    var tmObj = {
      "colorizedPicUrl": tm.colorizedPicUrl,
      "tmName": tm.tmName,
      "picUrl": tm.picUrl,
      "tmFormType": tm.tmFormType,
    };
    var nclones = [];
    for (var i = 0; i < tms.length; i++) {
      if (tms[i]) {
        var nclthree = tms[i].nclSmallCodes;
        nclthree = JSON.parse(nclthree);
        var nclone = { code: tms[i].nclOneCodes, tbCode: tms[i].proxyCode, name: "", nclThree: nclthree, 
          nclCount:nclthree.length,
          "tmStatus":tms[i].tmStatus,
          "tmStatusName":tms[i].tmStatusName,
          "submitTime":tms[i].created_at,
          "tmRegistNum":tms[i].tmRegistNum || "",
          "nclPublicExpense":tms[i].nclPublicExpense
        };
        nclones.push(nclone);
      }
    }
    var reqObj = {
      "serviceNo":order.channelOrderNum,
      "sourceOrderNo":channelorder.idempotent_no || channelorder.needId || "",
      "notes":order.remark,
      "apply": apply,
      "orderContact":contactsObj,
      "tm": tmObj,
      "nclones": nclones,
      "channelCode":channelCode,
      "itemCode":itemCode || "",
      "channelOrder":channelOrder
    };
    await this.channelreceiveDao.pushEditChannelAssistTmData(reqObj);
    return { code: 1 };
  }
  //--------------推送渠道订单数据---end-------------------------------------------------------------
    //获取渠道订单信息
  async getChannelOrderByChannelOrderNum(channelOrderNum,env) {
    var reqUrl = "http://fq" + env + "-api.gongsibao.com/openapi/serviceOrder/getByServiceOrderNo";
    if (channelOrderNum) {
      try {
        var data = {
          "order_no": channelOrderNum
        };
        var rc = system.getObject("util.execClient");
        var rtn = await rc.execPost(data, reqUrl);
        var result = JSON.parse(rtn.stdout);
        return result;
      } catch (e) {
        return null;
      }
    } else {
      return null;
    }
  }
}
module.exports = ChannelReceiveService;
