const system = require("../../system");
const ServiceBase = require("../sve.base");
const settings = require("../../../config/settings");
// const uiconfig = system.getUiConfig2(settings.wxconfig.appId);
// const tmSourceTypeToChannelCode = uiconfig.config.pdict.tmSourceTypeToChannelCode;//商标来源对应渠道码
// const channelCodeToTmSourceType = uiconfig.config.pdict.channelCodeToTmSourceType;//渠道码对应商标来源
const uuidv4 = require('uuid/v4');
const logCtl = system.getObject("web.oplogCtl");
class OrderService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(OrderService));
    this.channelApiUrl = settings.channelApiUrl();
    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.orderflowDao = system.getObject("db.orderflowDao");
    this.tradeDao = system.getObject("db.tradeDao");
    this.userDao = system.getObject("db.userDao");
    this.productDao = system.getObject("db.productDao");
    this.calculatepriceDao = system.getObject("db.calculatepriceDao");
    this.tmflowDao = system.getObject("db.tmflowDao");
    this.servicesitemDao = system.getObject("db.servicesitemDao");
    this.accountDao = system.getObject("db.accountDao");
    this.shopDao = system.getObject("db.shopDao");
    this.channelDao = system.getObject("db.channelDao");
    this.softwarecrsubmitDao = system.getObject("db.softwarecrsubmitDao");
    this.workcrsubmitDao = system.getObject("db.workcrsubmitDao");
    this.copyrightuserinfoDao = system.getObject("db.copyrightuserinfoDao");
    this.copyrightauthorDao = system.getObject("db.copyrightauthorDao");
    // this.channelpushApi = system.getObject("api.channelpushApi");
    this.oplogSve = system.getObject("service.oplogSve");
    this.execClient = system.getObject("util.execClient");
  }
  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 getCreateUUId(code) {
    var tcode = code == null ? "" : code;
    var myDate = new Date();
    var uid = await this.getUidStr(8, 60);
    return tcode + "" + myDate.getFullYear() + "" + (myDate.getMonth() + 1) + "" + myDate.getDate() + "" + myDate.getMilliseconds() + "" + uid;
    // return  myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+Math.round(Math.random()*500)+""+user.id;
  }
  async getCreateOrderNum() {
    var createOrderNum = await this.getUidStr(3, 36);//====================订单号生成
    return createOrderNum + "" + Date.now();
  }
  async getUidStr(len, radix) {
    var chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
    var uuid = [], i;
    radix = radix || chars.length;
    if (len) {
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      var r;
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }
    return uuid.join('');
  }
  async getOrderDetail(oid) {
    var order = await this.dao.findById(oid);
    return order;
  }
  async findOneByOrderNum(orderNum) {
    var app = await this.dao.findOneByOrderNum(orderNum);
    return app;
  }
  async getSubmitOrderDetail(orderNum) {
    //商标 h_order_tm_info   订单材料 h_order_tm_stuff   申请人信息 h_order_tm_contact_person
    var calcs = await this.calcDao.findByOrderNum(orderNum);
    for (var i = 0; i < calcs.rows.length; i++) {
      var tms = await this.trademarkDao.getTmsByCalcId(calcs.rows[i].dataValues.id);
      tms = tms.rows;
      if (tms.length > 0) {
        calcs.rows[i].dataValues["sealAuthorizeStuff"] = tms[0].dataValues.sealAuthorizeStuff;
      }
    }
    var tms = await this.trademarkDao.getTmByOrderNum(orderNum);
    var applier = await this.tmapplierinfoDao.getApplierInfoByOrderNum(orderNum);

    var obj = { calcs: calcs, applier: applier, tms: tms };
    return obj;
  }
  //特殊处理_重新提交：商标列表中的特殊处理商标后的提交
  async tsclResubmit(obj, user, app) {
    var self = this;
    var reqOrderObj = obj.order;
    var orderNum = reqOrderObj.orderNum;
    var calcs = obj.tms;
    var reqApplierObj = obj.applier;
    var reqCustomerObj = obj.customer;
    var partnerinfo = user.partnerinfo;//合伙人信息
    var ptm = await this.trademarkDao.getTmByOrderNum(reqOrderObj.orderNum);
    var porder = await this.dao.findOneByOrderNum(reqOrderObj.orderNum);
    var sum_ncl_total_public_expense = 0;//官费
    if (ptm.rows[0].tmStatus == "4") {
      sum_ncl_total_public_expense = porder.totalPublicExpense;
    }
    var sum_invoice_taxes = 0;//税费
    var sum_ncl_service_charge = 0;//服务费
    var userProfit = 0;//个人利润
    var referrerProfit = 0;//推荐人利润
    var platformProfit = 0;//平台利润
    var totalPlatformCost = 0;//平台使用费
    var platformProfitRatio = 0;//平台分润比例
    var referrerProfitRatio = 0;//推荐人分润比例
    var total_sum = 0;//订单总额
    return this.db.transaction(async function (t) {
      if (reqOrderObj.tsclType != "4" && reqOrderObj.tsclType != "FILLEXCEPTION") {//判断订单状态
        return { code: "-100", msg: "提交失败，请检查处理类型" };
      } else {
        var createOrderNum = await self.getCreateOrderNum();//uuid.replace(/\-/g,"");//====================订单号生成
        var serviceItem = await self.servicesitemDao.findOneByCode(porder.itemCode);//服务项信息
        if (serviceItem == null) {
          return { code: "-101", msg: "提交失败，请检查服务项目中是否存在编码为sbzc的服务项" };
        }
        serviceItem = serviceItem.dataValues;
        //新建订单
        var orderObj = {
          referrerProfit: referrerProfit,
          userProfit: userProfit,
          userName: user.userName,
          totalPlatformCost: totalPlatformCost,
          platformProfitRatio: platformProfitRatio,
          referrerProfitRatio: referrerProfitRatio,
          platformProfit: platformProfit,
          orderNum: createOrderNum,
          orderType: "8",
          app_id: app.id,
          user_id: user.id,
          onlyCode: user.onlyCode,
          nickName: user.nickName,
          customerContact: reqCustomerObj.customerContact,
          customerMobile: reqCustomerObj.mobile,
          itemCode: serviceItem.code,
          itemName: serviceItem.name,
          itemType: serviceItem.itemType,
          itemOrderNum: 1,
          itemOrderConsumeNum: 1,
          totalPublicExpense: sum_ncl_total_public_expense,
          totalInvoiceTaxes: sum_invoice_taxes,
          orderStatus: "32",
          totalServiceCharge: sum_ncl_service_charge,
          totalSum: total_sum,
          orderSourceType: porder.orderSourceType,
          parentOrderNum: orderNum,
          applyName: reqApplierObj.applyName
        };
        var reqParams = {
          account_id: user.account_id,
          user_id: user.id,
          username: user.nickName,
          renAmount: sum_ncl_total_public_expense,
          tradeType: "returnPublicExpense",
          status: "settled",
          tradeDate: new Date(),
        }
        if (ptm.rows[0].tmStatus == "4") {
          await self.tradeDao.model.create(reqParams, t);
        }
        return self.orderDao.create(orderObj, t).then(async function (order) {//创建订单
          var applierObj = {
            orderNum: order.orderNum,
            type: reqApplierObj.type,
            applyName: reqApplierObj.applyName,
            identityCard: reqApplierObj.type != "person" ? "" : reqApplierObj.identityCard,
            creditCode: reqApplierObj.creditCode,
            applyAddr: reqApplierObj.applyAddr,
            identityCardPic: reqApplierObj.type != "person" ? "" : reqApplierObj.identityCardPic,
            businessLicensePic: reqApplierObj.type == "person" ? "" : reqApplierObj.businessLicensePic
          };
          var customerObj = {
            zipCode: reqCustomerObj.zipCode,
            order_id: order.id,
            orderNum: order.orderNum,
            customerContact: reqCustomerObj.customerContact,
            mobile: reqCustomerObj.mobile,
            email: reqCustomerObj.email
          };
          var orderflowObj = { app_id: app.id, user_id: user.id, userName: user.userName, nickName: user.nickName, orderNum: order.orderNum, opContent: "商标特殊处理，订单已提报" };

          //创建订单流程
          var orderflow = await self.orderflowDao.create(orderflowObj, t);
          //创建商标进度接收人
          var customer = await self.tmcustomerinfoDao.create(customerObj, t);
          //创建商标申请用户
          var applier = await self.tmapplierinfoDao.create(applierObj, t);

          //商标创建
          for (var i = 0; i < calcs.length; i++) {//生成商标信息
            var tmpNcl = calcs[i];
            var ncl = tmpNcl.ncl.sort();

            //尼斯大类信息
            var tmpNclOnes = [];
            //尼斯小类
            var tmpNclSmallCodes = { ncl: [] };
            ncl.forEach(f => {
              tmpNclOnes.push(f.code);
              var tmpNclSmall = {
                code: f.code,
                name: '',
                price: 0,
                nclThree: f.nclThree.nclthree
              };
              tmpNclSmallCodes.ncl.push(tmpNclSmall);
            });
            //创建提报单数据
            var calculatepriceObj = {
              code: Math.round(Math.random() * 500) + "" + user.id + "" + new Date().getTime(),
              "app_id": app.id,
              "user_id": user.id,
              "userName": user.userName,
              onlyCode: user.onlyCode,
              nclOneCodes: tmpNclOnes.join(','),
              nclSmallCodes: JSON.stringify(tmpNclSmallCodes),
              customerContact: reqCustomerObj.customerContact,
              mobile: reqCustomerObj.mobile,
              email: reqCustomerObj.email,
              nclTotalPublicExpense: '0',
              nclServiceCharge: '0',
              invoiceTaxes: '0',
              tmType: "p",
              tmFormType: tmpNcl.tmFormType,
              tmName: tmpNcl.tmName,
              picUrl: tmpNcl.picUrl,
              userDel: '1',
              status: '2',
              colorizedPicUrl: tmpNcl.colorizedPicUrl,
              totalSum: '0',
              calcType: '2',
              creditCode: reqApplierObj.creditCode,
              applyName: reqApplierObj.applyName,
              applyAddr: reqApplierObj.applyAddr,
              zipCode: reqCustomerObj.zipCode,
              order_id: order.id,
              "orderNum": order.orderNum,
            };

            var calculateprice = await self.calculatepriceDao.create(calculatepriceObj, t);
            //进行单个大类创建商标数据
            for (var j = 0; j < ncl.length; j++) {
              var nclone = ncl[j];
              // var myDate=new Date();
              var key = await self.getUUId(user.id);//myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+user.id+""+Math.round(Math.random()*500);
              var nclthreeobj = { "nclthree": nclone.nclThree.nclthree };
              nclthreeobj = JSON.stringify(nclthreeobj);
              var mobile = reqCustomerObj.mobile;
              if (partnerinfo != null && partnerinfo.mobile != "") {
                mobile = partnerinfo.mobile;
              }
              var tmobj = {
                "applyName": reqApplierObj.applyName,
                tmRegistNum: "",
                partnerMobile: mobile,
                "app_id": app.id,
                "user_id": user.id,
                "userName": user.userName,
                onlyCode: user.onlyCode,
                "orderNum": order.orderNum,
                "tmType": "p",
                "tmFormType": tmpNcl.tmFormType,
                "nclOneCodes": nclone.code,
                "tmStatus": "WAITARTIFICIALEXAMINE",
                "colorizedPicUrl": tmpNcl.colorizedPicUrl,
                "nclSmallCodes": nclthreeobj,
                "tmName": tmpNcl.tmName,
                "picUrl": tmpNcl.picUrl,
                "proxyCode": key,
                "sealAuthorizeStuff": tmpNcl.sealAuthorizeStuff,
                parentProxyCode: tmpNcl.proxyCode,
                nclCalc_id: calculateprice.id
              };

              var tm = await self.trademarkDao.create(tmobj, t);
              //更新之前商标状态
              var param = { tmStatus: "DISCARDED", newProxyCode: key, opRemarkInfo: "新代理号：" + key };
              var sqlWhere = { where: { proxyCode: nclone.proxyCode, tmStatus: reqOrderObj.tsclType, app_id: app.id, user_id: user.id } };
              var deleteTm = await self.trademarkDao.updateByWhere(param, sqlWhere, t);//更新之前商标状态
            }
          }
          return { code: "1", msg: "提交成功" };
        });
      }
    });
  }
  //订单提报异常修改后的提交
  async orderRepeatSubmit(obj, user, app) {
    var self = this;
    var orderObj = obj.order;
    var calcs = obj.tms;
    var applierObj = obj.applier;
    var customerObj = obj.customer;
    var orderNum = orderObj.orderNum;
    var partnerinfo = user.partnerinfo;//合伙人信息
    return this.db.transaction(async function (t) {
      var ostatus = await self.dao.getOrderStatus(orderObj.id);
      if (orderObj.orderStatus != "64") {//判断订单状态
        return { code: "-1", msg: "提交失败，请检查订单状态" };
      } else {
        applierObj["orderNum"] = orderNum;
        var deleteTm = await self.trademarkDao.deleteByOrderNum(orderNum, t);//删除以前商标
        var applierResult = await self.tmapplierinfoDao.update(applierObj, t);//商标申请人信息
        var customerUpdate = await self.tmcustomerinfoDao.update(customerObj, t);//更新客户信息
        var orderflowObj = { app_id: app.id, user_id: user.id, userName: user.userName, nickName: user.nickName, orderNum: orderNum, opContent: "订单重新提报" };
        var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
        for (var i = 0; i < calcs.length; i++) {//生成商标信息
          var obj = calcs[i];
          await self.calculatepriceDao.update(obj, t);//尼斯
          var ncl = JSON.parse(obj.nclSmallCodes).ncl;
          for (var j = 0; j < ncl.length; j++) {
            var nclone = ncl[j];
            // var myDate=new Date();
            var key = await self.getUUId(user.id);// myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+Math.round(Math.random()*500)+""+user.id;
            var nclthreeobj = { "nclthree": nclone.nclThree };
            nclthreeobj = JSON.stringify(nclthreeobj);
            var mobile = customerObj.mobile;
            if (partnerinfo != null && partnerinfo.mobile != "") {
              mobile = partnerinfo.mobile;
            }
            var tmobj = {
              "applyName": applierObj.applyName, tmRegistNum: "", partnerMobile: mobile, "app_id": app.id, "user_id": user.id, "userName": user.userName,
              "orderNum": orderNum, "tmType": "p", "tmFormType": obj.tmFormType, "nclOneCodes": nclone.code, "tmStatus": "WAITARTIFICIALEXAMINE", onlyCode: user.onlyCode, "nclCalc_id": obj.id,
              "nclSmallCodes": nclthreeobj, "tmName": obj.tmName, "picUrl": obj.picUrl, "colorizedPicUrl": obj.colorizedPicUrl, "proxyCode": key, "sealAuthorizeStuff": obj.sealAuthorizeStuff
            };
            var tm = await self.trademarkDao.create(tmobj, t);
            // var tmflowObj={app_id:app.id,user_id:user.id,userName:user.userName,nickName:user.nickName,orderNum:orderNum,
            //    opContent:tm.tmStatusName,tmProxyCode:tm.proxyCode,logType:"tmlog"};
            // var tmflow = await self.this.tmflowDao.create(tmflowObj,t);//商标提交流程
          }
        }
      }
      var orderupdate = await self.dao.updatestatus(orderObj.id, "32", t);//更新订单状态
      return { code: "1", msg: "提交成功" };
    });
  }
  //1 生成商标  2 订单材料 3 申请用户信息 4 订单状态update  5 客户信息重新维护，订单中的商标开始提报并分润
  async orderSubmit(obj, user, app) {
    var self = this;
    var orderObj = obj.order;
    var calcs = obj.tms;
    var stuffObj = obj.stuff;
    var applierObj = obj.applier;
    var customerObj = obj.customer;
    var orderNum = orderObj.orderNum;
    orderObj.applyName = applierObj.applyName;
    var partnerinfo = user.partnerinfo;//合伙人信息
    var sumObj = { bao: 0, ren: 0 };
    return this.db.transaction(async function (t) {
      var ostatus = await self.dao.getOrderStatus(orderObj.id);
      if (orderObj.orderStatus != "4") {//判断订单状态
        return { code: "-1", msg: "提交失败，请检查订单状态" };
      } else {
        applierObj["orderNum"] = orderNum;
        var applier = await self.tmapplierinfoDao.create(applierObj, t);//商标申请人信息
        var customerUpdate = await self.tmcustomerinfoDao.update(customerObj, t);//更新客户信息
        if (Number(orderObj.totalPublicExpense) > 0) {
          var orderPersonFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.totalPublicExpense, remark: "官费", tradeDate: new Date(), tradeType: "publicExpense", status: "settled", orderNum: orderObj.orderNum
          };
          var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//官费
        }
        if (Number(orderObj.totalInvoiceTaxes) > 0) {
          var orderPersonFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.totalInvoiceTaxes, remark: "税费", tradeDate: new Date(), tradeType: "invoiceTaxes", status: "settled", orderNum: orderObj.orderNum
          };
          var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//税费
        }
        if (Number(orderObj.userProfit) > 0) {
          var orderPersonFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.userProfit, remark: "个人分润", tradeDate: new Date(), tradeType: "orderPersonFee", status: "settled", orderNum: orderObj.orderNum
          };
          var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//个人分润
          sumObj.ren = parseFloat(sumObj.ren) + parseFloat(orderPersonFee.renAmount);
        }//平台帐户中减去此笔交易

        //判断来源是移动商城时，需要对店铺利润进行处理
        if (orderObj.orderSourceType == "2" && orderObj.shopkeeperProfit > 0) {
          var orderPersonFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.shopkeeperProfit, remark: "店主分润", tradeDate: new Date(), tradeType: "orderPersonFee", status: "settled", orderNum: orderObj.orderNum
          };
          var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//移动端店主分润
          sumObj.ren = parseFloat(sumObj.ren) + parseFloat(orderPersonFee.renAmount);
        }//平台帐户中减去此笔交易

        console.log("用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户");
        console.log(user);
        console.log(orderObj);
        if (Number(orderObj.referrerProfit) > 0 && user.account.referrerOnlyCode != "" && user.account.referrerOnlyCode != null) {
          //首次下单 拥有推荐人 建立推荐人分润
          var o = { unionId: user.account.referrerOnlyCode, }
          var user2 = await self.userDao.findOne(o);//推荐人信息
          //var account2 = await self.accountDao.findOneByOnlyCode(user.account.referrerOnlyCode);//推荐人账户
          user2 = user2.dataValues;
          console.log("22222222222用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户用户");
          console.log(user2);
          var recommendFeeObj = {
            app_id: user2.app_id, account_id: user2.account_id, user_id: user2.id, username: user2.userName, nickName: user2.nickName,
            renAmount: orderObj.referrerProfit, remark: "推荐分润", tradeDate: new Date(), tradeType: "recommendFee", status: "settled", orderNum: orderObj.orderNum
          };
          var recommendFee = await self.tradeDao.createOrderTrade(recommendFeeObj, t);//推荐分润
          console.log("recommendFee@@@@@@@@@@@@@@@@@@@@@@@");
          console.log(recommendFee);
          sumObj.ren = parseFloat(sumObj.ren) + parseFloat(recommendFee.renAmount);
        }//平台帐户中减去此笔交易
        if (Number(orderObj.platformProfit) > 0) {

          var orderPlatformFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.platformProfit, remark: "平台分润", tradeDate: new Date(), tradeType: "orderPlatformFee", status: "settled", orderNum: orderObj.orderNum
          };
          var orderPlatformFee = await self.tradeDao.createOrderTrade(orderPlatformFeeObj, t);//平台分润
        }
        console.log(orderObj.totalPlatformCost);
        if (Number(orderObj.totalPlatformCost) > 0) {
          var platUseFeeObj = {
            app_id: app.id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
            renAmount: orderObj.totalPlatformCost, remark: "平台使用费", tradeDate: new Date(), tradeType: "platUseFee", status: "settled", orderNum: orderObj.orderNum
          };

          var platUseFee = await self.tradeDao.createOrderTrade(platUseFeeObj, t);//平台使用费

        }
        console.log("sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总");
        console.log(sumObj);
        await self.tradeDao.updatePAccount(sumObj, t);
        var orderflowObj = { app_id: app.id, user_id: user.id, userName: user.userName, nickName: user.nickName, orderNum: orderNum, opContent: "订单提报" };
        var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
        for (var i = 0; i < calcs.length; i++) {//生成商标信息
          var obj = calcs[i];
          var ncl = JSON.parse(obj.nclSmallCodes).ncl;
          for (var j = 0; j < ncl.length; j++) {
            var nclone = ncl[j];
            // var myDate=new Date();
            var key = await self.getUUId(user.id);//myDate.getFullYear()+""+myDate.getMonth()+""+myDate.getDate()+""+myDate.getHours()+""+myDate.getMinutes()+""+myDate.getSeconds()+""+myDate.getMilliseconds()+""+user.id+""+Math.round(Math.random()*500);
            var nclthreeobj = { "nclthree": nclone.nclThree };
            nclthreeobj = JSON.stringify(nclthreeobj);
            console.log(nclthreeobj);
            console.log(customerObj);
            var mobile = customerObj.mobile;
            if (partnerinfo != null && partnerinfo.mobile != "") {
              mobile = partnerinfo.mobile;
            }
            var tmobj = {
              "applyName": applier.dataValues.applyName,
              tmRegistNum: "", partnerMobile: mobile,
              "app_id": app.id,
              "user_id": user.id,
              "userName": user.userName,
              onlyCode: user.onlyCode,
              "orderNum": orderNum,
              "tmType": "p",
              "tmFormType": obj.tmFormType,
              "nclOneCodes": nclone.code,
              "tmStatus": "WAITARTIFICIALEXAMINE",
              "colorizedPicUrl": obj.colorizedPicUrl,
              "nclSmallCodes": nclthreeobj,
              "tmName": obj.tmName,
              "picUrl": obj.picUrl,
              "proxyCode": key,
              "sealAuthorizeStuff": obj.sealAuthorizeStuff,
              "nclCalc_id": obj.id
            };

            var tm = await self.trademarkDao.create(tmobj, t);
            // var tmflowObj={app_id:app.id,user_id:user.id,userName:user.userName,nickName:user.nickName,orderNum:orderNum,
            //    opContent:tm.tmStatusName,tmProxyCode:tm.proxyCode,logType:"tmlog"};
            // var tmflow = await self.orderflowDao.create(tmflowObj,t);//商标提交流程
          }
        }
      }
      var o = { id: orderObj.id, applyName: orderObj.applyName, orderStatus: '32' };
      var orderupdate = await self.dao.update(o, t);
      //var orderupdate= await self.dao.updatestatus(orderObj.id,"32",t);//更新订单状态
      return { code: "1", msg: "提交成功" };
    });
  }
  //修改订单状态并分润
  async changeStatus(obj) {
    var ids = obj.ids;
    var status = obj.status;
    console.log(obj);
    var self = this;
    for (var i = 0; i < ids.length; i++) {
      var tItem = await self.dao.findById(ids[i]);
      if (tItem.orderStatus != '4') {
        return { code: -101, mag: "修改失败,所选择的数据中不能包含有已提报的数据" }
      }
    }
    var sumObj = { bao: 0, ren: 0 };
    return this.db.transaction(async function (t) {
      for (var i = 0; i < ids.length; i++) {
        await self.dao.update({ id: ids[i], orderStatus: status }, t);
        var crorder = await self.dao.findById(ids[i]);
        var orderObj = crorder.dataValues;
        var user = await self.userDao.findById(orderObj.user_id);
        var userObj = user.dataValues;
        var account = await self.accountDao.findById(userObj.account_id);

        if (status == "32" && orderObj.orderStatus != "32" && crorder && user) {
          if (Number(orderObj.totalPublicExpense) > 0) {
            var orderPersonFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.totalPublicExpense, remark: "官费", tradeDate: new Date(), tradeType: "publicExpense", status: "settled", orderNum: orderObj.orderNum
            };
            var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//官费
          }
          if (Number(orderObj.totalInvoiceTaxes) > 0) {
            var orderPersonFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.totalInvoiceTaxes, remark: "税费", tradeDate: new Date(), tradeType: "invoiceTaxes", status: "settled", orderNum: orderObj.orderNum
            };
            var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//税费
          }
          if (Number(orderObj.userProfit) > 0) {
            var orderPersonFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.userProfit, remark: "个人分润", tradeDate: new Date(), tradeType: "orderPersonFee", status: "settled", orderNum: orderObj.orderNum
            };
            var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//个人分润
            sumObj.ren = parseFloat(sumObj.ren) + parseFloat(orderPersonFee.renAmount);
          }//平台帐户中减去此笔交易

          //判断来源是移动商城时，需要对店铺利润进行处理
          if (orderObj.orderSourceType == "2" && orderObj.shopkeeperProfit > 0) {
            var orderPersonFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.shopkeeperProfit, remark: "店主分润", tradeDate: new Date(), tradeType: "orderPersonFee", status: "settled", orderNum: orderObj.orderNum
            };
            var orderPersonFee = await self.tradeDao.createOrderTrade(orderPersonFeeObj, t);//移动端店主分润
            sumObj.ren = parseFloat(sumObj.ren) + parseFloat(orderPersonFee.renAmount);
          }//平台帐户中减去此笔交易
          if (Number(orderObj.referrerProfit) > 0 && account.referrerOnlyCode != "" && account.referrerOnlyCode != null) {
            //拥有推荐人 建立推荐人分润
            var o = { unionId: account.referrerOnlyCode, }
            var user2 = await self.userDao.findOne(o);//推荐人信息
            user2 = user2.dataValues;
            var recommendFeeObj = {
              app_id: user2.app_id, account_id: user2.account_id, user_id: user2.id, username: user2.userName, nickName: user2.nickName,
              renAmount: orderObj.referrerProfit, remark: "推荐分润", tradeDate: new Date(), tradeType: "recommendFee", status: "settled", orderNum: orderObj.orderNum
            };
            var recommendFee = await self.tradeDao.createOrderTrade(recommendFeeObj, t);//推荐分润
            sumObj.ren = parseFloat(sumObj.ren) + parseFloat(recommendFee.renAmount);
          }//平台帐户中减去此笔交易
          if (Number(orderObj.platformProfit) > 0) {
            var orderPlatformFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.platformProfit, remark: "平台分润", tradeDate: new Date(), tradeType: "orderPlatformFee", status: "settled", orderNum: orderObj.orderNum
            };
            var orderPlatformFee = await self.tradeDao.createOrderTrade(orderPlatformFeeObj, t);//平台分润

          }
          if (Number(orderObj.totalPlatformCost) > 0) {
            var platUseFeeObj = {
              app_id: orderObj.app_id, account_id: user.account_id, user_id: user.id, username: user.userName, nickName: user.nickName,
              renAmount: orderObj.totalPlatformCost, remark: "平台使用费", tradeDate: new Date(), tradeType: "platUseFee", status: "settled", orderNum: orderObj.orderNum
            };
            console.log(platUseFeeObj);
            var platUseFee = await self.tradeDao.createOrderTrade(platUseFeeObj, t);//平台使用费
          }
          console.log("sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总sum总");
          console.log(sumObj);
          await self.tradeDao.updatePAccount(sumObj, t);
        }
        var orderflowObj = { app_id: orderObj.app_id, user_id: user.id, userName: user.userName, nickName: user.nickName, orderNum: orderObj.orderNum, opContent: "订单" + orderObj.orderStatusName };
        var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
      }
      return { code: 1 }
    })
  }
  async orderCancel(orderNum, user, app) {
    var order = await this.dao.findOneByOrderNum(orderNum);
    var calcs = await this.calcDao.findByOrderNum(orderNum);
    order = order.dataValues;
    calcs = calcs.rows;
    var that = this;
    if (order.orderStatus != "1") {
      return null;// {code:"-2",msg:"操作失败，只能取消未付款订单"};
    }
    order.orderStatus = "2";
    return this.db.transaction(async function (t) {
      var orderupdate = await that.dao.update(order, t);
      var orderflowObj = {
        app_id: app.id,
        user_id: user.id,
        userName: user.userName,
        nickName: user.nickName,
        orderNum: order.orderNum,
        opContent: "订单取消",
        logType: "orderlog"
      };
      var orderflow = await that.orderflowDao.create(orderflowObj, t);//订单流程
      for (var i = 0; i < calcs.length; i++) {
        var obj = { id: "", status: "1", orderNum: "" };
        obj.id = calcs[i].dataValues.id;
        var calcResult = await that.calcDao.update(obj, t);
      }
      return "1";//{code:"1",msg:"订单已取消"};
    });
  }
  async findByPayUserId(payUserId) {
    var orders = await this.dao.findByPayUserId(payUserId);
    return orders;
  }
  async getApplierByPayUserId(payUserId) {
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@getApplierByPayUserId");
    var sql = "SELECT DISTINCT applyName FROM	h_tmapplier_info WHERE	orderNum IN (	SELECT DISTINCT	orderNum	FROM	h_order_info	WHERE	payUserId = " + payUserId + ") ORDER BY created_at desc ";
    console.log(sql);
    var appliers = await this.tmapplierinfoDao.customQuery(sql);
    return appliers;
  }
  async getPayUserIdByUserId(userId) {
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@getPayUserIdByUserId");
    var sql = "SELECT DISTINCT payUserId FROM	h_order_info	WHERE	user_id = " + userId;
    console.log(sql);
    var payUserIds = await this.dao.customQuery(sql);
    return payUserIds;
  }
  async getPayUserIdByOnlyCode(code) {
    console.log("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@getPayUserIdByOnlyCode");
    var sql = "SELECT DISTINCT payUserId FROM	h_order_info	WHERE	onlyCode = '" + code + "'";
    console.log(sql);
    var payUserIds = await this.dao.customQuery(sql);
    var ids = [];
    for (var i = 0; i < payUserIds.length; i++) {
      ids.push(payUserIds[i].payUserId)
    }
    return ids;
  }
  //微信支付成功回调
  async createOrderTrade(obj) {
    var orderNum = obj.orderNum;
    var payUser = obj.payUser;
    var payResult = obj.payResult;
    var that = this;
    var order = await this.dao.findOneByOrderNum(orderNum);
    var user = await this.userDao.findById(order.user_id);
    if (order.orderStatus == "1") {
      return this.db.transaction(async function (t) {
        var tradeObj = {
          idkey: orderNum,
          tradeDate: new Date(),
          status: "settled",
          tradeType: "orderTrade",
          remark: "订单交易",
          renAmount: Number(payResult.total_fee) / 100,
          app_id: order.app_id,
          account_id: user.account_id,
          user_id: order.user_id,
          username: user.userName,
          nickName: user.nickName,
          orderNum: order.orderNum
        };
        var trade = await that.tradeDao.createOrderTrade(tradeObj, t);//订单交易
        var orderflowObj = {
          app_id: order.app_id,
          user_id: order.user_id,
          userName: user.userName,
          nickName: user.nickName,
          orderNum: order.orderNum,
          opContent: "订单付款"
        };
        var orderflow = await that.orderflowDao.create(orderflowObj, t);//订单流程
        order.orderStatus = "4";
        order.paymentSerialNumber = payResult.transaction_id;
        order.paymentPlatformType = "wx";//支付平台类型:"wx":"微信","offline":"线下"
        order.payUserId = payUser.id;
        order.payNickName = payUser.nickName;
        order.payAppId = payUser.appid;
        console.log(order);
        var orderResult = await that.dao.update(order.dataValues, t);
        order.orderStatusName = "付款成功";
        var result = { trade: trade, order: order };
        //发送短信
        //订单来源类型，1PC，2移动商城，4渠道方
        if (order.orderSourceType == "2") {
          var shopItem = await that.shopDao.getShopItemInfo(order.shopOnlyCode);
          if (shopItem != null) {
            var smsClient = system.getObject("util.smsClient");
            smsClient.sendMsg(shopItem.userMobile, "亲爱的知产合伙人，你的客户于" + (new Date()).Format("yyyy-MM-dd") + "成功购买【" + order.itemName + "】服务，亲，赶紧去自己店铺收钱吧！");
          }
        }
        return result;
      });
    } else {
      return { order: order };
    }
    // var tmpTrade=await this.tradeSve.findOneByIdKey(tradekey);//查询是否已经生成了交易
    // if(!tmpTrade){
    //   var user=req.session.user;
    //   var trade=await this.fillmoney(tradekey,result.total_fee,req);
    //   console.log("user account_id......................................."+user.account_id);
    //   console.log("user app_id......................................."+user.app_id);
    //   var accountBalance = await this.accountSve.getAccountBalance(user.account_id,user.app_id);
    //   trade.dataValues["accountBalance"]=accountBalance;
    //   return System.getResult2(trade,null);
    // }else{
    //   var user=req.session.user;
    //   var accountBalance = await this.accountSve.getAccountBalance(user.account_id,user.app_id);
    //   tmpTrade.dataValues["accountBalance"]=accountBalance;
    //   return System.getResult2(tmpTrade,null);
    // }
  }

  async firstloading(userinfo, orderinfos) {
    var self = this;
    return this.db.transaction(async function (t) {
      var lengths = 0;
      var sources = [];
      for (var i = 0; i < orderinfos.length; i++) {
        var orderinfo = await self.dao.findOne({ orderNum: orderinfos[i].orderNum }, t);
        var status = 0;
        //订单状态，1未付款，2订单取消，4付款成功，8退款处理中，16已退款、32已提报
        switch (orderinfos[i].orderStatus) {
          case 3011:
            status = '1'; break;
          case 3012:
            status = '1'; break;
          case 3013:
            status = "4"; break;
          case 3021:
            status = '1'; break;
          case 3022:
            status = '4'; break;
          case 3023:
            status = '2'; break;
          case 3024:
            status = '4'; break;
          case 3031:
            status = '8'; break;
          case 3032:
            status = '8'; break;
          case 3033:
            status = '16'; break;
          case 3034:
            status = '4'; break;
          default:
            break;
        }
        switch (orderinfos[i].invoiceApply) {
          case 0:
            orderinfos[i].invoiceApply = 'notapply'; break;
          case 1:
            orderinfos[i].invoiceApply = 'applied'; break;
          default:
            break;
        }
        var totalsum = Number(orderinfos[i].totalSum) / 100;
        if (!orderinfo) {
          var source = {
            app_id: userinfo.app_id,
            user_id: userinfo.user_id,
            shopOnlyCode: userinfo.onlyCode,
            userName: userinfo.userName,
            orderNum: orderinfos[i].orderNum,
            itemName: orderinfos[i].itemName,
            invoiceApply: orderinfos[i].invoiceApply,
            totalSum: totalsum,
            orderStatus: status,
            customerContact: orderinfos[i].customerContact,
            customerMobile: orderinfos[i].customerMobile,
            created_at: orderinfos[i].add_time,
            updated_at: orderinfos[i].add_time,
            orderSourceType: '8',
          }
          sources.push(source);
          lengths += 1;
        }
      }
      await self.dao.bulkCreate(sources, t);
      return { code: 0, msg: "导入成功", data: lengths }
    })
  }
  async orderApproval(obj) {
    var self = this;
    var result = {
      code: 1,
      message: "success",
      data: {}
    };
    var user = obj.user;
    var orderNum = obj.order_num;
    var approval_notes = obj.approval_notes;
    if (!user || !user.onlyCode) {
      result.code = -100;
      result.message = "用户不存在";
      return result;
    }
    if (orderNum == null || orderNum == "" || orderNum == "undefined") {
      result.code = -101;
      result.message = "orderNum参数有误";
      return result;
    }
    if (approval_notes == null || approval_notes == "" || approval_notes == "undefined") {
      result.code = -102;
      result.message = "approval_notes参数有误";
      return result;
    }
    obj.approval_status = obj.approval_status.toString();
    console.log(obj.approval_status);
    if (obj.approval_status == null || obj.approval_status == "" || obj.approval_status == "undefined") {
      result.code = -103;
      result.message = "approval_status参数有误";
      return result;
    }
    var approval_status = "2";
    if (obj.approval_status == "1") {
      approval_status = "4"
    }
    return this.db.transaction(async function (t) {
      var order = await self.dao.findOneByOrderNum(orderNum);
      if (!order) {
        result.code = -104;
        result.message = "订单不存在";
        return result;
      } else {
        var orderObj = { id: order.id, orderStatus: approval_status, offlineApprovalNotes: approval_notes };
        var tmObj = { orderNum: orderNum };
        var tms = await self.trademarkDao.model.findAll({ where: tmObj, raw: true });
        var apply = await self.tmapplierinfoDao.findOne(tmObj);
        if (tms.length > 0 && apply) {
          var tm = tms[0];
          if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
            orderObj["orderStatus"] = "32";
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
          } else if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
            orderObj["orderStatus"] = "32";
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
          } else {
            tmObj["tmStatus"] = "READY";
          }
          var tmResult = await self.trademarkDao.model.update(tmObj, { where: { orderNum: orderNum }, transaction: t });

        }
        await self.dao.update(orderObj, t);
        if (approval_status == "4") {
          var tradeObj = {
            idkey: orderNum,
            tradeDate: new Date(),
            status: "settled",
            tradeType: "orderTrade",
            remark: "订单交易",
            renAmount: order.totalSum,
            app_id: order.app_id,
            account_id: user.account_id,
            user_id: order.user_id,
            username: user.userName,
            nickName: user.nickName,
            orderNum: order.orderNum
          };
          console.log(tradeObj);
          var trade = await self.tradeDao.createOrderTrade(tradeObj, t);//订单交易
          var orderflowObj = {
            app_id: order.app_id,
            user_id: order.user_id,
            userName: user.userName,
            nickName: user.nickName,
            orderNum: order.orderNum,
            opContent: "订单付款审核通过"
          };
          console.log(orderflowObj);
          var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程


        } else {
          var orderflowObj = {
            app_id: order.app_id,
            user_id: order.user_id,
            userName: user.userName,
            nickName: user.nickName,
            orderNum: order.orderNum,
            opContent: "订单付款审核不通过"
          };
          console.log(orderflowObj);
          var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
        }
        return result;
      }
    })

  }
  //商标自动提报专用
  async createOrder2(obj) {
    console.log(obj, "商标自动提报专用@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@");
    var result = { code: "1", msg: "success", order: null };
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    var user = obj.user;
    var app = obj.app;
    var nclones = obj.nclones || null;
    var copyright = obj.copyright || null;
    var copyrightType = Number(tm.reqtype || 0);//1软件著作权、2作品著作权、×××
    var copyrightData = null;
    var channel = await self.channelDao.model.findOne({ where: { channelCode: obj.channelCode, isPubed: 1 }, raw: true });//渠道信息
    if (!channel) {
      result.code = "-101";
      result.msg = "渠道错误";
      return result;
    }
    var serviceItem = await self.servicesitemDao.findOne({ code: obj.itemCode, channelCode: obj.channelCode });//服务项信息
    if (!serviceItem) {
      result.code = "-102";
      result.msg = "渠道产品不存在";
      return result;
    }
    if (tm.totalSum < serviceItem.platformWorkFloorPrice) {
      result.code = "-103";
      result.msg = "订单总价有误";
      return result;
    }
    if (serviceItem.itemType == "ip") {//商标数据
      if (!nclones || nclones == "undefined") {
        result.code = "-104";
        result.msg = "尼斯信息不能为空";
        return result;
      }
    }
    else if (serviceItem.itemType == "ic") {//著作权数据
      if (!copyright || copyright == "undefined") {
        result.code = "-105";
        result.msg = "著作权信息不能为空";
        return result;
      }
      copyrightData = JSON.parse(copyright);
    }
    return this.db.transaction(async function (t) {
      var u = await self.getCreateOrderNum();//====================订单号生成
      //创建订单对象 orderType:"1",itemCode:"sbzc",
      var orderObj = {
        applyName: apply.applyName || "",
        remark: tm.remark || "",
        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: apply.customerContact, customerMobile: apply.mobile,
        itemOrderNum: 1, itemOrderConsumeNum: 1,
        itemType: serviceItem.itemType,
        itemCode: obj.itemCode,
        orderType: "32",
        channelCode: obj.channelCode,
        channelName: channel.channelName,
        itemName: serviceItem.name,
        totalPublicExpense: tm.nclTotalPublicExpense, totalInvoiceTaxes: tm.invoiceTaxes, orderStatus: "1",
        totalServiceCharge: 0, totalSum: tm.totalSum, orderSourceType: "1", isSubProduct: 1,
        itemTypeTwoType: copyrightType//和是否提报产品结合使用：服务项目类型的二级类型0没有、1软件著作权、2作品著作权
      };
      console.log("---------------------------orderObj--------------------------------");
      console.log(orderObj)
      return self.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: "创建订单"
        };
        console.log("---------------------------orderflowObj--------------------------------");
        console.log(orderflowObj)
        var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
        //项目类型:ip:商标,ic:版权,pa:专利,iso:海外业务,common:增值服务,icbc:工商注册,zscq:知识产权,cwfw:财务服务,hyzz:行业资质,gqzr:股权转让,xzsp:行政审批
        if (serviceItem.itemType == "ip") {
          //商标数据openapi/order/getInfo
          await self.createOrder2ToAddTradeMark(self, user, app, tm, nclones, apply, order, t);
        }
        else if (serviceItem.itemType == "ic") {
          var tmpProxyCode = await self.getUUId(user.id);
          //添加代理人信息
          await self.copyrightuserinfoDao.createOrder2ToAddUser(order.orderNum, tmpProxyCode, copyrightType, t);
          //添加著作权人信息(单个)
          await self.copyrightauthorDao.createOrder2ToAddCrAuthor(order.orderNum, tmpProxyCode, apply, t);
          //软著数据，copyrightType=1软件著作权、2作品著作权
          if (copyrightType == 1) {
            copyrightData.statusProgress = "READY";//AWAITCHECK等待审核、WAITARTIFICIALEXAMINE等待人工审核、COMMITED人工已提交、READY资料准备
            //操作word里面的信息-需要解析附件中的信息
            await self.opWordInfo(copyrightData);
            await self.softwarecrsubmitDao.createOrder2ToAddSoftware(tmpProxyCode, copyrightData, order, t);
          }
          else if (copyrightType == 2) {
            await self.workcrsubmitDao.createOrder2ToAddWorks(tmpProxyCode, copyrightData, order, apply, t);
          }
        }
        //------------------------------------------------
        result.order = order;
        return result;
      });
    })
  };
  //添加商标数据
  async createOrder2ToAddTradeMark(self, user, app, tm, nclones, apply, order, t) {
    var customerObj = {
      zipCode: apply.zipCode || "", order_id: order.id, orderNum: order.orderNum,
      customerContact: apply.customerContact, mobile: apply.mobile, email: apply.email
    };
    var customer = await self.tmcustomerinfoDao.create(customerObj, t);//商标联系人
    var applierObj = {
      orderNum: order.orderNum, type: apply.type, applyName: apply.applyName,
      identityCard: apply.identityCard, creditCode: apply.creditCode,
      applyAddr: apply.applyAddr, identityCardPic: apply.identityCardPic,
      businessLicensePic: apply.businessLicensePic, identityCardPic2: apply.identityCardPic2,
      businessLicensePic2: apply.businessLicensePic2
    };
    console.log("---------------------------applierObj--------------------------------");
    console.log(applierObj)
    var applier = await self.tmapplierinfoDao.create(applierObj, t);//商标申请人信息
    for (var i = 0; i < nclones.length; i++) {
      var nclone = nclones[i];
      if (typeof (nclone) == "string") {
        nclone = JSON.parse(nclone);
      }
      // nclone = JSON.parse(nclone);
      var nclthreeobj = nclone.nclThree;
      var nclthreeobjCount = nclthreeobj.length;
      nclthreeobj = JSON.stringify(nclthreeobj);
      var key = await self.getUUId(user.id);
      var tmobj = {
        "applyName": apply.applyName,
        "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,
        "tmStatus": tm.tmStatus || "READY",
        "colorizedPicUrl": tm.colorizedPicUrl,
        "nclSmallCodes": nclthreeobj,
        "tmName": tm.tmName,
        "picUrl": tm.picUrl,
        "descUrl": apply.descUrl || "",
        "proxyCode": key,
        "sealAuthorizeStuff": apply.sealAuthorizeStuff,
        "channelOrderNum": tm.channelOrderNum || "",
        "channelUserId": tm.channelUserId || "",
        "channelPayStatus": tm.channelPayStatus || "wzf",
        "tmSourceType": tm.tmSourceType || "1",
        "needId": tm.needId || "",
        "channelOrderListInfo": nclone.channelOrderListInfo || tm.channelOrderListInfo || "",
        "nclCount": nclthreeobjCount,

      };
      var trademark = await self.trademarkDao.create(tmobj, t);
    }
  }
  //操作word里面的信息-需要解析附件中的信息
  async opWordInfo(copyrightData) {
    if (copyrightData.fileUrl) {
      //操作word里面的信息-需要解析附件中的信息
      var rc1 = system.getObject("util.execClient");
      var reqUrl = "http://43.247.184.92:8009/readcrword?appKey=343aff200d18be6637d&aliyunurl=" + copyrightData.fileUrl;
      try {
        var rtn1 = await rc1.execGet("", reqUrl);
        var relocation = JSON.parse(rtn1.stdout);
        if (relocation.status == 1 && relocation.data.length == 5) {
          copyrightData.statusProgress = "COMMITED";//AWAITCHECK等待审核、WAITARTIFICIALEXAMINE等待人工审核、COMMITED人工已提交、READY资料准备
          copyrightData.hardwareInfo = relocation.data[0];//硬件环境',
          copyrightData.softwareInfo = relocation.data[1];//软件环境',
          copyrightData.programmingLanguage = relocation.data[2];//编程语言',
          copyrightData.sourceCodeCapacity = relocation.data[3];//源程序量',
          copyrightData.softFunctionAndSpecialty = relocation.data[4];//主要功能和技术特点',
        }

      } catch (e) {
        //日志记录
        logCtl.error({
          optitle: "操作word里面的信息-需要解析附件中的信息异常error",
          op: "/base/service/impl/orderSve.js/opWordInfo",
          content: "opUrl=" + reqUrl,
          clientIp: ""
        });
      }
    }
  }

  async orderUpdate(obj) {
    var user = obj.user;
    if (!user) {
      return { code: "-4", msg: "用户为空" };
    }
    delete obj.user;
    if (!obj.id) {
      return { code: "-1", msg: "id为空" };
    }
    try {
      await this.dao.model.update(obj, { where: { id: obj.id } });
      return { code: "1", msg: "success" };
    } catch (error) {

      return { code: "-2", msg: "err" };
    }

  }
  //商标自动提报专用
  async updateOrderDetailByOrderNum(obj, onlyCode) {
    console.log("商标自动提报专用#####################");
    var self = this;
    var tmObj = obj.tm || null;
    var apply = obj.apply || null;//或是copyright
    var copyright = obj.copyright || null;
    var customer = obj.customer || null;
    var copyrightType = Number(tmObj.reqtype || 0);//1软件著作权、2作品著作权、×××
    var order = {
      orderNum: tmObj.orderNum, applyName: apply.applyName || "", customerContact: customer.customerContact,
      customerMobile: customer.mobile, remark: apply.remark || ""
    };
    var o = await this.dao.findOne({ orderNum: order.orderNum });
    if (!o) {
      return { code: "-100", msg: "未查到相应订单，无法修改" };
    }
    if (o.onlyCode != onlyCode) {
      return { code: "-100", msg: "只能操作自己的订单数据" };
    }

    //分类处理订单修改
    //项目类型:ip:商标,ic:版权,pa:专利,iso:海外业务,common:增值服务,icbc:工商注册,zscq:知识产权,cwfw:财务服务,hyzz:行业资质,gqzr:股权转让,xzsp:行政审批
    if (o.itemType == "ip") {
      //商标数据
      var setResult = await self.setPutOrderByTrademark(apply, o, order, tmObj);
      if (setResult.code != "1") {
        return setResult;
      }
    }
    else if (o.itemType == "ic") {
      if (!copyright) {
        return { code: "-100", msg: "著作权信息为空" };
      }
      //软著数据，copyrightType=1软件著作权、2作品著作权
      if (copyrightType == 1) {
        var setResult = await self.setPutOrderBySoftware(copyright, apply, o, order);
        if (setResult.code != "1") {
          return setResult;
        }
      }
      else if (copyrightType == 2) {
        var setResult = await self.setPutOrderByWorks(copyright, apply, o, order);
        if (setResult.code != "1") {
          return setResult;
        }
      }
    }
    return this.db.transaction(async function (t) {
      var orderResult = await self.dao.model.update(order, { where: { orderNum: order.orderNum }, transaction: t });

      if (o.itemType == "ip") {
        //商标数据
        var tmResult = await self.trademarkDao.model.update(tmObj, { where: { orderNum: tmObj.orderNum }, transaction: t });
        var applyResult = await self.tmapplierinfoDao.model.update(apply, { where: { orderNum: apply.orderNum }, transaction: t });
        //商标订单联系人
        var customerResult = await self.tmcustomerinfoDao.model.update(customer, { where: { orderNum: customer.orderNum }, transaction: t });
      }
      else if (o.itemType == "ic") {
        //添加著作权人信息(单个)
        await self.copyrightauthorDao.model.update(apply, { where: { orderNum: customer.orderNum }, transaction: t });
        //软著数据，copyrightType=1软件著作权、2作品著作权
        if (copyrightType == 1) {
          await self.softwarecrsubmitDao.model.update(copyright, { where: { orderNum: customer.orderNum }, transaction: t });
        }
        else if (copyrightType == 2) {
          await self.workcrsubmitDao.model.update(copyright, { where: { orderNum: customer.orderNum }, transaction: t });
        }
      }
      return { code: "1", msg: "success" };
    })
  };
  //updateOrderDetailByOrderNum__自动提报修改判断商标数据及状态
  async setPutOrderByTrademark(apply, o, order, tmObj) {
    var tms = await this.trademarkDao.model.findAll({ where: { orderNum: order.orderNum }, raw: true });
    for (var i = 0; i < tms.length; i++) {
      var tm = tms[i];
      if (tm.tmStatus != "WAITARTIFICIALEXAMINE" && tm.tmStatus != "FILLEXCEPTION" && tm.tmStatus != "READY") {
        return { code: "-100", msg: "修改失败，存在资料准备、等待人工审核以及填报异常之外状态的商标" };
      }
    }
    //"order_status":{"1":"未付款","2":"订单取消","4":"付款成功","8":"退款处理中","16":"已退款","32":"已提报","64":"审核中"},

    if (o.orderStatus == "2") {
      return { code: "-100", msg: "该订单已取消，无法修改" };
    }
    if (o.orderStatus == "8") {
      return { code: "-100", msg: "该订单正在退款，无法修改" };
    }
    if (o.orderStatus == "16") {
      return { code: "-100", msg: "该订单已退款，无法修改" };
    }
    if (o.orderStatus == "4" || o.orderStatus == "32") {
      if (tmObj.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
        order["orderStatus"] = "32";
        tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
      } else if (tmObj.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
        order["orderStatus"] = "32";
        tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
      } else {
        order["orderStatus"] = "4";
        tmObj["tmStatus"] = "READY";
      }
    }
    return { code: "1", msg: "success" };
  }
  //updateOrderDetailByOrderNum__自动提报修改判断软件著作权数据及状态
  async setPutOrderBySoftware(copyright, apply, o, order) {
    var software = await this.softwarecrsubmitDao.model.findOne({ where: { orderNum: order.orderNum }, raw: true });
    if (!software) {
      return { code: "-100", msg: "软件著作权的信息为空" };
    }
    //"order_status":{"1":"未付款","2":"订单取消","4":"付款成功","8":"退款处理中","16":"已退款","32":"已提报","64":"审核中"},
    if (o.orderStatus == "2") {
      return { code: "-100", msg: "该订单已取消，无法修改" };
    }
    if (o.orderStatus == "8") {
      return { code: "-100", msg: "该订单正在退款，无法修改" };
    }
    if (o.orderStatus == "16") {
      return { code: "-100", msg: "该订单已退款，无法修改" };
    }
    if (o.orderStatus == "4" || o.orderStatus == "32") {
      if (software.fileUrl != copyright.fileUrl) {
        //操作word里面的信息-需要解析附件中的信息
        await this.opWordInfo(copyright);
      }
      if (copyright.hardwareInfo && copyright.softwareInfo && copyright.programmingLanguage
        && copyright.sourceCodeCapacity && copyright.softFunctionAndSpecialty) {
        order["orderStatus"] = "32";
        copyright["statusProgress"] = "COMMITED";//人工已提交
      } else {
        order["orderStatus"] = "4";
        copyright["statusProgress"] = "READY";
      }
    }
    return { code: "1", msg: "success" };
  }
  //updateOrderDetailByOrderNum__自动提报修改判断作品著作权数据及状态
  async setPutOrderByWorks(copyright, apply, o, order) {
    var works = await this.workcrsubmitDao.model.findOne({ where: { orderNum: order.orderNum }, raw: true });
    if (!works) {
      return { code: "-100", msg: "作品著作权的信息为空" };
    }
    //"order_status":{"1":"未付款","2":"订单取消","4":"付款成功","8":"退款处理中","16":"已退款","32":"已提报","64":"审核中"},

    if (o.orderStatus == "2") {
      return { code: "-100", msg: "该订单已取消，无法修改" };
    }
    if (o.orderStatus == "8") {
      return { code: "-100", msg: "该订单正在退款，无法修改" };
    }
    if (o.orderStatus == "16") {
      return { code: "-100", msg: "该订单已退款，无法修改" };
    }
    if (o.orderStatus == "4" || o.orderStatus == "32") {
      order["orderStatus"] = "4";
      copyright["statusProgress"] = "COMMITED";//人工已提交
    }
    return { code: "1", msg: "success" };
  }
  //商标自动提报专用
  async getOrderDetailByOrderNum(obj, req) {
    var user = req.session.user;
    var orderNum = obj.orderNum;
    if (!orderNum) {
      return { code: "-2", msg: "orderNum参数错误" };
    }
    console.log("商标自动提报专用$$$$$$$$$$$$$$$$$$$$4");
    var result = { code: "-1", msg: "操作失败" };
    var obj = { orderNum: orderNum };
    var tmObj = { orderNum: orderNum };
    // if (user && user.mobile) {
    //   tmObj["mobile"] = user.mobile;
    // }
    var tms = await this.trademarkDao.model.findAll({ where: tmObj, raw: true });
    var apply = await this.tmapplierinfoDao.findOne(obj);
    var customer = await this.tmcustomerinfoDao.findOne(obj);
    var order = await this.dao.findOne(obj);
    return { code: "1", msg: "success", data: { apply: apply, tms: tms, order: order, customer: customer } };
  };
  //商标自动提报专用(知圈圈嵌入页用)
  async getFqOrderDetailByOrderNum(obj) {
    var orderNum = obj.orderNum;
    if (!orderNum) {
      return { code: "-2", msg: "orderNum参数错误" };
    }
    var result = { code: "-1", msg: "操作失败" };
    var obj = { orderNum: orderNum };
    var tmObj = { orderNum: orderNum };
    var tms = await this.trademarkDao.model.findAll({ where: tmObj, raw: true });
    var apply = await this.tmapplierinfoDao.findOne(obj);
    var customer = await this.tmcustomerinfoDao.findOne(obj);
    var order = await this.dao.findOne(obj);
    return { code: "1", msg: "success", data: { apply: apply, tms: tms, order: order, customer: customer } };
  };
  //软件著作权自动提报专用
  async getSoftwareOrderDetailByOrderNum(obj) {
    var orderNum = obj.orderNum;
    if (!orderNum) {
      return { code: "-2", msg: "orderNum参数错误" };
    }
    var result = { code: "-1", msg: "操作失败" };
    var obj = { orderNum: orderNum };
    var copyright = await this.softwarecrsubmitDao.model.findOne({ where: obj, raw: true });
    var apply = await this.copyrightauthorDao.findOne(obj);
    var order = await this.dao.findOne(obj);
    if (!order || !copyright || !apply) {
      return { code: "-10", msg: "操作失败，请重新再试", data: {} };
    }
    var param = {
      customerContact: order.customerContact,//客户联系人',
      mobile: order.customerMobile,//联系电话',
      name: apply.name,
      type: apply.type,//'类型，企业法人或个体商户',
      countryName: apply.countryName,//国籍',
      applyProvince: apply.applyProvince,//省',
      applyCity: apply.applyCity,//'市',
      certificateType: apply.certificateType,//证件类型企业法人营业执照或XXXXx',
      certificateCode: apply.certificateCode,//证件号码',
      garden: apply.garden,//园区',
      entType: apply.entType || "",//企业类别',
      sign_info: apply.sign_info || "",//'署名情况信息',
      alias_info: apply.alias_info || ""//'别名信息',
    }
    return { code: "1", msg: "success", data: { apply: param, copyright: copyright, order: order } };
  };
  //软件著作权自动提报专用
  async getWorksOrderDetailByOrderNum(obj) {
    var orderNum = obj.orderNum;
    if (!orderNum) {
      return { code: "-2", msg: "orderNum参数错误" };
    }
    var result = { code: "-1", msg: "操作失败" };
    var obj = { orderNum: orderNum };
    var copyright = await this.workcrsubmitDao.model.findOne({ where: obj, raw: true });
    var apply = await this.copyrightauthorDao.findOne(obj);
    var order = await this.dao.findOne(obj);
    if (!order || !copyright || !apply) {
      return { code: "-10", msg: "操作失败，请重新再试", data: {} };
    }
    // "authorName": apply.authorName,
    // "authorSign": apply.authorSign
    var param = {
      customerContact: order.customerContact,//客户联系人',
      mobile: order.customerMobile,//联系电话',
      name: apply.name,
      type: apply.type,//'类型，企业法人或个体商户',
      countryName: apply.countryName,//国籍',
      applyProvince: apply.applyProvince,//省',
      applyCity: apply.applyCity,//'市',
      certificateType: apply.certificateType,//证件类型企业法人营业执照或XXXXx',
      certificateCode: apply.certificateCode,//证件号码',
      garden: apply.garden,//园区',
      entType: apply.entType || "",//企业类别',
      sign_info: apply.sign_info || "",//'署名情况信息',
      alias_info: apply.alias_info || ""//'别名信息',
    }
    if (copyright.authorData && copyright.authorData.length > 5) {
      var tmpAuthorData = JSON.parse(copyright.authorData);
      if (tmpAuthorData.length > 0) {
        param.authorName = tmpAuthorData[0].authorName;
        param.authorSign = tmpAuthorData[0].authorSign;
      }
    }
    return { code: "1", msg: "success", data: { apply: param, copyright: copyright, order: order } };
  };
  // 商标自动提报专用 微信支付成功回调
  async createOrderTrade2(obj) {
    var orderNum = obj.orderNum;
    var payUser = obj.payUser;
    var payResult = obj.payResult;
    var that = this;
    var order = await this.dao.findOneByOrderNum(orderNum);
    var user = await this.userDao.findById(order.user_id);
    var apply = await this.tmapplierinfoDao.model.findOne({ orderNum: order.orderNum });
    var tms = await this.trademarkDao.model.findAll({ where: { orderNum: order.orderNum }, raw: true });
    var tm = null;
    if (tms.length > 0) {
      tm = tms[0];
    }
    if (order.orderStatus == "1") {
      return this.db.transaction(async function (t) {
        var tradeObj = {
          idkey: orderNum,
          tradeDate: new Date(),
          status: "settled",
          tradeType: "orderTrade",
          remark: "订单交易",
          renAmount: Number(payResult.total_fee) / 100,
          app_id: order.app_id,
          account_id: user.account_id,
          user_id: order.user_id,
          username: user.userName,
          nickName: user.nickName,
          orderNum: order.orderNum
        };
        var trade = await that.tradeDao.createOrderTrade(tradeObj, t);//订单交易
        var orderflowObj = {
          app_id: order.app_id,
          user_id: order.user_id,
          userName: user.userName,
          nickName: user.nickName,
          orderNum: order.orderNum,
          opContent: "订单付款"
        };
        var orderflow = await that.orderflowDao.create(orderflowObj, t);//订单流程
        order.orderStatus = "4";
        order.paymentSerialNumber = payResult.transaction_id;
        order.paymentPlatformType = "wx";//支付平台类型:"wx":"微信","offline":"线下"
        order.payUserId = payUser.id;
        order.payNickName = payUser.nickName;
        order.payAppId = payUser.appid;
        console.log(order);
        if (tm) {
          var tmObj = { orderNum: order.orderNum };
          if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
            order.orderStatus = "32";
          } else if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
            order.orderStatus = "32";
          } else {
            tmObj["tmStatus"] = "READY";
          }
          var tmResult = await that.trademarkDao.model.update(tmObj, { where: { orderNum: order.orderNum }, transaction: t });

        }
        var orderResult = await that.dao.update(order.dataValues, t);

        order.orderStatusName = "付款成功";
        var result = { trade: trade, order: order };
        //发送短信
        //订单来源类型，1PC，2移动商城，4渠道方
        if (order.orderSourceType == "2") {
          var shopItem = await that.shopDao.getShopItemInfo(order.shopOnlyCode);
          if (shopItem != null) {
            var smsClient = system.getObject("util.smsClient");
            smsClient.sendMsg(shopItem.userMobile, "亲爱的知产合伙人，你的客户于" + (new Date()).Format("yyyy-MM-dd") + "成功购买【" + order.itemName + "】服务，亲，赶紧去自己店铺收钱吧！");
          }
        }
        return result;
      });
    } else {
      return { order: order };
    }
  };

  async getLastTmOrder(onlycode, itemCode) {
    var orderArr = null;
    if (itemCode) {
      orderArr = await this.dao.model.findAll({ where: { onlyCode: onlycode, itemCode: itemCode }, order: [["created_at", "DESC"]], limit: 1, raw: true });

    } else {
      orderArr = await this.dao.model.findAll({ where: { onlyCode: onlycode }, order: [["created_at", "DESC"]], limit: 1, raw: true });

    }
    if (orderArr && orderArr.length > 0) {
      var order = orderArr[0];
      var obj = { orderNum: order.orderNum };
      var tms = await this.trademarkDao.model.findAll({ where: obj, raw: true });
      var apply = await this.tmapplierinfoDao.findOne(obj);
      var customer = await this.tmcustomerinfoDao.findOne(obj);
      return { code: "1", msg: "success", data: { apply: apply, tms: tms, order: order, customer: customer } };
    } else {
      return { code: "-1", msg: "no order" };
    }

  }
  //校验有效订单
  async checkChannelUsableOrder(usableOrderList, nclones) {
    if (!nclones) {
      return { code: -300, msg: "尼斯信息为空" };
    }
    if (!usableOrderList || usableOrderList.length < 1) {
      return { code: -301, msg: "无可用订单" };
    }
    for (var i = 0; i < nclones.length; i++) {
      var nclone = nclones[i];
      if (typeof (nclone) == "string") {
        nclone = JSON.parse(nclone);
      }
      var nclthree = nclone.nclThree;
      for (var j = 0; j < usableOrderList.length; j++) {
        var uorder = usableOrderList[j];
        if (uorder.order_no && uorder.class_count && nclone.channelOrderListInfo && nclone.channelOrderListInfo == uorder.order_no) {
          if (uorder.class_count > 10) {
            if (nclthree.length != uorder.class_count) {
              return { code: -302, msg: "建案内容与订单条件不匹配，请仔细核对！" };
            }
          } else {
            if (nclthree.length > 10) {
              return { code: -303, msg: "建案内容与订单条件不匹配，请仔细核对！" };
            }
          }
        }
      }
      return { code: 1 };
    }
  }
  //商标自动提报(内部)专用
  async createInsideOrder(obj) {
    var result = { code: "1", msg: "success", order: null };
    var channelorder = obj.channelorder;
    var self = this;
    var tm = obj.tm;
    tm["tmSourceType"] = "16";
    if (obj.channelCode == "ali_zcsubmit") {
      tm["tmSourceType"] = "32";
      if (!obj.needId) {
        result.code = "-100";
        result.msg = "阿里云需求ID不能为空";
        return result;
      }
      tm["needId"] = obj.needId;
    }
    // else if (obj.channelCode == "1688") {
    //   tm["tmSourceType"] = "64";
    //   if (!obj.needId) {
    //     result.code = "-110";
    //     result.msg = "1688需求ID不能为空";
    //     return result;
    //   }
    //   tm["needId"] = obj.needId;
    // }else if (obj.channelCode == "jd") {
    //   tm["tmSourceType"] = "128";
    //   if (!obj.needId) {
    //     result.code = "-110";
    //     result.msg = "jd需求ID不能为空";
    //     return result;
    //   }
    //   tm["needId"] = obj.needId;
    // }
    var judgeRes = self.trademarkDao.judgeChannelCode(obj.channelCode);//判断渠道码
    if (judgeRes) {
      tm["tmSourceType"] = judgeRes;
      if (!obj.needId) {
        result.code = "-110";
        result.msg = obj.channelCode + "需求ID不能为空";
        return result;
      }
      tm["needId"] = obj.needId;
    }
    tm["channelOrderListInfo"] = channelorder.order_nos && channelorder.order_nos.length > 0 ? channelorder.order_nos.join('，') : "";
    var apply = obj.apply;
    var user = obj.user;
    var app = obj.app;
    var nclones = obj.nclones || null;
    var copyright = obj.copyright || null;
    var copyrightType = Number(tm.reqtype || 0);//1软件著作权、2作品著作权、×××
    var copyrightData = null;
    var channel = await self.channelDao.model.findOne({ where: { channelCode: obj.channelCode, isPubed: 1 }, raw: true });//渠道信息
    if (!channel) {
      result.code = "-110";
      result.msg = "渠道错误";
      return result;
    }
    var serviceItem = await self.servicesitemDao.findOne({ code: obj.itemCode, channelCode: obj.channelCode });//服务项信息
    if (!serviceItem) {
      result.code = "-120";
      result.msg = "渠道产品不存在";
      return result;
    }
    // if (tm.totalSum < serviceItem.platformWorkFloorPrice) {
    //   result.code = "-103";
    //   result.msg = "订单总价有误";
    //   return result;
    // }
    if (serviceItem.itemType == "ip") {//商标数据
      if (!nclones || nclones == "undefined") {
        result.code = "-130";
        result.msg = "尼斯信息不能为空";
        return result;
      }
      var count = channelorder.oneClassCount;
      if (!count || count == 0) {
        return { code: "-140", msg: "渠道服务单数量有误" };
      } else if (nclones.length > Number(count)) {
        return { code: "-150", msg: "尼斯大类数量不能大于渠道可用服务单数量，可用渠道服务单的大类数量为" + count };
      }

      var usable_order_no_class_count = channelorder.usable_order_no_class_count;//有效渠道订单列表
      var checkRes = await this.checkChannelUsableOrder(usable_order_no_class_count, nclones);//校验有效订单
      if (checkRes.code != 1) {
        return checkRes;
      }
      //获取已提交的商标信息 用作校验重复提交
      var oldtms = await this.trademarkDao.model.findAll({
        where:{channelOrderNum:obj.channelOrderNum,applyName:apply.applyName,tmName:tm.tmName},
        raw:true
      });
      var oldNclOneCodes = [];//已提交商标尼斯集合
      if(oldtms && oldtms.length>0){
        for(var a=0;a<oldtms.length;a++){
          var oldtm = oldtms[a];
          oldNclOneCodes.push(oldtm.nclOneCodes);
        }
      }
      //校验重复提交并判断尼斯小项的数量
      var selectNclThreeCount = 0;
      for (let index = 0; index < nclones.length; index++) {
        const element = nclones[index];
        if(element.code && oldNclOneCodes.length>0){
          if(oldNclOneCodes.indexOf(element.code)>=0){
            return { code: "-260", msg: "已存在第" + element.code + "类的商标，不能重复提交" };
          }
        }
        
        var nclList = null;
        if (typeof (element) == "string") {
          nclList = JSON.parse(element);
        } else {
          nclList = element;
        }
        // var nclList = JSON.parse(element);
        selectNclThreeCount = selectNclThreeCount + nclList.nclThree.length;
      }
      var nclThreeCount = channelorder.nclThreeCount;
      if (selectNclThreeCount > Number(nclThreeCount)) {
        return { code: "-155", msg: "尼斯小项数量不能大于渠道可用服务单尼斯小项数量，可用渠道服务单的尼斯小项数量为" + nclThreeCount };
      }
    }
    else if (serviceItem.itemType == "ic") {//著作权数据
      if (!copyright || copyright == "undefined") {
        result.code = "-160";
        result.msg = "著作权信息不能为空";
        return result;
      }
      if (typeof (copyright) == "string") {
        copyrightData = JSON.parse(copyright);
      } else {
        copyrightData = copyright;
      }
      // copyrightData = JSON.parse(copyright);
    }
    return this.db.transaction(async function (t) {
      if (!user.userName || !user.companyName) {
        if (channelorder.operator_name && channelorder.org_name) {
          if (channelorder.operator_name != user.userName || channelorder.org_name != user.companyName) {
            //更新用户信息
            var userUpdateObj = {
              userName: channelorder.operator_name,
              nickName: channelorder.operator_name,
              companyName: channelorder.org_name
            };
            await self.userDao.updateByWhere(userUpdateObj, { where: { id: user.id } }, t);
            user["userName"] = channelorder.operator_name;
            user["nickName"] = channelorder.operator_name;
            user["companyName"] = channelorder.org_name;
          }
        }
      }
      var u = await self.getCreateOrderNum();//====================订单号生成
      //创建订单对象 orderType:"1",itemCode:"sbzc",
      var orderObj = {
        applyName: apply.applyName || "",
        remark: tm.remark || "",
        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: apply.customerContact, customerMobile: apply.mobile,
        itemOrderNum: nclones.length, itemOrderConsumeNum: nclones.length,
        itemType: serviceItem.itemType,
        itemCode: obj.itemCode,
        orderType: "32",
        channelCode: obj.channelCode,
        channelName: channel.channelName,
        itemName: serviceItem.name, channelOrderNum: obj.channelOrderNum, channelUserId: obj.channelUserId,
        totalPublicExpense: 0, totalInvoiceTaxes: 0, orderStatus: "4",
        totalServiceCharge: 0, totalSum: 0, orderSourceType: "1", isSubProduct: 1,
        itemTypeTwoType: copyrightType//和是否提报产品结合使用：服务项目类型的二级类型0没有、1软件著作权、2作品著作权
      };
      tm["channelUserId"] = obj.channelUserId || "";
      tm["channelOrderNum"] = obj.channelOrderNum || "";

      //第三方传递过来的订单信息来确定商标渠道支付状态，1支付，2待支付
      if (channelorder.order_pay_state && channelorder.order_pay_state == "已付清") {
        tm["channelPayStatus"] = "yzf";
      }
      else {
        tm["channelPayStatus"] = "wzf";
      }

      if (apply.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
        tm["tmStatus"] = obj.channelCode == "ali_zcsubmit" ? "DOCFINISH" : "WAITARTIFICIALEXAMINE";
        orderObj.orderStatus = "32";
      } else if (apply.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
        tm["tmStatus"] = obj.channelCode == "ali_zcsubmit" ? "DOCFINISH" : "WAITARTIFICIALEXAMINE";
        orderObj.orderStatus = "32";
      } else {
        tm["tmStatus"] = "READY";
      }
      // if (obj.channelCode == "1688" || obj.channelCode == "jd") {
      //   tm["tmStatus"] = "WAITCONFIRM";
      // }
      if (judgeRes) {
        tm["tmStatus"] = "WAITCONFIRM";
      }
      // console.log("---------------------------orderObj--------------------------------");
      // console.log(orderObj)
      return self.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: "创建订单"
        };
        console.log("---------------------------orderflowObj--------------------------------");
        console.log(orderflowObj)
        var orderflow = await self.orderflowDao.create(orderflowObj, t);//订单流程
        //项目类型:ip:商标,ic:版权,pa:专利,iso:海外业务,common:增值服务,icbc:工商注册,zscq:知识产权,cwfw:财务服务,hyzz:行业资质,gqzr:股权转让,xzsp:行政审批
        if (serviceItem.itemType == "ip") {
          //商标数据
          await self.createOrder2ToAddTradeMark(self, user, app, tm, nclones, apply, order, t);
        }
        else if (serviceItem.itemType == "ic") {
          var tmpProxyCode = await self.getUUId(user.id);
          //添加代理人信息
          await self.copyrightuserinfoDao.createOrder2ToAddUser(order.orderNum, tmpProxyCode, copyrightType, t);
          //添加著作权人信息(单个)
          await self.copyrightauthorDao.createOrder2ToAddCrAuthor(order.orderNum, tmpProxyCode, apply, t);
          //软著数据，copyrightType=1软件著作权、2作品著作权
          if (copyrightType == 1) {
            copyrightData.statusProgress = "READY";//AWAITCHECK等待审核、WAITARTIFICIALEXAMINE等待人工审核、COMMITED人工已提交、READY资料准备
            //操作word里面的信息-需要解析附件中的信息
            await self.opWordInfo(copyrightData);
            await self.softwarecrsubmitDao.createOrder2ToAddSoftware(tmpProxyCode, copyrightData, order, t);
          }
          else if (copyrightType == 2) {
            await self.workcrsubmitDao.createOrder2ToAddWorks(tmpProxyCode, copyrightData, order, apply, t);
          }
        }
        //------------------------------------------------
        result.order = order;
        return result;
      });
    })
  };
  //商标自动提报(内部)专用---修改
  async updateInsideOrderDetailByOrderNum(obj, onlyCode) {
    // console.log("商标自动提报专用#####################");
    var self = this;
    var channelorder = obj.channelorder;
    var user = obj.user;
    var app = obj.app;
    var nclones = obj.nclones;
    var tm = obj.tm || null;
    var apply = obj.apply || null;//或是copyright
    var copyright = obj.copyright || null;
    var customer = obj.customer || null;
    var copyrightType = Number(tm.reqtype || 0);//1软件著作权、2作品著作权、×××
    var order = {
      orderNum: tm.orderNum, applyName: apply.applyName || "", customerContact: customer.customerContact,
      customerMobile: customer.mobile, remark: apply.remark || ""
    };
    var orderItem = await this.dao.findOne({ orderNum: order.orderNum });
    if (!orderItem) {
      return { code: "-100", msg: "系统中未查到相应订单，无法修改" };
    }
    //判断不是beehive过来的渠道订单进行用户判断处理----sy
    // if (o.orderSourceType != "8" && o.onlyCode != onlyCode) {
    //   return { code: "-100", msg: "只能操作自己的订单数据" };
    // }
    if (!nclones || nclones == "undefined") {
      result.code = "-110";
      result.msg = "尼斯信息不能为空";
      return result;
    }
    var remainder = channelorder.fqRemainder;
    if (!remainder || remainder == 0) {
      return { code: "-120", msg: "该渠道服务单号数量有误" };
    } else if (nclones.length > Number(remainder)) {
      return { code: "-130", msg: "该渠道服务单号数量不足" };
    }
    // var time = new Date().getTime();
    // if (time > 1576339199000) {//2019-12-14 23:59:59
    //   var usable_order_no_class_count = channelorder.usable_order_no_class_count;//有效渠道订单列表
    //   var checkRes = await this.checkChannelUsableOrder(usable_order_no_class_count, nclones);//校验有效订单
    //   if (checkRes.code != 1) {
    //     return checkRes;
    //   }
    // }
    if(orderItem.created_at && orderItem.orderSourceType != "8"){
      var time = new Date(orderItem.created_at).getTime();
      if(time>1576339199000){//2019-12-14 23:59:59
        var usable_order_no_class_count = channelorder.usable_order_no_class_count;//有效渠道订单列表
        var checkRes = await this.checkChannelUsableOrder(usable_order_no_class_count,nclones);//校验有效订单
        if(checkRes.code!=1){
          return checkRes;
        }
      }
    }
    //判断尼斯小项的数量
    var selectNclThreeCount = 0;
    for (let index = 0; index < nclones.length; index++) {
      const element = nclones[index];
      var nclList = null;
      if (typeof (element) == "string") {
        nclList = JSON.parse(element);
      } else {
        nclList = element;
      }
      selectNclThreeCount = selectNclThreeCount + nclList.nclThree.length;
    }
    var nclThreeCount = channelorder.fqNclThreeCount;
    if (selectNclThreeCount > Number(nclThreeCount)) {
      return { code: "-155", msg: "尼斯小项数量不能大于渠道可用服务单尼斯小项数量，可用渠道服务单的尼斯小项数量为" + nclThreeCount };
    }

    var tms = await self.trademarkDao.model.findAll({ where: { orderNum: order.orderNum }, raw: true });
    var tradem = null;
    for (var i = 0; i < tms.length; i++) {
      tradem = tms[i];
      //------sy
      // "4": "不予受理"
      // "FILLEXCEPTION": "填报异常"
      // "READY": "资料准备"
      // "DOCFINISH": "资料齐全"
      // "AWAITCHECK": "等待审核"
      // "WAITARTIFICIALEXAMINE": "等待人工审核"
      // "WAITCOMMIT": "待提交"
      // "ALIPAYREFUND": "已失败退款(阿里)"
      // "ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)"
      // "ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)"
      // "SUBALITM": "已提交阿里(待补全信息)"
      // "REQALIERROR": "阿里接口错误(需峰擎系统处理)"
      // "SUBALITMOK": "已补全信息(待确认商标)",
      if (["WAITCONFIRM", "CONFIRMFAIL", "4", "FILLEXCEPTION", "READY", "DOCFINISH", "AWAITCHECK", "WAITARTIFICIALEXAMINE", "WAITCOMMIT", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "SUBALITM", "REQALIERROR", "SUBALITMOK"].indexOf(tradem.tmStatus) < 0) {
        return { code: "-140", msg: "存在状态为" + tradem.tmStatusName + "的商标，不能修改" };
      }
    }
    tm["channelOrderListInfo"] = channelorder.order_nos && channelorder.order_nos.length > 0 ? channelorder.order_nos.join('，') : "";
    tm["channelUserId"] = obj.channelUserId || "";
    tm["channelOrderNum"] = obj.channelOrderNum || "";
    return this.db.transaction(async function (t) {
      //第三方传递过来的订单信息来确定商标渠道支付状态，1支付，2待支付
      if (channelorder.order_pay_state && channelorder.order_pay_state == "已付清") {
        tm["channelPayStatus"] = "yzf";
      }
      if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
        tm["tmStatus"] = orderItem.channelCode == "ali_zcsubmit" ? "DOCFINISH" : "WAITARTIFICIALEXAMINE";

        order["orderStatus"] = "32";
      } else if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
        tm["tmStatus"] = orderItem.channelCode == "ali_zcsubmit" ? "DOCFINISH" : "WAITARTIFICIALEXAMINE";
        // if (obj.channelCode == "1688") {
        //   tm["tmStatus"] = "WAITCONFIRM";
        // }
        order["orderStatus"] = "32";
      } else {
        tm["tmStatus"] = "READY";
      }
      // if (orderItem.channelCode == "1688" || orderItem.channelCode == "jd") {
      //   tm["tmStatus"] = "WAITCONFIRM";
      // }
      var judgeRes = self.trademarkDao.judgeChannelCode(orderItem.channelCode);//判断渠道码
      if (judgeRes) {
        tm["tmStatus"] = "WAITCONFIRM";
      }
      //删除旧商标数据
      var setResult = await self.trademarkDao.model.destroy({ where: { orderNum: order.orderNum }, transaction: t });
      var orderResult = await self.dao.model.update(order, { where: { orderNum: order.orderNum }, transaction: t });
      var applyResult = await self.tmapplierinfoDao.model.update(apply, { where: { orderNum: apply.orderNum }, transaction: t });

      //商标订单联系人
      var customerResult = null;
      var customerObj = await self.tmcustomerinfoDao.model.findOne({ where: { orderNum: customer.orderNum }, raw: true });
      if (customerObj && customerObj.id) {
        customerResult = await self.tmcustomerinfoDao.model.update(customer, { where: { orderNum: customer.orderNum }, transaction: t });
      } else {
        customerResult = await self.tmcustomerinfoDao.create(customer, t);//商标联系人
      }
      tm["tmSourceType"] = "16";
      if (orderItem.channelCode == "ali_zcsubmit") {
        tm["tmSourceType"] = "32";
        if (!channelorder.needId) {
          result.code = "-150";
          result.msg = "阿里云需求ID不能为空!";
          return result;
        }
        tm["needId"] = channelorder.needId;
      }
      // else if (orderItem.channelCode == "1688") {
      //   tm["tmSourceType"] = "64";
      //   if (!channelorder.needId) {
      //     result.code = "-160";
      //     result.msg = "1688需求ID不能为空!";
      //     return result;
      //   }
      //   tm["needId"] = channelorder.needId;
      // }else if (orderItem.channelCode == "jd") {
      //   tm["tmSourceType"] = "128";
      //   if (!channelorder.needId) {
      //     result.code = "-160";
      //     result.msg = "jd需求ID不能为空!";
      //     return result;
      //   }
      //   tm["needId"] = channelorder.needId;
      // }
      if (judgeRes) {
        tm["tmSourceType"] = judgeRes;
        if (!channelorder.needId) {
          result.code = "-160";
          result.msg = orderItem.channelCode + "需求ID不能为空!";
          return result;
        }
        tm["needId"] = channelorder.needId;
      }
      for (var i = 0; i < nclones.length; i++) {
        var nclone = nclones[i];
        if (!nclone.code) {
          continue;
        }
        var nclthreeobj = nclone.nclThree;
        var nclthreeobjCount = nclthreeobj.length;
        nclthreeobj = JSON.stringify(nclthreeobj);
        var key = await self.getUUId(user.id);
        var oldTmList = tms.filter(f => f.nclOneCodes == nclone.code);
        if (orderItem.channelCode == "ali_zcsubmit") {
          tm["tmStatus"] = oldTmList && oldTmList.length > 0 ? oldTmList[0].tmStatus : tm.tmStatus || "READY";
        }
        var tmobj = {
          "applyName": apply.applyName,
          "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,
          "tmStatus": tm.tmStatus,
          "colorizedPicUrl": tm.colorizedPicUrl,
          "nclSmallCodes": nclthreeobj,
          "tmName": tm.tmName,
          "picUrl": tm.picUrl,
          "proxyCode": key,
          "sealAuthorizeStuff": tm.sealAuthorizeStuff,
          "descUrl": tm.descUrl || "",
          "channelOrderNum": tm.channelOrderNum,
          "channelUserId": tm.channelUserId,
          "channelPayStatus": tm.channelPayStatus || "wzf",
          "tmSourceType": oldTmList && oldTmList.length > 0 ? oldTmList[0].tmSourceType : tm.tmSourceType || "1",
          "needId": oldTmList && oldTmList.length > 0 ? oldTmList[0].needId : tm.needId || "",
          "businessId": oldTmList && oldTmList.length > 0 ? oldTmList[0].businessId : "",
          "channelOrderListInfo": nclone.channelOrderListInfo || tm.channelOrderListInfo || "",
          "nclCount": nclthreeobjCount,
        };
        // console.log(tmobj);
        var trademark = await self.trademarkDao.create(tmobj, t);
      }
      return { code: "1", msg: "success" };
    })
  };

  //商标自动提报(内部后期)专用---修改
  async updateInsideOrderDetailByOrderNum2(obj, onlyCode) {
    console.log("商标自动提报专用#####################");
    var self = this;
    var channelorder = obj.channelorder;
    var user = obj.user;
    var app = obj.app;
    var nclones = obj.nclones;
    var tm = obj.tm || null;
    var apply = obj.apply || null;//或是copyright
    var copyright = obj.copyright || null;
    var customer = obj.customer || null;
    var copyrightType = Number(tm.reqtype || 0);//1软件著作权、2作品著作权、×××
    var order = {
      orderNum: tm.orderNum, applyName: apply.applyName || "", customerContact: customer.customerContact,
      customerMobile: customer.mobile, remark: apply.remark || ""
    };
    var o = await this.dao.findOne({ orderNum: order.orderNum });
    if (!o) {
      return { code: "-100", msg: "未查到相应订单，无法修改" };
    }
    if (!nclones || nclones == "undefined") {
      result.code = "-104";
      result.msg = "尼斯信息不能为空";
      return result;
    }
    var remainder = channelorder.remainder;
    if (!remainder) {
      return { code: "-203", msg: "渠道订单产品数量有误" };
    } else if (nclones.length > Number(remainder)) {
      return { code: "-204", msg: "渠道订单产品数量不足" };
    }
    var tms = await self.trademarkDao.model.findAll({ where: { orderNum: order.orderNum }, raw: true });
    var tmE = tms[0];
    for (var i = 0; i < tms.length; i++) {
      var tradem = tms[i];
      //------sy
      if (tradem.tmStatus != "4" && tradem.tmStatus != "FILLEXCEPTION" && tradem.tmStatus != "READY" && tradem.tmStatus != "DOCFINISH" && tradem.tmStatus != "AWAITCHECK" && tradem.tmStatus != "WAITARTIFICIALEXAMINE" && tradem.tmStatus != "WAITCOMMIT") {
        return { code: "-400", msg: "存在状态为" + tradem.tmStatusName + "的商标，不能修改" };
      }
      // if (tradem.tmStatus != "NOTRECVED" && tradem.tmStatus != "FILLEXCEPTION" && tradem.tmStatus != "READY" && tradem.tmStatus != "DOCFINISH" && tradem.tmStatus != "AWAITCHECK" && tradem.tmStatus != "WAITARTIFICIALEXAMINE" && tradem.tmStatus != "WAITCOMMIT") {
      //   return { code: "-400", msg: "存在状态为" + tradem.tmStatusName + "的商标，不能修改" };
      // }
    }
    tm["channelUserId"] = obj.channelUserId || "";
    tm["channelOrderNum"] = obj.channelOrderNum || "";
    return this.db.transaction(async function (t) {
      //第三方传递过来的订单信息来确定商标渠道支付状态，1支付，2待支付
      if (channelorder.order_pay_state && channelorder.order_pay_state == "已付清") {
        tm["channelPayStatus"] = "yzf";
      }
      if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "ent") {
        tm["tmStatus"] = tm.channelPayStatus == "yzf" ? "WAITARTIFICIALEXAMINE" : "DOCFINISH";
        order["orderStatus"] = "32";
      } else if (tm.sealAuthorizeStuff && apply.businessLicensePic && apply.type == "person" && apply.identityCardPic) {
        tm["tmStatus"] = tm.channelPayStatus == "yzf" ? "WAITARTIFICIALEXAMINE" : "DOCFINISH";
        order["orderStatus"] = "32";
      } else {
        tm["tmStatus"] = "READY";
      }
      var busUserItem = await self.trademarkDao.model.findOne({ where: { orderNum: order.orderNum }, attributes: ["id", "partnerMobile"], raw: true });
      var busUserPartnerMobile = busUserItem && busUserItem.partnerMobile ? busUserItem.partnerMobile : apply.mobile;

      var orderResult = await self.dao.model.update(order, { where: { orderNum: order.orderNum }, transaction: t });
      var applyResult = await self.tmapplierinfoDao.model.update(apply, { where: { orderNum: apply.orderNum }, transaction: t });

      //商标订单联系人
      var customerResult = null;
      var customerObj = await self.tmcustomerinfoDao.model.findOne({ where: { orderNum: customer.orderNum }, raw: true });
      if (customerObj && customerObj.id) {
        customerResult = await self.tmcustomerinfoDao.model.update(customer, { where: { orderNum: customer.orderNum }, transaction: t });
      } else {
        customerResult = await self.tmcustomerinfoDao.create(customer, t);//商标联系人
      }
      var updateTmObj = {
        "applyName": apply.applyName,
        "tmFormType": tm.tmFormType,
        "tmStatus": tm.tmStatus || "READY",
        "colorizedPicUrl": tm.colorizedPicUrl,
        "tmName": tm.tmName,
        "picUrl": tm.picUrl,
        "sealAuthorizeStuff": tm.sealAuthorizeStuff || "",
        "descUrl": tm.descUrl || ""
      };
      for (var i = 0; i < tms.length; i++) {
        if (tms[i] && tms[i].id) {
          await self.trademarkDao.model.update(updateTmObj, { where: { id: tms[i].id }, transaction: t });
        }
      }
      return { code: "1", msg: "success" };
    })
  };

  //获取客户档案（根据公司名称，查询公司信息）
  async getCustomerInfoByCompanyName(obj) {
    var companyName = obj.companyName;
    if (!companyName) {
      return { code: -1, msg: "companyName参数错误" };
    } else {
      var customer = await this.tmapplierinfoDao.model.findOne({
        where: { applyName: companyName },
        attributes: ["id", "orderNum", "type", "applyAddr", "identityCard", "creditCode", "identityCardPic", "businessLicensePic"],
        raw: true
      });
      if (customer) {
        return { code: 1, data: customer };
      } else {
        return { code: -2, msg: "企业信息不存在" };
      }
    }
  }


  //--------------接收渠道订单数据---start-------------------------------------------------------------
  //商标自动提报(渠道)
  async createChannelOrder(obj) {
    var self = this;
    var result = { code: "1", msg: "success", order: null };
    var channelOrder = obj.channelOrder;
    var channelUser = obj.channelUser;
    var itemCode = obj.itemCode;
    var apply = obj.apply;
    var tm = obj.tm;
    var nclones = obj.nclones;
    var user = obj.user;
    var app = obj.app;
    var channel = await self.channelDao.model.findOne({ where: { channelCode: obj.channelCode, isPubed: 1 }, raw: true });//渠道信息
    if (!channel) {
      result.code = "-110";
      result.msg = "渠道错误";
      return result;
    }
    var serviceItem = await self.servicesitemDao.findOne({ code: obj.itemCode, channelCode: obj.channelCode });//服务项信息
    if (!serviceItem) {
      result.code = "-120";
      result.msg = "渠道产品不存在";
      return result;
    }
    var orderbefore = await this.dao.model.findOne({
      where: { app_id: app.id, channelOrderNum: obj.deliveryOrderNo },
      raw: true
    });
    if (orderbefore && orderbefore.id) {
      result.code = "-121";
      result.msg = "渠道订单已存在";
      return result;
    }
    return this.db.transaction(async function (t) {
      var u = await self.getCreateOrderNum();//====================订单号生成
      //创建订单对象 orderType:"1",itemCode:"sbzc",
      var orderObj = {
        applyName: apply.name || "",
        remark: apply.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: apply.contacts, customerMobile: apply.mobile,
        itemOrderNum: nclones.length, itemOrderConsumeNum: nclones.length,
        itemType: serviceItem.itemType,
        itemCode: itemCode,
        orderType: "32",//渠道下单
        orderSourceType: "4",//订单来源类型
        channelCode: obj.channelCode,///////////////////////////////////////////
        channelName: channel.channelName,
        itemName: serviceItem.name, channelOrderNum: obj.deliveryOrderNo, channelUserId: channelUser.channelUserId,
        totalPublicExpense: 0, totalInvoiceTaxes: 0, orderStatus: "4",
        totalServiceCharge: 0, totalSum: 0, orderSourceType: "1", isSubProduct: 1,
        itemTypeTwoType: 0//和是否提报产品结合使用：服务项目类型的二级类型0没有、1软件著作权、2作品著作权
      };
      tm["channelUserId"] = channelUser.channelUserId || "";
      tm["channelOrderNum"] = obj.deliveryOrderNo || "";
      tm["needId"] = channelOrder.needNo || "";
      tm["channelOrderListInfo"] = channelOrder.channelOrderNo || "";
      tm["channelPayStatus"] = channelOrder.payStatus == "yfk" ? "yzf" : "wzf";
      orderObj["orderStatus"] = channelOrder.payStatus == "yfk" ? "4" : "1";
      if (apply.gzwtsUrl && apply.businessLicensePic && apply.customerType == "ent") {
        orderObj.orderStatus = "32";
        tm["tmStatus"] = channelOrder.payStatus == "yfk" ? "WAITARTIFICIALEXAMINE" : "DOCFINISH";
      } else if (apply.gzwtsUrl && apply.businessLicensePic && apply.customerType == "person" && apply.identityCardPic) {
        orderObj.orderStatus = "32";
        tm["tmStatus"] = channelOrder.payStatus == "yfk" ? "WAITARTIFICIALEXAMINE" : "DOCFINISH";
      }
      if (channel && channel.channelCode) {
        var judgeRes = self.trademarkDao.judgeChannelCode(channel.channelCode);//判断渠道码
        if (judgeRes) {
          tm["tmSourceType"] = judgeRes;
        }
      }
      return self.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.orderflowDao.create(orderflowObj, t);//订单流程
        //项目类型:ip:商标,ic:版权,pa:专利,iso:海外业务,common:增值服务,icbc:工商注册,zscq:知识产权,cwfw:财务服务,hyzz:行业资质,gqzr:股权转让,xzsp:行政审批
        //商标数据
        await self.createChannelOrderToAddTradeMark(self, user, app, tm, nclones, apply, order, t);
        result.order = order;
        return result;
      })
    })

  };
  //添加商标数据
  async createChannelOrderToAddTradeMark(self, user, app, tm, nclones, apply, order, t) {
    var customerObj = {
      zipCode: apply.zipCode || "", order_id: order.id, orderNum: order.orderNum,
      customerContact: apply.contacts, mobile: apply.mobile, email: apply.email,
      channelOrderNum: order.channelOrderNum
    };
    var customer = await self.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.tmapplierinfoDao.create(applierObj, t);//商标申请人信息
    for (var i = 0; i < nclones.length; i++) {
      var nclone = nclones[i];
      // nclone = JSON.parse(nclone);
      var nclthreeobj = nclone.nclThree;
      nclthreeobj = JSON.stringify(nclthreeobj);
      var key = await self.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,
        "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.trademarkDao.create(tmobj, t);
    }
  }
  //修改商标订单-商标信息修改 -- 
  async updateChannelTmInfo(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.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.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];
      //------sy
      // "4": "不予受理"
      // "FILLEXCEPTION": "填报异常"
      // "READY": "资料准备"
      // "DOCFINISH": "资料齐全"
      // "AWAITCHECK": "等待审核"
      // "WAITARTIFICIALEXAMINE": "等待人工审核"
      // "WAITCOMMIT": "待提交"
      // "ALIPAYREFUND": "已失败退款(阿里)"
      // "ALIAUDITNOT": "阿里云审不通过(修改可以重新推送阿里)"
      // "ALICUSTOMERREJECTED": "客户反馈(待修改重新同步)"
      // "SUBALITM": "已提交阿里(待补全信息)"
      // "REQALIERROR": "阿里接口错误(需峰擎系统处理)"
      // "SUBALITMOK": "已补全信息(待确认商标)",
      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.db.transaction(async function (t) {
      var otpObj = {
        id: orderItem.id
      };
      if (obj.notes) {//商标说明
        otpObj["remark"] = obj.notes;
        await self.dao.update(otpObj, t);//商标定单 修改商标说明
      }
      var tmObj = {
        channelOrderNum: deliveryOrderNo
      };
      if (obj.picUrl) {//商标图样 黑白
        tmObj["picUrl"] = obj.picUrl;
      }
      if (obj.colorizedPicUrl) {//彩色商标图样
        tmObj["colorizedPicUrl"] = obj.colorizedPicUrl;
      }
      if (obj.tmName) {//商标名称
        tmObj["tmName"] = obj.tmName;
      }
      if (obj.tmFormType) {//商标类型
        tmObj["tmFormType"] = obj.tmFormType.toString();
      }
      var applier2 = await self.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) {
            if (tm.channelPayStatus == "yzf") {
              tmStatus = "WAITARTIFICIALEXAMINE";
            } else {//订单未付款 跳出循环 
              tmStatus = "DOCFINISH";
              break;
            }
          } else {//资料不齐全 跳出循环 
            tmStatus = "READY";
            break;
          }
        }
      }
      if (tmStatus) {
        tmObj["tmStatus"] = tmStatus;
      }
      await self.trademarkDao.model.update(tmObj, { where: { channelOrderNum: tmObj.channelOrderNum, app_id: app.id }, transaction: t });
      return { code: 1 };
    })
  }
  //商标订单-商标尼斯信息 -- 
  async updateChannelNclInfo(obj) {
    var user = obj.user;
    var app = obj.app;
    var self = this;
    if (!user || !user.id) {
      return system.getResultFail(-100, "未知用户");
    }
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.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: -103, msg: "非本人订单，无法修改" };
    }
    var tbCode = obj.tbCode;
    if (!tbCode) {
      return system.getResultFail(-104, "tbCode参数错误");
    }
    //获取商标尼斯信息
    var tm = await self.trademarkDao.model.findOne({ where: { channelOrderNum: deliveryOrderNo, proxyCode: tbCode, app_id: app.id }, raw: true });
    if (!tm || !tm.id) {
      return system.getResultFail(-105, "商标信息不存在");
    }
    if (["WAITCONFIRM", "CONFIRMFAIL", "4", "FILLEXCEPTION", "READY", "DOCFINISH", "AWAITCHECK", "WAITARTIFICIALEXAMINE", "WAITCOMMIT", "ALIPAYREFUND", "ALIAUDITNOT", "ALICUSTOMERREJECTED", "SUBALITM", "REQALIERROR", "SUBALITMOK"].indexOf(tm.tmStatus) < 0) {
      return { code: -110, msg: "存在状态为" + tm.tmStatusName + "的商标，不能修改" };
    }
    //获取交付单下其它商标尼斯信息
    var othertm = await this.trademarkDao.model.findAll({
      where: {
        channelOrderNum: deliveryOrderNo,
        app_id: app.id,
        proxyCode: { [self.db.Op.ne]: tbCode }
      },
      raw: true
    });
    if (!obj.nclOneCodes) {
      return system.getResultFail(-106, "nclOneCodes参数错误");
    }
    if (!obj.nclSmallCodes || obj.nclSmallCodes.length < 1) {
      return system.getResultFail(-107, "nclSmallCodes参数错误");
    }
    if (obj.nclSmallCodes.length > 10) {
      return system.getResultFail(-108, "尼斯小类不能超过10项");
    }
    var nclOneCodes2 = obj.nclOneCodes;
    for (var i = 0; i < othertm.length; i++) {//判断重复大类
      var other = othertm[i];
      if (other.nclOneCodes == obj.nclOneCodes) {
        return system.getResultFail(-109, "该商标存在重复的尼斯大类");
      } else {
        nclOneCodes2 = nclOneCodes2 + "," + other.nclOneCodes;
      }
    }
    return await self.db.transaction(async function (t) {
      var tmObj = {
        id: tm.id,
        nclOneCodes: obj.nclOneCodes,
        nclSmallCodes: JSON.stringify(obj.nclSmallCodes)
      };
      var applier2 = await self.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) {
          if (tm.channelPayStatus == "yzf") {
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
          } else {
            tmObj["tmStatus"] = "DOCFINISH";
          }
        }
      }
      await self.trademarkDao.update(tmObj, t);//修改商标尼斯信息
      return { code: 1 };
    })
  }
  //修改商标订单-修改商标交付单联系人 --
  async updateChannelContacts(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.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.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.db.transaction(async function (t) {
      var contactsObj = {};
      var orderObj = { id: orderItem.id };
      if (obj.name) {
        contactsObj["customerContact"] = obj.name;
        orderObj["customerContact"] = obj.name;
      }
      if (obj.mobile) {
        contactsObj["mobile"] = obj.mobile;
        orderObj["customerMobile"] = obj.mobile;
      }
      if (obj.email) {
        contactsObj["email"] = obj.email;
      }
      if (obj.tel) {
        contactsObj["tel"] = obj.tel;
      }
      //修改联系人信息
      await self.tmcustomerinfoDao.model.update(contactsObj, { where: { orderNum: orderItem.orderNum }, transaction: t });
      await self.dao.update(orderObj, t);
      var applier2 = await self.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))) {
          if (tm.channelPayStatus == "yzf") {
            tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
          } else {
            tmObj["tmStatus"] = "DOCFINISH";
          }
        }
        await self.trademarkDao.update(tmObj, t);
      }
      return { code: 1 };
    })
  }
  //修改商标订单-修改申请人信息
  async updateChannelCustomerInfo(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.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.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 + "的商标，不能修改" };
      }
    }
    var applier = await self.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    if (!applier) {
      return { code: -105, msg: "未知申请人" };
    }
    return await self.db.transaction(async function (t) {
      var ciObj = {};
      var cusObj = {};
      var orderObj = { id: orderItem.id };
      if (obj.customerType) {
        ciObj["type"] = obj.customerType;
      }
      if (obj.name) {
        ciObj["applyName"] = obj.name;
        orderObj["applyName"] = obj.name;
        await self.dao.update(orderObj, t);
      }

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

      var applier2 = await self.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderItem.orderNum },
        raw: true
      });
      // var tms = await this.trademarkDao.model.findAll({
      //   where:{orderNum:orderItem.orderNum},
      //   raw:true
      // })
      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) {
            var tmObj = { id: tm.id };
            if (tm.channelPayStatus == "yzf") {
              tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
            } else {
              tmObj["tmStatus"] = "DOCFINISH";
            }
            await self.trademarkDao.update(tmObj, t);
          }
        }
      }
      return { code: 1 };
    })
  }
  //修改商标订单-修改交官文件
  async updateChannelOfficial(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.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.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 + "的商标，不能修改" };
      }
    }
    var applier = await self.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    if (!applier) {
      return { code: -105, msg: "未知申请人" };
    }
    return await self.db.transaction(async function (t) {
      var ciObj = {};
      var tmObj = {};
      if (obj.businessLicensePdf) {
        ciObj["businessLicensePic"] = obj.businessLicensePdf;
        ciObj["businessLicensePic2"] = obj.businessLicensePic;
      }
      if (obj.identityCardPdf) {
        ciObj["identityCardPic"] = obj.identityCardPdf;
        ciObj["identityCardPic2"] = obj.identityCardPic;
      }
      await self.tmapplierinfoDao.model.update(ciObj, { where: { orderNum: orderItem.orderNum }, transaction: t });//申请人信息 修改营业执照、身份证文件
      if (obj.gzwtsUrl) {
        tmObj["sealAuthorizeStuff"] = obj.gzwtsUrl;
      }
      if (obj.smwjUrl) {
        tmObj["descUrl"] = obj.smwjUrl;
      }
      await self.trademarkDao.model.update(tmObj, { where: { orderNum: orderItem.orderNum }, transaction: t });//商标交付单 修改盖章委托书、说明文件
      var applier2 = await self.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderItem.orderNum },
        raw: true
      });
      // var tms = await this.trademarkDao.model.findAll({
      //   where:{orderNum:orderItem.orderNum},
      //   raw:true
      // })
      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) {
            var tmObj = { id: tm.id };
            if (tm.channelPayStatus == "yzf") {
              tmObj["tmStatus"] = "WAITARTIFICIALEXAMINE";
            } else {
              tmObj["tmStatus"] = "DOCFINISH";
            }
            await self.trademarkDao.update(tmObj, t);
          }
        }
      }
      return { code: 1 };
    })
  }
  //修改商标订单-修改支付状态
  async updateChannelPayStatus(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    var payStatus = obj.payStatus;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    if (!payStatus) {
      return system.getResultFail(-100, "支付状态不能为空");
    }
    // 1.获取交付单信息
    var orderItem = await this.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.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 + "的商标，不能修改" };
      }
    }
    var applier = await self.tmapplierinfoDao.model.findOne({
      where: { orderNum: orderItem.orderNum },
      raw: true
    });
    if (!applier) {
      return { code: -105, msg: "未知申请人" };
    }
    return await self.db.transaction(async function (t) {
      var ciObj = {};
      var tmObj = {};
      ciObj["orderStatus"] = payStatus == "yfk" ? "4" : "1";
      tmObj["channelPayStatus"] = payStatus == "yfk" ? "yzf" : "wzf";
      await self.dao.model.update(ciObj, { where: { id: orderItem.id }, transaction: t });
      await self.trademarkDao.model.update(tmObj, { where: { orderNum: orderItem.orderNum }, transaction: t });
      return { code: 1 };
    })
  }
  //渠道商标方案确认
  async channelTmConfirm(obj) {
    var self = this;
    var user = obj.user;
    var app = obj.app;
    var deliveryOrderNo = obj.deliveryOrderNo;
    if (!deliveryOrderNo) {
      return system.getResultFail(-101, "deliveryOrderNo参数错误");
    }
    var isConfirm = obj.isConfirm;
    if (!isConfirm) {
      return system.getResultFail(-103, "isConfirm参数错误");
    }
    // 1.获取交付单信息
    var orderItem = await this.dao.model.findOne({
      where: { channelOrderNum: deliveryOrderNo, channelCode: obj.channelCode },
      raw: true
    });
    if (!orderItem) {
      return { code: -102, msg: "系统中未查到相应订单，无法修改" };
    }
    var tms = await self.trademarkDao.model.findAll({ where: { channelOrderNum: deliveryOrderNo, 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.trademarkDao.model.update(tmObj, {
      where: { orderNum: orderItem.orderNum }
    });
    return { code: 1 };
  }
  //--------------接收渠道订单数据---end-------------------------------------------------------------

  //--------------推送渠道订单数据---start-------------------------------------------------------------
  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 pushChannelAssistTmData(orderNum, channelCode) {
    try {
      if (!channelCode) {
        return { code: -200, msg: "渠道参数错误" };
      }
      if (!orderNum) {
        return { code: -201, msg: "订单号参数错误" };
      }
      //获取订单信息
      var order = await this.dao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!order || !order.id) {
        return { code: -202, msg: "未知订单" };
      }
      //获取订单所属人信息
      var user = await this.userDao.model.findOne({
        where: { id: order.user_id },
        raw: true
      });
      if (!user || !user.id) {
        return { code: -206, msg: "未知用户" };
      }
      //获取商标信息
      var tms = await this.trademarkDao.model.findAll({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!tms || tms.length < 1) {
        return { code: -203, msg: "未知商标" };
      }
      //获取申请人信息
      var applier = await this.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!applier || !applier.id) {
        return { code: -204, msg: "未知申请人" };
      }
      //获取联系人信息
      var contacts = await this.tmcustomerinfoDao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!contacts || !contacts.id) {
        return { code: -205, msg: "未知联系人" };
      }
      var itemCode = order.itemCode;
      var channelOrder = {
        "channelServiceNo": "",
        "channelOrderNo": "",
        "needNo": "",
        // "salesCount": 0,
        // "nclCount": 0,
        "payStatus": "yfk",
        // "payTime": ""
        "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 = {
        "applyAddr": applier.applyAddr,
        "applyArea": applier.applyArea,
        "businessLicensePic": applier.businessLicensePic2,
        "businessLicensePdf": applier.businessLicensePic,
        "code": applier.creditCode,
        "contacts": contacts.customerContact,
        "customerType": applier.type,
        "email": contacts.email,
        "fax": contacts.fax,
        "identityCardNo": applier.identityCard,
        "identityCardPic": applier.identityCardPic2,
        "identityCardPdf": applier.identityCardPic,
        "mobile": contacts.mobile,
        "name": applier.applyName,
        "notes": order.remark,
        "gzwtsUrl": tm.sealAuthorizeStuff,
        "smwjUrl": tm.descUrl,
        "zipCode": contacts.zipCode
      };
      var tmObj = {
        "tmStatus": tm.tmStatus,
        "colorizedPicUrl": tm.colorizedPicUrl,
        "tmName": tm.tmName,
        "picUrl": tm.picUrl,
        "gzwtsUrl": tm.sealAuthorizeStuff,
        "tmFormType": tm.tmFormType,
        "totalPublicExpense": order.totalPublicExpense,
        "totalServiceCharge": order.totalServiceCharge,
        "totalSum": order.totalSum,
        "totalTaxes": order.totalInvoiceTaxes
      };
      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 };
          nclones.push(nclone);
        }
      }
      var reqObj = {
        "actionBody": {
          "itemCode": itemCode,
          "channelOrder": channelOrder,
          "apply": apply,
          "tm": tmObj,
          "nclones": nclones
        },
        "requrl": "action/receiveData/springBoard",
        "actionType": "assistRegTmData",
        "user": user,
        "actionProcess": channelCode,
      };
      var token = await this.getToken(channelCode);
      if (!token || token.status != 0) {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: "推送渠道辅助注册商标数据---获取token失败",
          op: "orderSve/pushChannelAssistTmData",
          content: JSON.stringify(token),
          result: JSON.stringify(token),
          clientIp: ""
        });
        return { code: -1 };
      }
      var channelApiUrl = this.channelApiUrl;
      if (channelCode) {
        channelApiUrl = settings.channelApiUrl(channelCode);
      }
      var reqUrl = channelApiUrl + "/action/receiveData/springBoard";
      var rc = system.getObject("util.execClient");
      var rtn = await rc.execPostTK(reqObj, reqUrl, token.data.token);
      if (rtn.status == 0) {
        // var relocation = JSON.parse(rtn.stdout);
        await this.oplogSve.createDb({
          logLevel: "info",
          optitle: "推送渠道辅助注册商标数据---成功",
          op: reqUrl,
          resultinfo: JSON.stringify(rtn),
          content: JSON.stringify(reqObj),
          clientIp: ""
        });
      } else {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: "推送渠道辅助注册商标数据---失败",
          op: reqUrl,
          resultinfo: JSON.stringify(rtn),
          content: JSON.stringify(reqObj),
          clientIp: ""
        });
        return { code: -2 };
      }
      return { code: 1 };
    } catch (e) {
      await this.oplogSve.createDb({
        logLevel: "error",
        optitle: "推送渠道辅助注册商标数据---异常",
        op: "orderSve/pushChannelAssistTmData",
        content: JSON.stringify(e.stack),
        clientIp: ""
      });
      return { code: -400, msg: "操作失败", err: e.stack };
    }

  }
  //推送渠道辅助注册商标修改数据
  async pushEditChannelAssistTmData(orderNum, channelCode) {
    try {
      if (!channelCode) {
        return { code: -200, msg: "渠道参数错误" };
      }
      if (!orderNum) {
        return { code: -201, msg: "订单号参数错误" };
      }
      //获取订单信息
      var order = await this.dao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!order || !order.id) {
        return { code: -202, msg: "未知订单" };
      }
      //获取订单所属人信息
      var user = await this.userDao.model.findOne({
        where: { id: order.user_id },
        raw: true
      });
      if (!user || !user.id) {
        return { code: -206, msg: "未知用户" };
      }
      //获取商标信息
      var tms = await this.trademarkDao.model.findAll({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!tms || tms.length < 1) {
        return { code: -203, msg: "未知商标" };
      }
      //获取申请人信息
      var applier = await this.tmapplierinfoDao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!applier || !applier.id) {
        return { code: -204, msg: "未知申请人" };
      }
      //获取联系人信息
      var contacts = await this.tmcustomerinfoDao.model.findOne({
        where: { orderNum: orderNum },
        raw: true
      });
      if (!contacts || !contacts.id) {
        return { code: -205, msg: "未知联系人" };
      }
      var itemCode = order.itemCode;
      var tm = tms[0];
      var applyObj = {
        code: applier.creditCode,
        name: applier.applyName,
        applyAddr: applier.applyAddr,//申请地址
        applyArea: applier.applyArea,//申请区域
        customerType: applier.type,//申请人类型 ent person
        businessLicensePic: applier.businessLicensePic2,  //营业执照图片
        businessLicensePdf: applier.businessLicensePic,  //营业执pdf
        zipCode: contacts.zipCode,//邮政编码
        identityCardNo: applier.identityCard,
        identityCardPic: applier.identityCardPic2,
        identityCardPdf: applier.identityCardPic,
      };
      var contactsObj = {
        name: contacts.customerContact,
        mobile: contacts.mobile,
        email: contacts.email,
        tel: contacts.tel,//座机
        fax: contacts.fax//传真
      };
      var tmsList = [];
      var nclOneCodes = "";
      for (var i = 0; i < tms.length; i++) {
        var btm = tms[i];
        var tmObj = {
          tbCode: btm.proxyCode,//提报号(自动生成)
          officialType: btm.tmStatus,//"dsccl": "待上传材料", "dsh": "待审核"
          nclOneCodes: btm.nclOneCodes,//尼斯大类
          nclSmallCodes: btm.nclSmallCodes,//尼斯小类
          nclCount: btm.nclCount,//尼斯数量
          nclPublicExpense: btm.nclPublicExpense
        };
        nclOneCodes = nclOneCodes + "," + btm.nclOneCodes;
        tmsList.push(tmObj);
      }
      var orderObj = {
        tmStatus: tm.tmStatus,
        tmName: tm.tmName,//商标名称
        tmFormType: tm.tmFormType,//商标类型形式："1": "立体", "3": "字", "4": "图", "5": "字图", "6": "颜色", "7": "彩色"
        nclOneCodes: nclOneCodes,//尼斯大类列表：格式以,隔开
        picUrl: tm.picUrl,//商标图样
        colorizedPicUrl: tm.colorizedPicUrl,//商标彩色图样
        gzwtsUrl: tm.sealAuthorizeStuff,//盖章委托书
        smwjUrl: tm.descUrl,//说明文件
        notes: order.remark || "", // 备注信息
        nclOneCount: tms.length,
        nclCount: tm.nclCount || 10,
      };
      var reqObj = {
        "actionBody": {
          "needId": tm.needId,
          "itemCode": itemCode,
          "apply": applyObj,
          "contacts": contactsObj,
          "tms": tmsList,
          "order": orderObj
        },
        "requrl": "action/receiveData/springBoard",
        "actionType": "assistEditTmData",
        "actionProcess": channelCode,
      };
      var token = await this.getToken(channelCode);
      if (!token || token.status != 0) {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: "推送渠道辅助注册商标数据---获取token失败",
          op: "orderSve/pushEditChannelAssistTmData",
          content: JSON.stringify(token),
          clientIp: ""
        });
        return { code: -1 };
      }
      var channelApiUrl = this.channelApiUrl;
      if (channelCode) {
        channelApiUrl = settings.channelApiUrl(channelCode);
      }
      var reqUrl = channelApiUrl + "/action/receiveData/springBoard";
      var rc = system.getObject("util.execClient");
      var rtn = await rc.execPostTK(reqObj, reqUrl, token.data.token);
      if (rtn.status == 0) {
        await this.oplogSve.createDb({
          logLevel: "info",
          optitle: "推送渠道辅助注册商标数据---成功",
          op: reqUrl,
          resultinfo: JSON.stringify(rtn),
          content: JSON.stringify(reqObj),
          clientIp: ""
        });
      } else {
        await this.oplogSve.createDb({
          logLevel: "error",
          optitle: "推送渠道辅助注册商标数据---失败",
          op: reqUrl,
          resultinfo: JSON.stringify(rtn),
          content: JSON.stringify(reqObj),
          clientIp: ""
        });
        return { code: -2 };
      }
      return { code: 1 };
    } catch (e) {
      await this.oplogSve.createDb({
        logLevel: "error",
        optitle: "推送渠道辅助注册商标数据---异常",
        op: "orderSve/pushEditChannelAssistTmData",
        content: JSON.stringify(e.stack),
        clientIp: ""
      });
      return { code: -400, msg: "操作失败", err: e.stack };
    }

  }
  //--------------推送渠道订单数据---end-------------------------------------------------------------
}
module.exports = OrderService;
// console.log(JSON.stringify(tmSourceTypeToChannelCode)+"-------------------------");
// console.log(JSON.stringify(channelCodeToTmSourceType)+"-------------------------");
// var task = new OrderService();
// var a=[{class_count:10,order_no:"100303766"}];
// var b=[
//   {"channelOrderListInfo":"100303766",
//       "code":"05",
//       "name":"医药",
//       "price":300,
//       "nclThree":[
//           {
//               "code":"050002",
//               "name":"乌头碱",
//               "fullname":"050002 乌头碱",
//               "pcode":"0501",
//               "disabled":false
//           },
//           {
//               "code":"050008",
//               "name":"医用酒精",
//               "fullname":"050008 医用酒精",
//               "pcode":"0501",
//               "disabled":false
//           },
//           {
//               "code":"050009",
//               "name":"药用乙醛",
//               "fullname":"050009 药用乙醛",
//               "pcode":"0501",
//               "disabled":false
//           }
//       ]
//   }
// ];
// task.checkChannelUsableOrder(a,b).then(d=>{
//   console.log("ddddddddddddddddddddddddddd:"+JSON.stringify(d));
//   console.log("ddddddddddddddddddddddddddd:"+typeof(d));
//   if(d){
//     console.log("eeeeeeeeeeeeeeeee"+d);
//   }
// })
// console.log("-----------------------------------------------------");
// console.log(settings.channelApiUrl("jd"));
