const system = require("../../system");
const ServiceBase = require("../sve.base")
const settings = require("../../../config/settings")
var moment = require('moment');
const logCtl = system.getObject("web.oplogCtl");
class OrderService extends ServiceBase {
  constructor() {
    super(ServiceBase.getDaoName(OrderService));
    this.utilstlbankSve = system.getObject("service.utilstlbankSve");
    this.utilszxbankSve = system.getObject("service.utilszxbankSve");
    this.serviceitemSve = system.getObject("service.serviceitemSve");
    this.orderflowSve = system.getObject("service.orderflowSve");
    this.customercontactsSve = system.getObject("service.customercontactsSve");
    this.customerinfoSve = system.getObject("service.customerinfoSve");
    this.icpcustomerinfoSve = system.getObject("service.icpcustomerinfoSve");
    this.tmstuffSve = system.getObject("service.tmstuffSve");
    this.trademarkSve = system.getObject("service.trademarkSve");
    this.tmofficialSve = system.getObject("service.tmofficialSve");
    this.companyDao = system.getObject("db.companyDao");
    this.receiptvoucherSve = system.getObject("service.receiptvoucherSve");

    this.expensevoucherDao = system.getObject("db.expensevoucherDao");//费用单
    this.moneyjourneyDao = system.getObject("db.moneyjourneyDao");//账单
    this.receiptvoucherDao = system.getObject("db.receiptvoucherDao");//收款单
    this.moneyaccountDao = system.getObject("db.moneyaccountDao");
    this.oplogDao = system.getObject("db.oplogDao");
    this.businesscompanyDao = system.getObject("db.businesscompanyDao");
    this.businessinfoDao = system.getObject("db.businessinfoDao");
    this.pushmsgWxop = system.getObject("wxop.pushmsgWxop");
    this.mailClient = system.getObject("util.mailClient");
    this.userDao = system.getObject("db.userDao");
  }
  //付款提醒(商标订单)
  async orderPaymentReminder() {
    try {
      var self = this;
      var enddate = new Date();
      var stdate = new Date(enddate.getTime() - 24 * 60 * 60 * 1000);
      var unpaidOrderList = await this.dao.model.findAll({
        where: { orderPayStatus: "dfk", sveItemType: "ip", created_at: { [this.db.Op.between]: [stdate, enddate] } },
        attributes: ["id", "company_id", "createuser_id", "created_at", "name"],
        include: [
          { model: this.db.models.company, as: "company", attributes: ["name", "domainname"] },
          { model: this.db.models.user, as: "createuser", attributes: ["userName", "nickName", "mobile", "email"] }
        ]
      });
      var notifiedUserOrderList = [];
      var notifiedUserList = [];
      for (var i = 0; i < unpaidOrderList.length; i++) {
        var unpaidOrder = unpaidOrderList[i];
        if (unpaidOrder) {
          var createuser = unpaidOrder.createuser;
          var company = unpaidOrder.company;
          if (createuser && company && company.name && company.domainname) {
            var index = notifiedUserList.indexOf(unpaidOrder.createuser_id);
            if (index < 0) {
              notifiedUserList.push(unpaidOrder.createuser_id);
              unpaidOrder["count"] = 1;
              notifiedUserOrderList.push(unpaidOrder);
            } else {
              if (notifiedUserOrderList[index]["count"]) {
                notifiedUserOrderList[index]["count"] = notifiedUserOrderList[index]["count"] + 1;
              } else {
                notifiedUserOrderList[index]["count"] = 1;
              }
            }
          }
        }
      }
      console.log(notifiedUserOrderList);
      for (var j = 0; j < notifiedUserOrderList.length; j++) {
        var notifiedUserOrder = notifiedUserOrderList[j];
        if (notifiedUserOrder && notifiedUserOrder.name) {
          var createuser = notifiedUserOrder.createuser;
          var company = notifiedUserOrder.company;
          if (createuser && company && company.name && company.domainname) {
            if (createuser.email) {
              var text = null;
              if (notifiedUserOrder.count && notifiedUserOrder.count > 1) {
                text = " 【知圈圈】尊敬的用户，您的商标：" + notifiedUserOrder.name + "等" + notifiedUserOrder.count + "个订单尚未付款，如需要快速申报商标局，请及时处理，详情请查看官网。『" + company.domainname + "』" + company.name;
              } else {
                text = " 【知圈圈】尊敬的用户，您的商标：" + notifiedUserOrder.name + "订单尚未付款，如需要快速申报商标局，请及时处理，详情请查看官网。『" + company.domainname + "』" + company.name;

              }
              if (text) {
                await self.mailClient.sendMsg(createuser.email, "付款提醒", null, text, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom

              }
            }
            if (createuser.mobile && notifiedUserOrder.company_id) {
              var text = null;
              if (notifiedUserOrder.count && notifiedUserOrder.count > 1) {
                text = " 【知圈圈】尊敬的用户，您的商标：" + notifiedUserOrder.name + "等" + notifiedUserOrder.count + "个订单尚未付款，如需要快速申报商标局，请及时处理，详情请查看官网。『" + company.domainname + "』" + company.name;
              } else {
                text = " 【知圈圈】尊敬的用户，您的商标：" + notifiedUserOrder.name + "订单尚未付款，如需要快速申报商标局，请及时处理，详情请查看官网。『" + company.domainname + "』" + company.name;

              }
              if (text) {
                await self.pushmsgWxop.pushMsg({
                  company_id: notifiedUserOrder.company_id, mobile: createuser.mobile, title: text, itemName: "付款提醒", progress: "已完成"
                });
              }
            }
          }

        }
      }
      return { code: 1 };
    } catch (e) {
      return { code: -100, err: e.stack };
    }
  }
  //获取该公司本周、本月、总计的订单量和毛利===》订单量 (单)
  async fetchProAndOrderForBoss(companyid, user) {//订单数量（件数）展示---在使用
    var isRole = await this.isCheckRole(user, "boss");
    var weekresult = null;
    var monthresult = null;
    var totalresult = null;
    if (isRole) {
      weekresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE YEARWEEK(date_format(created_at,"%Y-%m-%d")) = YEARWEEK(now()) and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status',
        { replacements: { status: companyid }, type: this.db.QueryTypes.SELECT });
      monthresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE date_format(created_at,"%Y-%m")=date_format(now(),"%Y-%m")  and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status',
        { replacements: { status: companyid }, type: this.db.QueryTypes.SELECT });
      totalresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status',
        { replacements: { status: companyid }, type: this.db.QueryTypes.SELECT });
    } else {
      weekresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE YEARWEEK(date_format(created_at,"%Y-%m-%d")) = YEARWEEK(now()) and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:createuser_id',
        { replacements: { status: companyid, createuser_id: user.id }, type: this.db.QueryTypes.SELECT });
      monthresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE date_format(created_at,"%Y-%m")=date_format(now(),"%Y-%m")  and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:createuser_id',
        { replacements: { status: companyid, createuser_id: user.id }, type: this.db.QueryTypes.SELECT });
      totalresult = await this.db.query('SELECT sum(totalProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:createuser_id',
        { replacements: { status: companyid, createuser_id: user.id }, type: this.db.QueryTypes.SELECT });
    }

    var result = {
      profit: {
        week: weekresult[0].value,
        month: monthresult[0].value,
        total: totalresult[0].value
      },
      order: {
        week: weekresult[0].num,
        month: monthresult[0].num,
        total: totalresult[0].num
      }
    };
    return result;
  }

  //获取该公司近十二个月的订单和毛利数据   totalProfitSum=>channelProfitSum
  async fetchProfitAndOrder(companyid) {
    var result = await this.db.query(
      'SELECT date_format(created_at, "%Y-%m") as month, SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num ,sum(channelProfitSum) as value from `biz_order` where created_at>date_add(last_day(date_sub(curdate(), interval 1 year)), interval 1 day)  and orderPayStatus="yfk" and deleted_at is null and company_id=:status group by date_format(created_at, "%Y-%m")',
      { replacements: { status: companyid }, type: this.db.QueryTypes.SELECT });
    var d = new Date();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    var a = [];
    if (month == 12) {
      for (var i = 1; i <= 12; i++) {
        if (i < 10) {
          var b = year + "-0" + i;
        } else {
          var b = year + "-" + i;
        }
        a.push({ name: b, num: 0, value: 0 });
      }
    } else {
      var b = month;
      var c = year - 1;
      for (var i = 1; i <= 12; i++) {
        b = b + 1;
        if (b <= 12) {
          if (b < 10) {
            var d = c + "-0" + b;
          } else {
            var d = c + "-" + b;
          }
          a.push({ month: d, num: 0, value: 0 })
        }
        if (b == 12) {
          c = c + 1;
          b = 0
        };
      }
    }
    var p = { month: [], obj1: [], obj2: [] }
    for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < result.length; j++) {
        if (a[i].month == result[j].month) {
          a[i].num = result[j].num;
          a[i].value = result[j].value;
        }
      }
      p.month.push(a[i].month);
      p.obj1.push(Number(a[i].value));
      p.obj2.push(a[i].num);
    }

    return p;
  }

  //获取该公司不同类型产品的毛利和订单数量===》产品订单贡献度----在使用
  async fetchProAndOrderPie(companyid, user) {
    var isRole = await this.isCheckRole(user, "boss");
    var result = null;
    if (isRole) {
      result = await this.db.query(
        'SELECT sveItemType,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num ,sum(totalProfitSum) as value from `biz_order` where orderPayStatus="yfk" and deleted_at IS NULL and company_id=:status group by sveItemType',
        { replacements: { status: companyid }, type: this.db.QueryTypes.SELECT });
    } else {
      result = await this.db.query(
        'SELECT sveItemType,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num ,sum(totalProfitSum) as value from `biz_order` where orderPayStatus="yfk" and deleted_at IS NULL and company_id=:status and createuser_id=:createuser_id group by sveItemType',
        { replacements: { status: companyid, createuser_id: user.id }, type: this.db.QueryTypes.SELECT });
    }
    var productCata = {
      "ip": "商标", "ic": "版权", "pa": "专利", "iso": "海外业务", "common": "增值服务", "icbc": "工商注册",
      "zscq": "知识产权", "cwfw": "财务服务", "hyzz": "行业资质", "gqzr": "股权转让", "xzsp": "行政审批"
    };
    var params = { bottomData: [], obj1: [], obj2: [] };
    for (var i = 0; i < result.length; i++) {
      var code = result[i].sveItemType;
      var p1 = {
        name: productCata[code],
        value: result[i].value
      };
      var p2 = {
        name: productCata[code],
        value: result[i].num
      }
      params.bottomData.push(p1.name);
      params.obj1.push(p1); params.obj2.push(p2);
    }
    return params;
  }


  //获取该业务员本周、本月、总计的收款和毛利数据 // totalProfitSum=>channelProfitSum===》毛利 (元)
  async fetchForSalesman(companyid, user_id) {
    var weekresult = await this.db.query('SELECT sum(totalSum) as total,sum(channelProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE YEARWEEK(date_format(created_at,"%Y-%m-%d")) = YEARWEEK(now()) and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:userId',
      { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
    var monthresult = await this.db.query('SELECT sum(totalSum) as total, sum(channelProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE date_format(created_at,"%Y-%m")=date_format(now(),"%Y-%m")  and orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:userId',
      { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
    var totalresult = await this.db.query('SELECT sum(totalSum) as total,sum(channelProfitSum) as value ,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num FROM `biz_order` WHERE orderPayStatus="yfk" and deleted_at IS NULL and company_id =:status and createuser_id=:userId',
      { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
    var result = {
      profit: {
        week: weekresult[0].value,
        month: monthresult[0].value,
        total: totalresult[0].value
      },
      receiveMoney: {
        week: weekresult[0].total,
        month: monthresult[0].total,
        total: totalresult[0].total
      },
      order: {
        week: weekresult[0].num,
        month: monthresult[0].num,
        total: totalresult[0].num
      }
    };
    console.log(result);
    return result;
  }

  //获取该业务员近十二个月的订单数量、回款和毛利
  async fetchPicForSalesman(companyid, user_id) {
    var result = await this.db.query(
      'SELECT date_format(created_at, "%Y-%m") as month,SUM(CASE WHEN sveItemCode="zzsbzc" OR sveItemCode="dlrfzzc" THEN nclOneCodesNum ELSE salesNum END) as num, sum(totalSum) as total,sum(totalProfitSum) as profit from `biz_order` where created_at>date_add(last_day(date_sub(curdate(), interval 1 year)), interval 1 day)  and company_id=:status and createuser_id=:userId and orderPayStatus="yfk" and deleted_at IS NULL group by date_format(created_at, "%Y-%m")',
      { replacements: { status: companyid, userId: user_id }, type: this.db.QueryTypes.SELECT });
    console.log("----------fetchPicForSalesman------------");
    console.log(result);
    var d = new Date();
    var month = d.getMonth() + 1;
    var year = d.getFullYear();
    var a = [];
    if (month == 12) {
      for (var i = 1; i <= 12; i++) {
        if (i < 10) {
          var b = year + "-0" + i;
        } else {
          var b = year + "-" + i;
        }
        a.push({ name: b, profit: 0, total: 0, num: 0 });
      }
    } else {
      var b = month;
      var c = year - 1;
      for (var i = 1; i <= 12; i++) {
        b = b + 1;
        if (b <= 12) {
          if (b < 10) {
            var d = c + "-0" + b;
          } else {
            var d = c + "-" + b;
          }
          a.push({ month: d, profit: 0, total: 0, num: 0 })
        }
        if (b == 12) {
          c = c + 1;
          b = 0
        };
      }
    }
    var p = { month: [], obj1: [], obj2: [], obj3: [] }
    for (var i = 0; i < a.length; i++) {
      for (var j = 0; j < result.length; j++) {
        if (a[i].month == result[j].month) {
          a[i].profit = result[j].profit;
          a[i].total = result[j].total;
          a[i].num = result[j].num;
        }
      }
      p.month.push(a[i].month);
      p.obj1.push(Number(a[i].profit));
      p.obj2.push(Number(a[i].total));
      p.obj3.push(Number(a[i].num));
    }
    console.log(p);
    return p;

  }
  // async afteraudit(obj, tm) {

  //   //修改收款
  //   var moneyjourney = await this.moneyjourneyDao.findOne({ sourceOrderNo: obj.code });
  //   if (moneyjourney) {
  //     var pMoneyjourney = moneyjourney.get({ raw: true });
  //     await this.moneyjourneyDao.update({ id: pMoneyjourney.id, auditStatus: obj.auditStatus, notes: obj.notes }, tm);
  //   }
  //   //修改账单
  //   var receiptvoucher = await this.receiptvoucherDao.findOne({ sourceOrderNo: obj.code });
  //   if (receiptvoucher) {
  //     var pReceiptvoucher = receiptvoucher.get({ raw: true });
  //     await this.receiptvoucherDao.update({ id: pReceiptvoucher.id, auditStatus: obj.auditStatus, notes: obj.notes }, tm);
  //   }
  // }

  async findOneByCode(code) {//通过订单号获取订单，无attributes过滤字段
    return this.dao.findOneByCode(code);
  }
  async findItemByCode(code) {//通过订单号获取订单，有attributes过滤字段
    return this.dao.findItemByCode(code);
  }

  //------------------------------------------------订单利润结算-------------------------------------开始---------

  async orderSettlement(obj) {
    // { company_id: this.siteid, account_id: this.account_id, codelist: this.codelist }
    var orderList = await this.dao.model.findAll({
      where: { code: { [this.db.Op.in]: obj.codelist }, company_id: Number(obj.company_id), orderFlowStatus: "5", pfSettleProfit: 0 },
      attributes: ["id", "company_id", "createuser_id", "subType", "totalSum", "channelProfitSum", "code", "name", "sveItemCode", "sveItemName"]
    });
    if (!orderList || orderList.length == 0) {
      return { code: -100, msg: "暂无要结算的订单分润，操作的订单列表订单流程必须是完成状态且结算状态为未结算" }
    }
    if (obj.codelist.length != orderList.length) {
      return { code: -110, msg: "所操作的订单列表中订单流程还存在没有完成，操作的订单列表订单流程必须是完成状态且结算状态为未结算" }
    }
    var ptMoneyItem = self.moneyaccountDao.getOneItemByCompanyId(1);
    var channelMoneyItem = self.moneyaccountDao.getOneItemByCompanyId(Number(obj.account_id));
    if (!ptMoneyItem) {
      return { code: -111, msg: "平台转账资金账户为空，不能进行结算分润" }
    }
    if (!channelMoneyItem) {
      return { code: -112, msg: "所选择的银行账户不存在，不能进行结算分润" }
    }
    if (channelMoneyItem.company_id != Number(obj.company_id)) {
      return { code: -113, msg: "所选择的银行账户公司跟订单公司联匹配，不能进行结算分润" }
    }
    var remittanceList = [];//转账列表{payeeName,code,certificateNo,company_id,channelProfitSum}
    var expensevoucherList = [];//费用
    var receiptvoucherList = [];//收款
    var moneyjourneyList = [];//账单
    var opOrderNumList = [];
    var self = this;
    for (let index = 0; index < orderList.length; index++) {
      const element = orderList[index];
      if (element) {
        await self.assembleOpArray(self, remittanceList, expensevoucherList, receiptvoucherList, moneyjourneyList, opOrderNumList, element, ptMoneyItem, channelMoneyItem);
      }
    }
    await this.db.transaction(async function (t) {
      await self.moneyaccountDao.updateByWhere({ balance: ptMoneyItem.balance }, { where: { id: ptMoneyItem.id } }, t);
      await self.moneyaccountDao.updateByWhere({ balance: channelMoneyItem.balance }, { where: { id: channelMoneyItem.id } }, t);
      await self.execDbOp(self, expensevoucherList, receiptvoucherList, moneyjourneyList, opOrderNumList, t);
    });
    //TODO:remittanceList----转账????
    return { code: 1, msg: "ok" };
  }

  async assembleOpArray(self, remittanceList, expensevoucherList, receiptvoucherList, moneyjourneyList, opOrderNumList, element, ptMoneyItem, channelMoneyItem) {//组装操作数组数据
    var receiptvoucherItem = await self.receiptvoucherDao.model.findOne({
      where: { sourceOrderNo: element.code, sourceType: "order", payFlowType: 1 },
      attributes: ["id", "totalSum", "company_id", "createcompany_id"],
      raw: true
    });
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    if (!receiptvoucherItem) {//-----收款单信息为空
      //日志记录
      await self.oplogDao.create({
        company_id: element.company_id,
        user_id: element.createuser_id,
        sourceOrderNo: element.code,
        op: "/igirl-web/app/base/service/impl/orderSve.js/assembleOpArray",
        opTitle: nowTimeStr + "订单分润结算-->收款单信息为空",
        logLevel: "error",
        content: element.code + "的订单号对应的收款单信息为空，无法进行订单分润结算",
        opLogType: "orderSettlement",
        opLogStatus: "fail",
      });
      return;
    }
    if (receiptvoucherItem.createcompany_id) {//---------订单号对应收款单的公司资金帐户信息为空
      //日志记录
      await self.oplogDao.create({
        company_id: element.company_id,
        user_id: element.createuser_id,
        sourceOrderNo: element.code,
        op: "/igirl-web/app/base/service/impl/orderSve.js/assembleOpArray",
        opTitle: nowTimeStr + "订单分润结算-->订单号对应收款单的公司资金帐户信息为空",
        logLevel: "error",
        content: element.code + "的订单号对应收款单的公司资金帐户信息为空，无法进行订单分润结算",
        opLogType: "orderSettlement",
        opLogStatus: "fail",
      });
      return;
    }
    var isCheckMoney = 0;//验证余额是否够用
    //处理帐户
    var ptBalance = Number(ptMoneyItem.balance) - Number(element.channelProfitSum);
    if (tmpBalance < 0) {
      isCheckMoney = 1;
    } else {
      ptMoneyItem.balance = ptBalance;
      channelMoneyItem.balance = Number(channelMoneyItem.balance) + Number(element.channelProfitSum);
    }
    if (isCheckMoney > 0) {
      //日志记录
      await self.oplogDao.create({
        company_id: element.company_id,
        user_id: element.createuser_id,
        sourceOrderNo: element.code,
        op: "/service/impl/utilscloudSve.js/assembleOpArray",
        opTitle: nowTimeStr + "订单分润结算组装错误，对应的帐户余额不足=>error",
        logLevel: "info",
        content: "帐户余额：" + ptMoneyItem.balance + "，订单将要分润给渠道利润：" + element.channelProfitSum,
        opLogType: "orderSettlement",
        opLogStatus: "fail",
      });
      return;
    }
    await self.assembleOp(remittanceList, expensevoucherList, receiptvoucherList, moneyjourneyList, element, ptMoneyItem, channelMoneyItem);
    opOrderNumList.push(element.code);
  }

  async assembleOp(remittanceList, expensevoucherList, receiptvoucherList, moneyjourneyList, element, ptMoneyItem, channelMoneyItem) {
    var transferRate = 0;
    var amt = 0;
    if (Number(element.channelProfitSum) > 0) {
      transferRate = (Number(element.channelProfitSum) * Number(channelMoneyItem.transferRate || "0") / 1000);//转账手续费用
      amt = Number(element.channelProfitSum) - transferRate;//转账金额，单位元
      amt = amt.toFixed(2)
    }
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    var gfCode = await self.getBusUid("js");
    //platform......................................
    expensevoucherList.push({
      company_id: ptMoneyItem.company_id,
      createuser_id: element.createuser_id,
      code: gfCode,
      sourceType: "order",
      sourceOrderNo: element.code,
      expenseType: "channelSettleProfit",
      totalSum: element.channelProfitSum,
      auditStatus: "tg",
      notes: nowTimeStr + "：渠道分润结算",
      moneyaccount_id: ptMoneyItem.id
    });
    moneyjourneyList.push({
      company_id: ptMoneyItem.company_id,
      createuser_id: element.createuser_id,
      code: gfCode,
      accountType: "bank",
      directionType: "zc",//凭单类型,"sr": "收","zc": "支"
      voucherDate: new Date(),
      recvAmount: element.channelProfitSum,
      sourceType: "expensevoucher",
      sourceOrderNo: element.code,
      auditStatus: "tg",
      notes: nowTimeStr + "：渠道分润结算",
      moneyaccount_id: ptMoneyItem.id,
      createcompany_id: ptMoneyItem.company_id
    });
    //channel.......................................
    var channelCode = await self.getBusUid("fr");
    receiptvoucherList.push({
      company_id: channelMoneyItem.company_id,
      code: channelCode,
      createuser_id: element.createuser_id,
      auditStatus: "tg",
      sourceType: "order",
      sourceOrderNo: element.code,
      receiptType: "ptzz",
      accountType: "bank",
      payDate: new Date(),
      payFlowType: 1,
      totalSum: element.channelProfitSum,
      notes: nowTimeStr + "：平台分润结算",
      sveItemCode: element.sveItemCode,//项目操作码
      sveItemName: element.sveItemName,//项目名称
      moneyaccount_id: channelMoneyItem.id,
      createcompany_id: channelMoneyItem.company_id
    });
    moneyjourneyList.push({
      company_id: channelMoneyItem.company_id,
      createuser_id: element.createuser_id,
      code: channelCode,
      accountType: "bank",
      directionType: "zc",//凭单类型,"sr": "收","zc": "支"
      voucherDate: new Date(),
      recvAmount: element.channelProfitSum,
      sourceType: "receiptvoucher",
      sourceOrderNo: element.code,
      auditStatus: "tg",
      notes: nowTimeStr + "：平台分润结算",
      moneyaccount_id: channelMoneyItem.id,
      createcompany_id: channelMoneyItem.company_id
    });
    //手续费
    if (transferRate > 0) {
      var channelSxfCode = await self.getBusUid("sxf");
      expensevoucherList.push({
        company_id: channelMoneyItem.company_id,
        createuser_id: element.createuser_id,
        code: channelSxfCode,
        sourceType: "expensevoucher",
        sourceOrderNo: element.code,
        expenseType: "sxf",
        totalSum: transferRate,
        auditStatus: "tg",
        notes: nowTimeStr + "：平台分润结算转账服务费扣除",
        moneyaccount_id: channelMoneyItem.id
      });
      moneyjourneyList.push({
        company_id: channelMoneyItem.company_id,
        createuser_id: element.createuser_id,
        code: channelSxfCode,
        accountType: "bank",
        directionType: "zc",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        recvAmount: transferRate,
        sourceType: "receiptvoucher",
        sourceOrderNo: element.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：平台分润结算转账服务费扣除",
        moneyaccount_id: channelMoneyItem.id,
        createcompany_id: channelMoneyItem.company_id
      });
    }
    if (amt > 0) {
      remittanceList.push({
        payeeName: channelMoneyItem.payeeName,
        code: channelMoneyItem.code,
        certificateNo: channelMoneyItem.certificateNo,
        company_id: channelMoneyItem.company_id,
        channelProfitSum: amt,
        orderNo: element.code,
        user_id: element.createuser_id
      });
    }
  }

  async execDbOp(self, expensevoucherList, receiptvoucherList, moneyjourneyList, opOrderNumList, t) {
    if (expensevoucherList.length > 0) {
      await self.expensevoucherDao.bulkCreate(expensevoucherList, t);
    }
    if (receiptvoucherList.length > 0) {
      await self.receiptvoucherDao.bulkCreate(receiptvoucherList, t);
    }
    if (moneyjourneyList.length > 0) {
      await self.moneyjourneyDao.bulkCreate(moneyjourneyList, t);
    }
    if (opOrderNumList.length > 0) {
      await self.updateByWhere({ pfSettleProfit: 1 }, { where: { code: { [self.dao.db.Op.in]: opOrderNumList }, pfSettleProfit: 0 } }, t);
    }
  }

  //------------------------------------------------订单利润结算-------------------------------------结束---------

  //------------------------------------------------创建订单或修改订单-------------------------------------开始---------

  async isOrderVerify(user, verifyType, tm, serviceitem, nclones, buyProductCount) {  //订单验证
    // console.log(user, "user.............................");

    /*
      verifyType==1为商标注册验证，2为其他订单验证
    */
    var sveItemRateConfig = serviceitem.rateConfig ? Number(serviceitem.rateConfig) : 0;//产品费率
    var fwf = serviceitem.serviceCharge ? Number(serviceitem.serviceCharge) : 0;//服务费
    var yhfl = serviceitem.discountsRateConfig ? Number(serviceitem.discountsRateConfig) : 0;//最大优惠费率
    var gf = serviceitem.publicExpense ? Number(serviceitem.publicExpense) : 0;//产品官费
    var nclSmallPrice = gf / 10;//单个小类官费
    nclSmallPrice = Number(nclSmallPrice.toFixed(2));
    var productCount = tm.salesNum || 1;//产品数量
    var gfze = 0;//官费总额
    if (verifyType == 1) {
      productCount = nclones.length;
      for (var a = 0; a < nclones.length; a++) {
        var tmcode = await this.getBusUid("tm");
        var nclone = nclones[a];
        var nclthreeobj = nclone.nclThree;
        gfze = gfze + gf;
        if (nclthreeobj.length > 10) {
          gfze = gfze + (nclthreeobj.length - 10) * nclSmallPrice;
        }
      }
    }
    else if (verifyType == 2) {
      productCount = buyProductCount;
      gfze = gf * Number(productCount);
      if (Number(tm.totalSum) < Number(serviceitem.price)) {
        return { code: -210, msg: "订单金额有误" };
      }
      return "";
    }
    var fwfze = Number(fwf) * Number(productCount);//服务费总额
    var sfze = Number(tm.totalSum) / (sveItemRateConfig + 100) * sveItemRateConfig; //totalTaxes 税费总额
    sfze = sfze.toFixed(2);
    sfze = Number(sfze);
    var zdyhe = (gfze + fwfze) * yhfl / 100;//最大优惠额
    zdyhe = zdyhe.toFixed(2);
    zdyhe = Number(zdyhe);
    //毛利总额=应付总额-官费总额
    var mlze = Number(tm.totalSum) - gfze;//totalProfitSum 毛利总额
    mlze = mlze.toFixed(2);
    mlze = Number(mlze);
    //优惠金额=服务费+官费总额-应付总额(服务费、官费之和小于等于应付总额时，优惠金额为零)
    var yhje = fwfze + gfze - Number(tm.totalSum);
    if (yhje < 0) {
      yhje = 0;
    }
    yhje = yhje.toFixed(2);
    yhje = Number(yhje);
    if (fwfze != Number(tm.totalServiceCharge)) {
      return { code: -201, msg: "服务费总额有误" };
    }
    if (gfze != Number(tm.totalPublicExpense)) {
      return { code: -202, msg: "官费总额有误" };
    }
    if (sfze != Number(tm.totalTaxes)) {
      return { code: -203, msg: "税费总额有误" };
    }
    if (mlze != Number(tm.totalProfitSum)) {
      return { code: -204, msg: "毛利总额有误" };
    }
    if (yhje != Number(tm.totalDiscounts) || yhje > zdyhe) {
      return { code: -205, msg: "优惠总额有误" };
    }
    // user.company.companyType---公司类型
    var channelProfitSum = 0;//订单渠道分成毛利润总额
    var pfProfitSum = 0;//订单平台毛利润总额
    var totalProfitSum = Number(tm.totalProfitSum);//订单毛利润总额
    if (totalProfitSum > 0) {
      var tmpChannelProfitRate = Number(serviceitem.channelProfitRate);
      if (tmpChannelProfitRate > 0) {
        var channelProfitRate = tmpChannelProfitRate / 100;
        channelProfitSum = totalProfitSum * channelProfitRate;
        pfProfitSum = totalProfitSum - channelProfitSum;
        channelProfitSum = channelProfitSum.toFixed(2);
        pfProfitSum = pfProfitSum.toFixed(2);
        if (channelProfitSum < 0 || pfProfitSum < 0) {
          return { code: -206, msg: "利润计算有误" };
        }
        tm["channelProfitSum"] = channelProfitSum;
        tm["pfProfitSum"] = pfProfitSum;
      } else if (tmpChannelProfitRate == 0) {
        pfProfitSum = mlze;//毛利总额
      }
    }//渠道利润分成比率(只分订单中毛利润总额的分成)
    return "";
  }

  async createOtherOrder(obj) {//创建其他订单（除带提报信息的订单）
    var itemCode = obj.itemCode;//产品编码
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    var user = obj.user;
    var orderSource = obj.orderSource || "gsay";
    var tm_company_type = obj.tm_company_type || "";
    var sourceOrderNo = obj.sourceOrderNo || "";
    var orderAppendinfo = obj.order_appendinfo || "";//订单附加信息
    if (!itemCode) {
      return { code: -101, msg: 'itemCode参数错误' };
    }
    var serviceitem = await this.serviceitemSve.findOneByCode(itemCode, user.company_id);//获取产品
    if (!serviceitem) {
      return { code: -102, msg: '未知的产品' };
    }
    var verifyResult = await self.isOrderVerify(user, 2, tm, serviceitem, null, 1);
    if (verifyResult) {
      return verifyResult;
    }
    //获取公司信息
    var companyItem = await this.companyDao.model.findOne({
      where: { id: user.company_id },
      attributes: ["id", "companyType"],
      raw: true
    });
    if (!companyItem) {
      return { code: -103, msg: '未知的公司信息' };
    }
    return this.db.transaction(async function (t) {
      var ordercode = await self.getBusUid("pro");
      var orderObj = {
        orderSource: orderSource,
        company_id: user.company_id,
        createuser_id: user.id,
        name: tm.name || "",//商标名称
        code: ordercode,
        busPayOrderCode: ordercode,//业务支付订单号
        wxPayOrderCode: ordercode,//业务微信支付订单号
        aliPayOrderCode: ordercode,//业务支付宝支付订单号
        orderType: apply.orderType || "dkxd",//订单类型，"zzdd": "自主订单","dkxd": "代客下单"
        salesNum: tm.salesNum || 1,//项目订单数量（即服务项目的倍数，默认值为1）
        salesDiliverNum: 0,//项目订单交付数量（即与项目订单数量相对应）
        orderPayStatus: "dfk",//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
        orderFlowStatus: "1",//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
        orderStatus: "1",//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
        totalServiceCharge: tm.totalServiceCharge || 0,//服务费总额
        totalPublicExpense: tm.totalPublicExpense || 0,//官费总额
        totalDiscounts: tm.totalDiscounts || 0,//优惠总额
        totalTaxes: tm.totalTaxes || 0,//税费总额（订单总额*产品费率%）
        totalSum: tm.totalSum || 0,//订单总额（服务费+官费+(税费总额-优惠总额)）
        totalProfitSum: tm.totalProfitSum || 0,//订单利润总额（订单总额-官费总额-(税费总额-优惠总额)）
        pfProfitSum: tm.pfProfitSum || 0,//订单平台毛利润总额
        channelProfitSum: tm.channelProfitSum || 0,//订单渠道分成毛利润总额
        nclOneCodesNum: 0,//大类件数
        sveItemType: serviceitem.itemType,//服务项目类型
        sveItemRateConfig: serviceitem.rateConfig || 0,//产品费率
        sveDiscountsRateConfig: tm.discountsRateConfig || 0,//优惠税率
        sveItemCode: itemCode,//项目操作码
        sveItemName: serviceitem.name,//项目名称
        mobilePic: serviceitem.mobilePic,//移动端产品图片
        productonetype_id: serviceitem.producttype_pid_id,//产品大类Id
        producttype_id: serviceitem.producttype_id,//产品小类Id
        serviceItemSnapshot: JSON.stringify(serviceitem),//产品快照
        orderAppendinfo: orderAppendinfo ? JSON.stringify(orderAppendinfo) : "",//订单附加信息
        contacts: apply.contacts || "",//联系人
        mobile: apply.mobile || "",//手机号
        email: apply.email || "",//邮箱
        // tel: apply.tel,//座机
        // fax: apply.fax,//传真
        // zipCode: apply.zipCode,//邮政编码
        notes: apply.notes || "", //备注
        sourceOrderNo: sourceOrderNo,//订单的来源单号
        subType: companyItem.companyType == "self" ? "self" : "platform",
      };
      var order = await self.dao.create(orderObj, t);//创建订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: order.code,
        opContent: "创建订单"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      if (serviceitem.itemType == "ip" && tm.name && tm.tmApplyNum) {//商标注册
        await self.opOtherTmInfo(self, user, tm, serviceitem, order, t);
        if (orderSource == "ptsj" && tm_company_type) {
          await self.opOtherOrderTmBusInfo(self, user, tm, tm_company_type, order, t);
        }//商标的商机处理
      }

      return { code: 1, msg: "success", data: order };

    })
  }

  async updateOtherOrder(obj) { //修改其他订单（除带提报信息的订单）
    var itemCode = obj.itemCode;//产品编码
    var orderNum = obj.orderNum;//订单编号
    var user = obj.user;
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    if (!itemCode) {
      return { code: -101, mag: 'itemCode参数错误' };
    }
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    //orderPayStatus订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //orderFlowStatus订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    //orderStatus订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if ((["dfk", "yfk"].indexOf(orderitem.orderPayStatus) < 0) ||
      (["1", "2"].indexOf(orderitem.orderFlowStatus) < 0) ||
      (["1", "2", "3", "4", "6"].indexOf(orderitem.orderStatus) < 0)) {
      return { code: -104, msg: "目前的订单的状态，不能进行修改" };
    }
    if (user.id != orderitem.createuser_id || user.company_id != orderitem.company_id) {
      return { code: -105, msg: "要修改的订单信息有误" };
    }
    if (!orderitem.serviceItemSnapshot) {
      return { code: -106, mag: '未知的产品' };
    }
    var serviceitem = JSON.parse(orderitem.serviceItemSnapshot);//获取产品
    var verifyResult = await self.isOrderVerify(user, 2, tm, serviceitem, null, 1);
    if (verifyResult) {
      return verifyResult;
    }
    if (Number(orderitem.totalPublicExpense) != Number(tm.totalPublicExpense)) {
      return { code: -220, msg: "官费总额与原有订单不符" };
    }
    return this.db.transaction(async function (t) {
      // var ordercode = await self.getBusUid("tmo");
      var orderObj = {
        id: orderitem.id,
        // company_id: user.company_id,
        // createuser_id: user.id,
        updateuser_id: user.id,
        name: tm.name,//商标名称
        // code: ordercode,
        // orderType: apply.orderType || "dkxd",//订单类型，"zzdd": "自主订单","dkxd": "代客下单"
        // salesNum: 1,//项目订单数量（即服务项目的倍数，默认值为1）
        // salesDiliverNum: nclones.length,//项目订单交付数量（即与项目订单数量相对应）
        // orderPayStatus: "dfk",//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
        // orderFlowStatus: "1",//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"


        // orderStatus: "3",//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
        totalServiceCharge: tm.totalServiceCharge,//服务费总额
        totalPublicExpense: tm.totalPublicExpense,//官费总额
        totalDiscounts: tm.totalDiscounts,//优惠总额
        totalTaxes: tm.totalTaxes,//税费总额（订单总额*产品费率%）
        totalSum: tm.totalSum,//订单总额（服务费+官费+(税费总额-优惠总额)）
        totalProfitSum: tm.totalProfitSum,//订单利润总额（订单总额-官费总额-(税费总额-优惠总额)）
        pfProfitSum: tm.pfProfitSum,//订单平台毛利润总额
        channelProfitSum: tm.channelProfitSum,//订单渠道分成毛利润总额
        // nclOneCodesNum: nclones.length,//大类件数


        // sveItemType: "ip",//服务项目类型
        // sveItemRateConfig: tm.sveItemRateConfig || 0,//产品费率
        // sveDiscountsRateConfig: tm.totalDiscountsRate || 0,
        // sveItemCode: serviceitem.id,//项目操作码
        // sveItemName: serviceitem.name,//项目名称
        // mobilePic: serviceitem.mobilePic,//移动端产品图片
        // producttype_id: serviceitem.producttype_id,//产品小类Id
        // serviceItemSnapshot: serviceitem.toString(),//产品快照
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
        // tel: apply.tel,//座机
        // fax: apply.fax,//传真
        // zipCode: apply.zipCode,//邮政编码
        notes: apply.notes //备注
      };
      var order = await self.dao.update(orderObj, t);//修改订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "修改订单信息"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      if (serviceitem.itemType == "ip" && tm.name && tm.tmApplyNum) {//商标注册
        //删除商标信息
        await self.trademarkSve.dao.bulkDeleteByWhere({ where: { sourceOrderNo: orderitem.code } }, t);
        await self.opOtherTmInfo(self, user, tm, serviceitem, orderitem, t);
      }


      return { code: 1, msg: "success", data: orderitem };
    })

  }
  async updatePtsjOrder(obj) { //修改平台商机订单
    var orderNum = obj.orderNum;//订单编号
    var user = obj.user;
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    // if (!itemCode) {
    //   return { code: -101, mag: 'itemCode参数错误' };
    // }
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    //orderPayStatus订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //orderFlowStatus订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    //orderStatus订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if (orderitem.orderPayStatus != "dfk") {
      return { code: -104, msg: "目前的订单的状态，不能进行修改" };
    }
    if (user.id != orderitem.createuser_id || user.company_id != orderitem.company_id) {
      return { code: -105, msg: "要修改的订单信息有误" };
    }
    if (!orderitem.serviceItemSnapshot) {
      return { code: -106, mag: '未知的产品' };
    }
    var serviceitem = JSON.parse(orderitem.serviceItemSnapshot);//获取产品
    var verifyResult = await self.isOrderVerify(user, 2, tm, serviceitem, null, 1);
    if (verifyResult) {
      return verifyResult;
    }
    // if (Number(orderitem.totalPublicExpense) != Number(tm.totalPublicExpense)) {
    //   return { code: -220, msg: "官费总额与原有订单不符" };
    // }
    return this.db.transaction(async function (t) {
      // var ordercode = await self.getBusUid("tmo");
      var orderObj = {
        id: orderitem.id,
        updateuser_id: user.id,
        totalServiceCharge: tm.totalServiceCharge,//服务费总额
        totalPublicExpense: tm.totalPublicExpense,//官费总额
        totalDiscounts: tm.totalDiscounts,//优惠总额
        totalTaxes: tm.totalTaxes,//税费总额（订单总额*产品费率%）
        totalSum: tm.totalSum,//订单总额（服务费+官费+(税费总额-优惠总额)）
        totalProfitSum: tm.totalProfitSum,//订单利润总额（订单总额-官费总额-(税费总额-优惠总额)）
        pfProfitSum: tm.pfProfitSum,//订单平台毛利润总额
        channelProfitSum: tm.channelProfitSum,//订单渠道分成毛利润总额
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
      };

      var order = await self.dao.update(orderObj, t);//修改订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "修改订单信息"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      if (serviceitem.itemType == "ip" && tm.name && tm.tmApplyNum) {//商标注册
        //删除商标信息
        await self.trademarkSve.dao.bulkDeleteByWhere({ where: { sourceOrderNo: orderitem.code } }, t);
        await self.opOtherTmInfo(self, user, tm, serviceitem, orderitem, t);
      }
      return { code: 1, msg: "success", data: orderitem };
    })

  }
  async deletePtsjOrder(obj) { //删除平台商机订单
    var orderNum = obj.orderNum;//订单编号
    if (!orderNum) {
      return { code: -102, mag: '订单编号参数错误' };
    }
    var user = obj.user;
    var self = this;
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    var businessinfo = await this.businessinfoDao.model.findOne({ where: { sourceOrderCode: orderNum }, raw: true });//获取商机信息
    if (!businessinfo) {
      return { code: -106, mag: '未知的商机' };
    }
    if (!businessinfo.sourceCode) {
      return { code: -107, mag: '未知的客户' };
    }
    var businesscompany = await this.businesscompanyDao.model.findOne({ where: { code: businessinfo.sourceCode }, raw: true });//获取商机客户信息
    if (!businesscompany) {
      return { code: -108, mag: '未知的客户' };
    }
    //orderPayStatus订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //orderFlowStatus订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    //orderStatus订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if (orderitem.orderPayStatus != "dfk") {
      return { code: -104, msg: "该订单支付状态为" + orderitem.orderPayStatusName + ",不能删除" };
    }
    if (user.id != orderitem.createuser_id || user.company_id != orderitem.company_id) {
      return { code: -105, msg: "不能删除非本人订单" };
    }

    return this.db.transaction(async function (t) {
      var order = await self.dao.delete({ id: orderitem.id }, t);//删除订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "删除平台商机订单"
      };
      var bi = await self.businessinfoDao.update({ id: businessinfo.id, dispose_status: "wxd", sourceOrderCode: "" }, t);//商机信息改为未下单并清除来源订单号
      var order_num = Number(businesscompany.order_num || 0);
      if (order_num >= 1) {
        order_num = order_num - 1;
      } else {
        order_num = 0;
      }
      var bc = await self.businesscompanyDao.update({ id: businesscompany.id, order_num: order_num }, t);//修改商机客户下单数量
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      return { code: 1, msg: "success" };
    })

  }
  async createTmOrder(obj) { //创建商标订单
    var itemCode = obj.itemCode;//产品编码
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    var user = obj.user;
    var nclones = obj.nclones || null;
    if (!nclones || nclones.length < 1) {
      return { code: -100, mag: "尼斯大类不能为空" };
    }
    if (!itemCode) {
      return { code: -101, mag: 'itemCode参数错误' };
    }
    var serviceitem = await this.serviceitemSve.findOneByCode(itemCode, user.company_id);//获取产品
    if (!serviceitem) {
      return { code: -102, mag: '未知的产品' };
    }
    var verifyResult = await self.isOrderVerify(user, 1, tm, serviceitem, nclones, null);
    if (verifyResult) {
      return verifyResult;
    }
    //获取公司信息
    var companyItem = await this.companyDao.model.findOne({
      where: { id: user.company_id },
      attributes: ["id", "companyType"],
      raw: true
    });
    if (!companyItem) {
      return { code: -103, mag: '未知的公司信息' };
    }
    // if(!tm.name && tm.tmFormType=="4"){//图形商标
    //   tm["name"]="图形";
    // }
    if (tm.tmFormType == "4") {//图形商标
      tm["name"] = "图形";
    }
    return this.db.transaction(async function (t) {
      var ordercode = await self.getBusUid("tmo");
      var orderObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        name: tm.name,//商标名称
        code: ordercode,
        busPayOrderCode: ordercode,//业务支付订单号
        wxPayOrderCode: ordercode,//业务微信支付订单号
        aliPayOrderCode: ordercode,//业务支付宝支付订单号
        orderType: apply.orderType || "dkxd",//订单类型，"zzdd": "自主订单","dkxd": "代客下单"
        salesNum: nclones.length,//项目订单数量（即服务项目的倍数，默认值为1）
        // salesDiliverNum: nclones.length,//项目订单交付数量（即与项目订单数量相对应）
        salesDiliverNum: 0,//项目订单交付数量（即与项目订单数量相对应）
        orderPayStatus: "dfk",//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
        orderFlowStatus: "1",//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
        orderStatus: "1",//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
        totalServiceCharge: tm.totalServiceCharge,//服务费总额
        totalPublicExpense: tm.totalPublicExpense,//官费总额
        totalDiscounts: tm.totalDiscounts,//优惠总额
        totalTaxes: tm.totalTaxes,//税费总额
        totalSum: tm.totalSum,//订单总额（含税）
        totalProfitSum: tm.totalProfitSum,//订单毛利润总额（含税:订单总额-官费总额）
        pfProfitSum: tm.pfProfitSum,//订单平台毛利润总额
        channelProfitSum: tm.channelProfitSum,//订单渠道分成毛利润总额
        nclOneCodesNum: nclones.length,//大类件数
        sveItemType: "ip",//服务项目类型
        sveItemRateConfig: serviceitem.rateConfig || 0,//产品费率
        sveDiscountsRateConfig: tm.discountsRateConfig || 0,//优惠税率
        sveItemCode: itemCode,//项目操作码
        sveItemName: serviceitem.name,//项目名称
        mobilePic: serviceitem.mobilePic,//移动端产品图片
        productonetype_id: serviceitem.producttype_pid_id,//产品大类Id
        producttype_id: serviceitem.producttype_id,//产品小类Id
        serviceItemSnapshot: JSON.stringify(serviceitem),//产品快照
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
        tel: apply.tel,//座机
        fax: apply.fax,//传真
        zipCode: apply.zipCode,//邮政编码
        notes: apply.notes, //备注
        subType: companyItem.companyType == "self" ? "self" : "platform",
      };
      if (apply.customerType == "person") {
        if (!apply.businessLicensePic || !apply.identityCardPic || !apply.sealAuthorizeStuff) {
          orderObj["orderStatus"] = "2";
        } else {
          orderObj["orderStatus"] = "3";
        }
      }
      if (apply.customerType == "ent") {
        if (!apply.businessLicensePic || !apply.sealAuthorizeStuff) {
          orderObj["orderStatus"] = "2";
        } else {
          orderObj["orderStatus"] = "3";
        }
      }
      //订单客户档案添加和修改
      await self.opCustomerInfo(self, user, t, apply, null, orderObj);
      var order = await self.dao.create(orderObj, t);//创建订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: order.code,
        opContent: "创建订单"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      await self.opTmInfo(self, user, tm, apply, nclones, order, t);
      // var msgObj={
      //   company_id: 4,mobile:"13075556693",title:"公众号进度信息推送",itemName:"商标注册",progress:"已完成"
      // };
      // self.pushmsgWxop.pushMsg(msgObj);
      return { code: 1, msg: "success", data: order };

    })

  }

  async updateTmOrder(obj) { //修改商标订单
    var itemCode = obj.itemCode;//产品编码
    var orderNum = obj.orderNum;//订单编号
    var user = obj.user;
    var self = this;
    var tm = obj.tm;
    var apply = obj.apply;
    var nclones = obj.nclones || null;
    if (!nclones || nclones.length < 1) {
      return { code: -100, mag: "尼斯大类不能为空" };
    }
    if (!itemCode) {
      return { code: -101, mag: 'itemCode参数错误' };
    }
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    //orderPayStatus订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //orderFlowStatus订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    //orderStatus订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if ((["dfk", "yfk", "zfpz", "pzshwtg"].indexOf(orderitem.orderPayStatus) < 0) ||
      (["1", "2"].indexOf(orderitem.orderFlowStatus) < 0) ||
      (["1", "2", "3", "4", "6"].indexOf(orderitem.orderStatus) < 0)) {
      return { code: -104, msg: "目前的订单的状态，不能进行修改" };
    }
    // if (user.mobile && user.mobile == orderitem.mobile) {
    //   //客户修改自己订单
    // } else {
    //   if (user.id != orderitem.createuser_id || user.company_id != orderitem.company_id) {
    //     return { code: -105, msg: "要修改的订单信息有误" };
    //   }
    // }
    if (!orderitem.serviceItemSnapshot) {
      return { code: -106, mag: '订单产品未知' };
    }
    // if(Number(tm.totalPublicExpense)>Number(orderitem.totalPublicExpense)){
    //   return { code: -107, mag: '官费已超过历史金额' };
    // }
    var serviceitem = JSON.parse(orderitem.serviceItemSnapshot);//获取快照产品
    var verifyResult = await self.isOrderVerify(user, 1, tm, serviceitem, nclones, null);
    if (verifyResult) {
      return verifyResult;
    }
    // if(!tm.name && tm.tmFormType=="4"){//图形商标
    //   tm["name"]="图形";
    // }
    if (tm.tmFormType == "4") {//图形商标
      tm["name"] = "图形";
    }
    if (orderitem.orderPayStatus != "dfk") {
      if (Number(orderitem.totalPublicExpense) < Number(tm.totalPublicExpense)) {
        return { code: -220, msg: "官费总额与原有订单不符" };
      }
    }
    return this.db.transaction(async function (t) {
      // var ordercode = await self.getBusUid("tmo");
      var orderObj = {
        id: orderitem.id,
        // company_id: user.company_id,
        // createuser_id: user.id,
        updateuser_id: user.id,
        name: tm.name,//商标名称
        // code: ordercode,
        // orderType: apply.orderType || "dkxd",//订单类型，"zzdd": "自主订单","dkxd": "代客下单"
        salesNum: nclones.length,//项目订单数量（即服务项目的倍数，默认值为1）
        // salesDiliverNum: nclones.length,//项目订单交付数量（即与项目订单数量相对应）
        // orderPayStatus: "dfk",//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
        // orderFlowStatus: "1",//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
        // orderStatus: "1",//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"


        totalServiceCharge: tm.totalServiceCharge,//服务费总额
        totalPublicExpense: tm.totalPublicExpense,//官费总额
        totalDiscounts: tm.totalDiscounts,//优惠总额
        totalTaxes: tm.totalTaxes,//税费总额
        totalSum: tm.totalSum,//订单总额
        totalProfitSum: tm.totalProfitSum,//订单利润总额
        pfProfitSum: tm.pfProfitSum,//订单平台毛利润总额
        channelProfitSum: tm.channelProfitSum,//订单渠道分成毛利润总额
        nclOneCodesNum: nclones.length,//大类件数

        // sveItemType: "ip",//服务项目类型
        // sveItemRateConfig: tm.sveItemRateConfig || 0,//产品费率
        // sveDiscountsRateConfig: tm.totalDiscountsRate || 0,
        // sveItemCode: serviceitem.id,//项目操作码
        // sveItemName: serviceitem.name,//项目名称
        // mobilePic: serviceitem.mobilePic,//移动端产品图片
        // producttype_id: serviceitem.producttype_id,//产品小类Id
        // serviceItemSnapshot: serviceitem.toString(),//产品快照
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
        tel: apply.tel,//座机
        fax: apply.fax,//传真
        zipCode: apply.zipCode,//邮政编码
        notes: apply.notes //备注
      };
      //订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
      //营业执照图片、身份证图片、盖章委托书
      if (apply.customerType == "person") {
        if (!apply.businessLicensePic || !apply.identityCardPic || !apply.sealAuthorizeStuff) {
          orderObj.orderStatus = "2";
        } else {
          orderObj.orderStatus = "3";
        }
      }
      if (apply.customerType == "ent") {
        if (!apply.businessLicensePic || !apply.sealAuthorizeStuff) {
          orderObj.orderStatus = "2";
        } else {
          orderObj.orderStatus = "3";
        }
      }
      //订单客户档案添加和修改
      await self.opCustomerInfo(self, user, t, apply, orderitem, orderObj);
      await self.dao.update(orderObj, t);//修改订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "修改订单信息"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      //删除商标信息、附件
      await self.tmstuffSve.dao.bulkDeleteByWhere({ where: { code: orderitem.code } }, t);

      // if(orderitem.orderStatus=="6"){//部分递交异常

      // }else{
      //   await self.trademarkSve.dao.bulkDeleteByWhere({ where: { sourceOrderNo: orderitem.code } }, t);
      //   await self.opTmInfo(self, user, tm, apply, nclones, orderitem, t);
      // }

      await self.opTmInfo(self, user, tm, apply, nclones, orderitem, t);


      return { code: 1, msg: "success", data: orderitem };
    });

  }

  async opTmInfo(self, user, tm, apply, nclones, order, t, ) {//商标（商标注册）添加操作
    //获取产品快照
    var serviceitem = order.serviceItemSnapshot;
    if (serviceitem) {
      serviceitem = JSON.parse(serviceitem);
    }
    var gf = serviceitem.publicExpense ? Number(serviceitem.publicExpense) : 0;//产品官费
    var nclSmallPrice = gf / 10;//单个小类官费
    nclSmallPrice = Number(nclSmallPrice.toFixed(2));
    if (tm.picUrl) {//商标图样
      var tmstuffObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        code: order.code,//来源单号
        name: tm.name,//附件名称
        stuffType: "ty",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
        stuffUrl: tm.picUrl,//附件地址
      };
      var tmstuff = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
    }
    if (tm.colorizedPicUrl) {//彩色图样
      var tmstuffObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        code: order.code,//来源单号
        name: tm.name,//附件名称
        stuffType: "csty",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
        stuffUrl: tm.colorizedPicUrl,//附件地址
      };
      var tmstuff2 = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
    }
    if (apply.sealAuthorizeStuff) {//盖章委托书
      var tmstuffObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        code: order.code,//来源单号
        name: tm.name,//附件名称
        stuffType: "gzwts",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
        stuffUrl: apply.sealAuthorizeStuff,//附件地址
      };
      var tmstuff3 = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
    }
    if (apply.descUrl) {//优先权证明文件
      var tmstuffObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        code: order.code,//来源单号
        name: tm.name,//附件名称
        stuffType: "smwj",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
        stuffUrl: apply.descUrl,//附件地址
      };
      var tmstuff4 = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
    }
    var tms = null;
    if (order.orderStatus == "6") {//部分递交异常
      //获取商标
      tms = await self.trademarkSve.dao.model.findAll({ where: { sourceOrderNo: order.code }, attributes: ["id", "code", "nclOneCodes"], raw: true });
    }
    // if (tms && tms.length > 0) {
    //   await self.trademarkSve.dao.bulkDeleteByWhere({ where: { sourceOrderNo: order.code } }, t);
    // }
    await self.trademarkSve.dao.bulkDeleteByWhere({ where: { sourceOrderNo: order.code } }, t);
    for (var i = 0; i < nclones.length; i++) {
      var tmcode = await self.getBusUid("tm");
      var nclone = nclones[i];
      var nclthreeobj = nclone.nclThree;
      //计算尼斯小类官方总额
      var nclgfze = 300;
      if (nclthreeobj.length > 10) {
        nclgfze = nclgfze + (nclthreeobj.length - 10) * nclSmallPrice;
      }
      nclthreeobj = JSON.stringify(nclthreeobj);
      if (tms && tms.length > 0) {//部分递交异常商标创建时 代理号要与之前相同
        for (var j = 0; j < tms.length; j++) {
          if (tms[j].code && tms[j].nclOneCodes && tms[j].nclOneCodes == nclone.code) {
            tmcode = tms[j].code;
          }
        }
      }
      var trademarkobj = {
        sourceOrderNo: order.code,//来源单号
        order_id: order.id,
        company_id: user.company_id,
        createuser_id: user.id,
        code: tmcode,//提报号(自动生成)
        name: tm.name,//商标名称
        tmType: "p",//"p": "普通商标", "j": "集体商标", "z": "证明商标", "t": "特殊商标"
        tmFormType: tm.tmFormType,//商标类型形式："1": "立体", "3": "字", "4": "图", "5": "字图", "6": "颜色", "7": "彩色"
        caseType: "sbzc",//案例类型:"sbzc": "商标注册", "sbbg": "商标变更", "sbbh": "商标驳回"
        nclOneCodes: nclone.code,//尼斯大类
        nclSmallCodes: nclthreeobj,//尼斯小类
        nclPublicExpense: nclgfze,
        producttype_id: order.producttype_id,
        // notes: "" // 备注信息
      };
      var trademark = await self.trademarkSve.dao.create(trademarkobj, t);//创建商标
    }
  }
  async opCustomerInfo(self, user, tm, apply, orderitem, orderObj) {//订单客户档案添加和修改
    var customerInfoObj = {
      company_id: user.company_id,
      code: apply.code,
      name: apply.name,
      applyAddr: apply.applyAddr,//申请地址
      applyArea: apply.applyArea,//申请区域
      customerType: apply.customerType,//申请人类型 ent person
      businessLicensePic: apply.businessLicensePic,  //营业执照图片
      owner_id: user.id
    };
    if (apply.customerType == "person") {
      customerInfoObj["identityCardNo"] = apply.identityCardNo;
      customerInfoObj["identityCardPic"] = apply.identityCardPic;
      //身份证号、身份证图片
      if (!apply.identityCardNo || !apply.identityCardPic) {
        orderObj.orderStatus = "2";
      }
      else {
        orderObj.orderStatus = "3";
      }
    }
    //订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if (orderitem && orderitem.orderPayStatus == "dfk" && orderObj.orderStatus == "3") {
      orderObj.orderStatus = "1";
    }//针对修改操作
    var customer = await self.customerinfoSve.findOneByCodeAndUserId(apply.code, user.id);//查询客户档案
    if (customer && customer.id) {//客户已存在 则更新
      customerInfoObj["id"] = customer.id;
      await self.customerinfoSve.update(customerInfoObj, tm);
    } else {//客户不存在 则创建
      customer = await self.customerinfoSve.dao.create(customerInfoObj, tm);
    }
    orderObj["customerinfo_id"] = customer.id;
    var customerContactObj = {
      company_id: user.company_id,
      customerinfo_id: customer.id,
      name: apply.contacts,//联系人
      mobile: apply.mobile,//手机号
      email: apply.email,//邮箱
      tel: apply.tel,//座机
      fax: apply.fax,//传真
      zipCode: apply.zipCode,//邮政编码
    };
    var customercontacts = await self.customercontactsSve.findOneByMobile(apply.mobile, customer.id);
    if (!customercontacts) {//客户联系人不存在 则创建
      customercontacts = await self.customercontactsSve.dao.create(customerContactObj, tm);//创建订单联系人
    }
  }
  async opOtherTmInfo(self, user, tm, serviceitem, order, t) {//其他商标（除商标注册的商标）添加操作
    var tmcode = await self.getBusUid("tmp");
    var trademarkobj = {
      sourceOrderNo: order.code,//来源单号
      order_id: order.id,
      company_id: user.company_id,
      createuser_id: user.id,
      code: tmcode,//提报号(自动生成)
      name: tm.name,//商标名称
      nclOneCodes: tm.nclOneCodes || "",//商标大类
      tmRegistNum: tm.tmApplyNum,//商标注册号
      producttype_id: serviceitem.producttype_id,//产品小类Id
      // notes: "" // 备注信息
    };
    var trademark = await self.trademarkSve.dao.create(trademarkobj, t);//创建商标
  }

  async opOtherOrderTmBusInfo(self, user, tm, tm_company_type, order, t) {//处理商机对应的商标信息
    // this.businesscompanyDao
    // this.businessinfoDao
    var sqlWhere = { tm_regist_num: tm.tmApplyNum, ncl_one_codes: tm.nclOneCodes, tm_company_type: tm_company_type, dispose_status: "wxd" };
    var busItem = await self.businessinfoDao.findOne(sqlWhere);
    if (!busItem) {
      throw new Error("没有该条商标信息或该条商标状态不是为下单");
    }
    if (!busItem.sourceCode) {
      throw new Error("没有该条商标对应的商机编号");
    }
    var companySqlWhere = { code: busItem.sourceCode };
    var busCompanyItem = await self.businesscompanyDao.findOne(companySqlWhere);
    if (!busCompanyItem) {
      throw new Error("没有该条商标对应的商机信息");
    }
    var setParams = {
      createcompany_id: user.company_id,
      createuser_id: user.id,
      sourceOrderCode: order.code,
      dispose_status: "yxd"
    }
    await self.businessinfoDao.updateByWhere(setParams, { where: sqlWhere }, t);
    var recovery_time = moment(busCompanyItem.claim_time).add(1, "months");
    var companyBusOrderNum = Number(busCompanyItem.order_num || 0) + 1;
    await self.businesscompanyDao.updateByWhere({ order_num: companyBusOrderNum, recovery_time: recovery_time }, { where: { id: busCompanyItem.id } }, t);
  }

  //------------------------------------------------创建订单或修改订单-------------------------------------结束---------

  async getTmOrderDetail(orderNum) {//获取商标订单详情
    var order = await this.dao.findOne({ code: orderNum });
    var data = {};
    if (order && order.id) {
      data["order"] = order;
      var customerinfo = await this.customerinfoSve.dao.findOne({ id: order.customerinfo_id });//客户信息
      data["customerinfo"] = customerinfo;
      var tmstuffs = await this.tmstuffSve.dao.model.findAll({ where: { code: orderNum }, raw: true });
      data["tmstuffs"] = tmstuffs;
      var trademarks = await this.trademarkSve.dao.model.findAll({ where: { sourceOrderNo: order.code }, raw: true });
      if (trademarks && trademarks.length > 0) {
        for (var i = 0; i < trademarks.length; i++) {
          var tmofficials = await this.tmofficialSve.dao.model.findAll({ where: { trademark_id: trademarks[i].id }, raw: true });
          trademarks[i]["tmofficials"] = tmofficials;
        }
      }
      data["trademarks"] = trademarks;
      var orderflow = await this.orderflowSve.dao.model.findAll({ where: { sourceOrderNo: orderNum }, 'order': [['created_at', 'DESC']], raw: true })
      data["orderflow"] = orderflow;
      var company = await this.companyDao.model.findOne({ where: { id: order.company_id }, attributes: ["contact", "contactmobile", "fax", "zipCode"] });
      data["company"] = company;
      var receiptvoucher = await this.receiptvoucherDao.model.findOne({ where: { sourceOrderNo: order.code }, attributes: ["accountTypeName", "accountType", "payDate", "certifyFileUrl"], 'order': [['created_at', 'ASC']] });
      data["receiptvoucher"] = receiptvoucher;
      return { code: 1, data: data };
    } else {
      return { code: -100, msg: "订单数据为空" };
    }

  }

  async aiadive(obj) {//处理商标智能推荐
    var sql = "select req from biz_aiadive where search='" + obj.seltype[0] + " / " + obj.seltype[1] + "'";
    var tmpResult = await this.dao.customQuery(sql);
    var nclinfo = [];
    tmpResult.forEach(n => {
      nclinfo.push(n.req);
    })
    var info = "{'ncl':[" + nclinfo + "]}";
    var result = info.replace(/'/g, "\"");
    return result;

  }

  //------------------------------------------------------------------- 订单线下支付------------------------------------
  async offlinePay(obj) {
    var user = obj.user;
    var fileUrl = obj.fileUrl;
    var orderNum = obj.orderNum;
    var account_id = obj.account_id;
    if (!account_id) {
      return { code: -103, msg: "付款账户参数错误" };
    }
    if (!fileUrl) {
      return { code: -100, msg: "支付凭证不能为空" };
    }
    if (!orderNum) {
      return { code: -101, msg: "订单号不能为空" };
    }
    var order = await this.dao.model.findOne({
      where: { code: orderNum },
      attributes: ["id", "orderPayStatus", "company_id", "createuser_id", "totalSum", "sveItemCode", "sveItemName", "subType"], raw: true
    });
    if (!order) {
      return { code: -102, msg: "订单数据为空" };
    }
    if (order.orderPayStatus != "dfk") {
      return { code: -104, msg: "订单付款状态不是未付款" };
    }
    var that = this;
    return this.db.transaction(async function (t) {
      var orderObj = {
        code: orderNum,
        auditStatus: "dsh",
        orderPayStatus: "zfpz"
      }
      var skdcode = await that.getBusUid("XX");
      var opComanyId = order.subType == "platform" ? 1 : order.company_id;
      var receiptvoucherObj = {
        company_id: opComanyId,
        moneyaccount_id: account_id,
        createuser_id: order.createuser_id,
        receiptType: "sk",//收款类型，"sk": "收款","tk": "退款","zz": "转账" ,"csrz": "初始入账" ,"zz": "代收款","zz": "平台转账"
        accountType: "bank",//帐户类型:"cash": "现金", "bank": "银行" ,"wx":"微信","alipay":"支付宝","other":"其它"
        payDate: new Date(),//支付时间
        payFlowType: 1,//支付流类型,1为订单支付，2为补单
        totalSum: order.totalSum,//订单总额（平台费用+服务费+官费+发票税费+个人利润+平台利润）
        certifyFileUrl: fileUrl, //证明文件Url
        notes: "线下支付",//备注
        sourceType: "order",
        sourceOrderNo: orderNum,
        code: skdcode,
        sveItemCode: order.sveItemCode,//项目操作码
        sveItemName: order.sveItemName,//项目名称
        createcompany_id: order.company_id,
      };
      var receiptvoucher = await that.receiptvoucherDao.create(receiptvoucherObj, t);
      await that.receiptvoucherSve.aftercreate(receiptvoucher, t);
      orderObj["receiptvoucher_id"] = receiptvoucher.id;
      //修改订单付款状态
      var orderResult = await that.dao.model.update(orderObj, { where: { code: orderObj.code }, transaction: t });
      order.orderPayStatus = "zfpz";
      return { code: 1, data: order };
    });
  }
  //撤销审核 用于交付管理》材料审核页面
  async cancelAudit(obj) {
    var user = obj.user;
    var code = obj.code;
    if (!user) {
      return { code: -1, msg: "用户数据不存在" };
    }
    if (!code) {
      return { code: -2, msg: "code参数错误" };
    }
    var order = await this.dao.model.findOne({ where: { code: code }, raw: true });
    if (!order) {
      return { code: -3, msg: "订单不存在" };
    }
    if (order.orderStatus != '5') {
      return { code: -4, msg: "订单状态错误" };
    }
    if (order.orderFlowStatus != '3') {
      return { code: -5, msg: "订单流程状态错误" };
    }
    var that = this;
    return this.db.transaction(async function (t) {
      var obj = {
        orderStatus: "3", orderFlowStatus: "2", opNotes: "撤销审核", updator: user.nickName,
        updateuser_id: user.id, opContent: "订单交官材料撤销审核"
      };
      await that.dao.model.update(obj, { where: { code: code }, transaction: t });
      // var addParams = {
      //   sourceOrderNo: code,
      //   opContent: "订单交官材料撤销审核",
      //   company_id: user.company_id,
      //   createuser_id: user.id
      // }
      // await that.orderflowSve.create(addParams, t);
      return { code: 1 };
    })

  }
  //邮件通知
  async emailMsgSend(code, setOrderParams) {
    var self = this;
    var salesman = null;
    var customer = null;
    var order = await this.dao.model.findOne({
      where: { code: code },
      include: [
        { model: this.db.models.company, as: "company", attributes: ["name", "domainname"] }
      ],
      raw: true
    });
    if (order && order["company.name"]) {
      salesman = await this.userDao.model.findOne({ where: { id: order.createuser_id }, raw: true });
      if (order.mobile) {
        customer = await this.userDao.model.findOne({
          where: { [this.db.Op.or]: [{ mobile: order.mobile }, { userName: order.mobile }], company_id: order.company_id },
          raw: true
        });
      }
      if (order.sveItemType == "ip") {//商标
        //业务员通知
        if (salesman) {
          if (salesman.email) {//邮件通知 salesman.email
            if (setOrderParams.orderStatus == '4') {//订单交官材料审核不通过
              var text = "【知圈圈】尊敬的用户，您的商标【" + order.name + "】订单材料审核不通过，订单号:" + order.code + "，如需要快速申报商标局，请及时处理，详情请查看官网。";
              var html = text + '<a href="http://' + order["company.domainname"] + '">『' + order["company.domainname"] + '』' + order["company.name"] + '</a>'
              var result = self.mailClient.sendMsg(salesman.email, "商标业务通知", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
            }
            if (setOrderParams.orderStatus == '5') {//订单交官材料审核通过
              var text = "【知圈圈】尊敬的用户，您的商标【" + order.name + "】订单材料已经通过审核，订单号:" + order.code + "，详情请查看官网。";
              var html = text + '<a href="http://' + order["company.domainname"] + '">『' + order["company.domainname"] + '』' + order["company.name"] + '</a>'
              var result = self.mailClient.sendMsg(salesman.email, "商标业务通知", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
            }

          }
        }
        //客户通知
        if (order.email) {//邮件通知 salesman.email
          if (setOrderParams.orderStatus == '5') {//订单通过人工审核
            var text = "【知圈圈】尊敬的用户，您的商标申请订单信息已通过平台审核，进入官方申报队列，商标名称：【" + order.name + "】，订单号：" + order.code + "，详情请查看官网 。";
            var html = text + '<a href="http://' + order["company.domainname"] + '">『' + order["company.domainname"] + '』' + order["company.name"] + '</a>'
            var result = self.mailClient.sendMsg(order.email, "商标业务通知", null, html, null, null, []); //发送成功后result的值:250 Data Ok: queued as freedom
          }
        }
        // if (customer) {

        // }
      }
    }
  }
  //公众号通知
  async wxMsgSend(code, setOrderParams) {
    var self = this;
    var salesman = null;
    var customer = null;
    var order = await this.dao.model.findOne({
      where: { code: code },
      include: [
        { model: this.db.models.company, as: "company", attributes: ["name", "domainname"] }
      ],
      raw: true
    });
    if (order && order["company.name"]) {
      salesman = await this.userDao.model.findOne({ where: { id: order.createuser_id }, raw: true });
      if (order.mobile) {
        customer = await this.userDao.model.findOne({
          where: { [this.db.Op.or]: [{ mobile: order.mobile }, { userName: order.mobile }], company_id: order.company_id },
          raw: true
        });
      }
      if (order.sveItemType == "ip") {//商标
        //业务员通知
        if (salesman) {
          if (salesman.mobile) {//公众号通知
            if (setOrderParams.orderStatus == '4') {//订单交官材料审核不通过
              var title = "尊敬的用户，您的商标【" + order.name + "】订单材料审核不通过，订单号:" + order.code + "，如需要快速申报商标局，请及时处理，详情请查看官网。『" + order['company.domainname'] + "』" + order['company.name'];
              self.pushmsgWxop.pushMsg({
                company_id: salesman.company_id, mobile: salesman.mobile, title: title, itemName: order.sveItemName, progress: "订单交官材料审核不通过"
              });
            }
            if (setOrderParams.orderStatus == '5') {//订单交官材料审核通过
              var title = "尊敬的用户，您的商标【" + order.name + "】订单材料已经通过审核，订单号:" + order.code + "，详情请查看官网。『" + order['company.domainname'] + "』" + order['company.name'];
              self.pushmsgWxop.pushMsg({
                company_id: salesman.company_id, mobile: salesman.mobile, title: title, itemName: order.sveItemName, progress: "订单交官材料审核通过"
              });
            }
          }
        }
        //客户通知
        if (order.mobile) {//公众号通知
          if (setOrderParams.orderStatus == '5') {//订单通过人工审核
            var title = "尊敬的用户，您的商标申请订单信息已通过平台审核，进入官方申报队列，商标名称：" + order.name + "，订单号：" + order.code + "，详情请查看官网 。『" + order['company.domainname'] + "』" + order['company.name'];
            self.pushmsgWxop.pushMsg({
              company_id: order.company_id, mobile: order.mobile, title: title, itemName: order.sveItemName, progress: "订单通过人工审核"
            });
          }
        }
        // if (customer) {

        // }
      }
    }
  }
  async blukupdate(qobj) {
    var type = qobj.type;
    var value = qobj.value;
    var selectedRows = qobj.selectedRows;
    var self = this;
    var errorinfo = [];
    for (var i = 0; i < selectedRows.length; i++) {
      // var salesman = null;
      // var customer = null;
      // var order = await this.dao.model.findOne({where:{code:selectedRows[i].code},raw:true});
      // if(order){
      //   salesman = await this.userDao.model.findOne({where:{id:order.createuser_id},raw:true});
      //   if(order.mobile){
      //     customer = await this.userDao.model.findOne({
      //       where:{[this.db.Op.or]: [{ mobile: order.mobile }, { userName: order.mobile }],company_id:order.company_id },
      //       raw:true
      //     });
      //   }
      // }
      var setOrderParams = {
        updator: qobj.updator,
        updateuser_id: qobj.updateuser_id,
        opNotes: value
      };
      var opContent = "";
      if (type == 0) {
        setOrderParams["orderStatus"] = '4';
        opContent = "订单交官材料审核不通过，原因：" + value
      }
      if (type == 1) {
        setOrderParams["orderStatus"] = '5';
        setOrderParams["orderFlowStatus"] = '3';
        opContent = "订单交官材料审核通过"
      }
      try {
        await this.db.transaction(async function (t) {
          await self.updateByWhere(setOrderParams, { where: { code: selectedRows[i].code } }, t);
          var sqlWhere = {
            sourceOrderNo: selectedRows[i].code,
            opContent: opContent,
            company_id: qobj.company_id,
          }
          var flows = await self.orderflowSve.findOne(sqlWhere, t);
          if (!flows) {
            var addParams = {
              sourceOrderNo: selectedRows[i].code,
              opContent: opContent,
              company_id: qobj.company_id,
              createuser_id: qobj.updateuser_id
            }
            await self.orderflowSve.create(addParams, t);
          }
        })
        this.emailMsgSend(selectedRows[i].code, setOrderParams);
        this.wxMsgSend(selectedRows[i].code, setOrderParams);

      } catch (e) {
        errorinfo.push(sourceOrderNo);
      }
    }
    var status = 0;
    var msg = "审核成功"
    if (errorinfo.length > 0) {
      status = -1;
      msg = "审核失败，失败的数据为：" + JSON.stringify(errorinfo);
    }
    return { status: status, msg: msg, data: null }
  }

  async cancelOrderByCode(obj) {
    var code = obj.code;
    var user = obj.user;
    if (!code) {
      return { code: -101, msg: "code参数错误" };
    }
    var that = this;
    return this.db.transaction(async function (t) {
      var obj = {
        orderPayStatus: "ddqx"
      };
      var result = await that.dao.model.update(obj, { where: { code: code }, transaction: t });
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: code,
        opContent: "取消订单"
      };
      var orderflow = await that.orderflowSve.dao.create(flowObj, t);//创建订单流程
      return { code: 1, msg: "success", data: orderflow };
    })
  }
  //上传材料(订单列表页直接上传材料)
  async uploadStuffs(obj) {
    var user = obj.user;
    if (!obj.code) {
      return { code: -100, msg: "code参数错误" };
    }
    var order = await this.dao.model.findOne({ where: { code: obj.code }, raw: true });
    if (!order) {
      return { code: -103, msg: "订单不存在" };
    }
    if (order.orderStatus != "1" && order.orderStatus != "2" && order.orderStatus != "3" && order.orderStatus != "4" && order.orderStatus != "6") {
      return { code: -104, msg: "当前订单状态为" + order.orderStatusName + ",不能执行此操作" };
    }
    var customer = await this.customerinfoSve.dao.model.findOne({ where: { id: order.customerinfo_id }, raw: true });//查询客户档案 根据id查询
    if (!customer) {
      return { code: -105, msg: "订单客户信息不存在" };
    }
    var self = this;
    if (!(!obj.businessLicensePic && !obj.identityCardPic && !obj.sealAuthorizeStuff)) {
      return this.db.transaction(async function (t) {
        var orderObj = {};
        //判断订单状态
        if (customer.customerType == "person") {
          if (!obj.businessLicensePic || !obj.identityCardPic || !obj.sealAuthorizeStuff) {
            orderObj["orderStatus"] = "2";
          } else {
            orderObj["orderStatus"] = "3";
          }
        }
        if (customer.customerType == "ent") {
          if (!obj.businessLicensePic || !obj.sealAuthorizeStuff) {
            orderObj["orderStatus"] = "2";
          } else {
            orderObj["orderStatus"] = "3";
          }
        }
        if (orderObj && orderObj.orderStatus) {//修改订单状态
          await self.dao.model.update(orderObj, { where: { code: order.code }, transaction: t });
        }
        if (obj.sealAuthorizeStuff) {
          await self.tmstuffSve.dao.bulkDeleteByWhere({ where: { code: order.code, stuffType: "gzwts" } }, t);//删除旧盖章委托书材料
          var tmstuffObj = {
            company_id: user.company_id,
            code: order.code,//来源单号
            name: order.name,//附件名称
            stuffType: "gzwts",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
            stuffUrl: obj.sealAuthorizeStuff,//附件地址
          };
          var tmstuff = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
        }
        if (obj.descUrl) {
          await self.tmstuffSve.dao.bulkDeleteByWhere({ where: { code: order.code, stuffType: "smwj" } }, t);//删除旧盖章委托书材料
          var tmstuffObj = {
            company_id: user.company_id,
            code: order.code,//来源单号
            name: order.name,//附件名称
            stuffType: "smwj",//附件类型:"csty": "彩色图样", "wts": "委托书", "gzwts": "盖章委托书", "ty": "图样" , "sywj": "声音文件" , "smwj": "说明文件"
            stuffUrl: obj.descUrl,//附件地址
          };
          var tmstuff2 = await self.tmstuffSve.dao.create(tmstuffObj, t);//创建商标材料
        }
        if (customer.customerType == "ent" && customer.businessLicensePic != obj.businessLicensePic) {
          var customerInfoObj = {
            businessLicensePic: obj.businessLicensePic
          };
          await self.customerinfoSve.dao.model.update(customerInfoObj, { where: { id: customer.id }, transaction: t });//更新客户档案
        }
        if (customer.customerType == "person" && ((customer.businessLicensePic != obj.businessLicensePic) || (customer.identityCardPic != obj.identityCardPic))) {
          var customerInfoObj = {};
          if (!customer.businessLicensePic && obj.businessLicensePic) {
            customerInfoObj["businessLicensePic"] = obj.businessLicensePic;
          }
          if (!customer.identityCardPic && obj.identityCardPic) {
            customerInfoObj["identityCardPic"] = obj.identityCardPic;
          }
          await self.customerinfoSve.dao.model.update(customerInfoObj, { where: { id: customer.id }, transaction: t });//更新客户档案
        }

        return { code: 1 };
      })
    } else {
      return { code: -102, msg: "上传材料不能为空" };
    }

  }
  /**
   * 获取订单数据统计，按订单流程进行统计--(待付款，已付款，已完成)
   * @param {*} mobile 用户手机号
   * @param {*} createuser_id 用户ID
   * @param {*} company_id 公司ID
   * @param {*} productonetypeid_list 产品大类列表IDs
   */
  async getOrderInfo(mobile, createuser_id, company_id, productonetypeid_list) {
    var result = { code: 1, msg: "未下订单", data: { dfk: { flow_status: "1", count: 0 }, yfk: { flow_status: "2", count: 0 }, ywc: { flow_status: "5", count: 0 } } };
    //订单流程状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    var sql = "SELECT orderFlowStatus,COUNT(id) AS orderCount FROM biz_order";
    var params = {};
    if (mobile) {
      sql = sql + " WHERE deleted_at IS NULL and ( mobile=:mobile or (createuser_id=:createuser_id and company_id=:company_id ))"
      params.mobile = mobile;
      params.createuser_id = createuser_id;
      params.company_id = company_id;
    } else {
      sql = sql + " WHERE deleted_at IS NULL and createuser_id=:createuser_id and company_id=:company_id"
      params.createuser_id = createuser_id;
      params.company_id = company_id;
    }
    if (productonetypeid_list.length > 0) {
      sql = sql + " and productonetype_id IN (" + productonetypeid_list.join(",") + ")";
    }
    sql = sql + "  GROUP BY orderFlowStatus";
    var list = await this.dao.customQuery(sql, params);
    if (list && list.length > 0) {
      var clz = 0;
      for (let index = 0; index < list.length; index++) {
        const element = list[index];
        if (element) {
          if (Number(element.orderFlowStatus) == 1) {
            result.data.dfk.count = result.data.dfk.count + Number(element.orderCount);
          } else if (Number(element.orderFlowStatus) == 2 || Number(element.orderFlowStatus) == 3 || Number(element.orderFlowStatus) == 4) {
            result.data.yfk.count = result.data.yfk.count + Number(element.orderCount);
          } else if (Number(element.orderFlowStatus) == 5) {
            result.data.ywc.count = result.data.ywc.count + Number(element.orderCount);
          }
        }
      }
      result.msg = "ok";
    }
    return result;
  }

  /**
 * 获取订单数据统计，按订单流程进行统计--(待付款，已付款，已完成)
 * @param {*} page_index 当前页
 * @param {*} page_size 每页大小
 * @param {*} mobile 用户手机号
 * @param {*} createuser_id 用户ID
 * @param {*} company_id 公司ID
 * @param {*} productonetypeid_list 产品大类列表IDs
 * @param {*} flow_status 订单流程状态
 */
  async getOrderList(page_index, page_size, mobile, createuser_id, company_id, productonetypeid_list, flow_status) {
    var where = {};
    if (mobile) {
      where[this.db.Op.or] = [
        { [this.db.Op.and]: [{ createuser_id: createuser_id }, { company_id: company_id }] },
        { mobile: mobile }
      ];
    } else {
      where.createuser_id = createuser_id;
      where.company_id = company_id;
    }
    if (flow_status && Number(flow_status) > 0) {
      if (Number(flow_status) == 2) {
        where["orderFlowStatus"] = { [this.db.Op.in]: ["2", "3", "4"] };
      } else {
        where["orderFlowStatus"] = flow_status;
      }
    }
    where["productonetype_id"] = { [this.db.Op.in]: productonetypeid_list };
    var attributesObj = ["id", "code", "name", "sveItemName", "mobilePic", "totalPublicExpense", "totalServiceCharge", "totalTaxes", "salesNum", "orderFlowStatus", "totalSum"];
    var orderList = await this.dao.getPageList(page_index, page_size, where, [["updated_at", 'desc']], attributesObj);
    if (!orderList || orderList.rows.length == 0) {
      return { code: -210, message: "目前没有订单数据", data: [] };
    }
    return { code: 1, message: "ok", data: orderList.rows };
  }
  //---------------------------------------------------------------中信，通联----获取订单二维码开始------------------------------------
  async getQrCodeInfo(obj) {//获取中信支付二维码
    var orderNo = obj.code || "";
    var comanyId = obj.company_id;
    var opType = obj.op_type;
    if (!orderNo || !comanyId || !opType) {
      return { code: -100, msg: "参数信息有误" }
    }
    var qrCodeInfo = await this.cacheManager["ZxPayQrCodeCache"].getListByCache(orderNo, comanyId, opType);
    if (qrCodeInfo) {
      return JSON.parse(qrCodeInfo);
    }
    var orderInfo = await this.findItemByCode(orderNo);
    if (!orderInfo) {
      return { code: -130, msg: "订单信息有误" }
    }
    var qrCode = "";
    var setField = {};
    if (opType == "wx") {
      qrCode = await this.getBusUid("wx");
      setField.wxPayOrderCode = qrCode;
      orderInfo.wxPayOrderCode = qrCode;
    } else {
      //支付宝
      qrCode = await this.getBusUid("ali");
      setField.aliPayOrderCode = qrCode;
      orderInfo.aliPayOrderCode = qrCode;
    }
    var opComanyId = orderInfo.subType == "platform" ? 1 : orderInfo.company_id;
    await this.updateByWhere(setField, { where: { code: orderNo } });
    var getQrCodeInfo = await this.utilszxbankSve.getQrCode(opComanyId, qrCode, orderInfo.totalSum * 100,
      orderInfo.sveItemCode, orderInfo.sveItemName, obj.create_ip, opType);
    if (getQrCodeInfo) {
      if (getQrCodeInfo.code != 1) {
        return getQrCodeInfo;
      }
      getQrCodeInfo.data.wxPayOrderCode = orderInfo.wxPayOrderCode;
      getQrCodeInfo.data.aliPayOrderCode = orderInfo.aliPayOrderCode;
      //充值下单成功后初始化业务锁
      await this.cacheManager["ZxPayLocker"].init(qrCode);
      await this.cacheManager["ZxPayQrCodeCache"].setList(orderInfo.code, orderInfo.company_id, opType, JSON.stringify(getQrCodeInfo));
      return getQrCodeInfo;
    }
    return { code: -150, msg: "接口暂无信息返回" };
  }

  async checkPayStatus(obj) {//中信支付状态验证
    try {
      var wxPayOrderCode = obj.wxPayOrderCode || "";
      var aliPayOrderCode = obj.aliPayOrderCode || "";
      var comanyId = obj.company_id;
      var opType = obj.op_type;
      if (!wxPayOrderCode || !aliPayOrderCode || !comanyId || !opType) {
        return { code: -100, msg: "参数信息有误" }
      }
      var payOrderCode = opType == "wx" ? wxPayOrderCode : aliPayOrderCode;

      var payStatus = await this.utilszxbankSve.queryOrder(comanyId, payOrderCode, opType);
      if (payStatus && payStatus.code == 1 && payStatus.data.trade_state == "SUCCESS") {
        payStatus.data.client_ip = obj.client_ip || "";
        return await this.utilszxbankSve.opBackNotify(payStatus.data, "页面回调");
      }
      return { code: -110, msg: "请及时支付" };
    } catch (e) {
      logCtl.error({
        optitle: "页面回调支付状态---error异常",
        op: "/base/service/impl/orderSve.js/checkPayStatus",
        content: "error：" + e.stack + "，参数=" + JSON.stringify(obj),
        clientIp: obj.client_ip || ""
      });
      return { code: -200, msg: "接口异常" };
    }
  }

  async checkPayStatusTl(obj) {//通联支付状态验证
    try {
      var wxPayOrderCode = obj.wxPayOrderCode || "";
      var aliPayOrderCode = obj.aliPayOrderCode || "";
      var comanyId = obj.company_id;
      var subType = obj.sub_type;
      var opType = obj.op_type;
      var orderCode = obj.orderCode;
      if (!wxPayOrderCode || !aliPayOrderCode || !comanyId || !subType || !opType || !orderCode) {
        return { code: -100, msg: "参数信息有误" }
      }
      var orderInfo = await this.findItemByCode(orderCode);
      if (!orderInfo) {
        return { code: -110, msg: "订单信息有误" }
      }
      if (orderInfo.orderPayStatus == "yfk") {
        return { code: 1, msg: "ok", data: { orderPayStatus: "yfk" } };
      }
      var payTrxid = opType == "wx" ? wxPayOrderCode : aliPayOrderCode;
      var opComanyId = subType == "platform" ? 1 : comanyId;
      var payStatus = await this.utilstlbankSve.queryOrder(opComanyId, payTrxid);
      if (payStatus && payStatus.code == 1 && payStatus.data.trxstatus == "0000") {
        payStatus.data.client_ip = obj.client_ip || "";
        let attachList = [];
        if (payStatus.data.reqsn.indexOf("_") >= 0) {
          attachList = payStatus.data.reqsn.split("_");
        }
        else {
          attachList.push(payStatus.data.reqsn);
        }
        if (attachList.length != 2) {
          return { code: -120, msg: "reqsn参数错误，没有_标识" };
        }
        payStatus.data.out_trade_no = attachList[0];
        payStatus.data.company_id = attachList[1];
        return await this.utilstlbankSve.opBackNotify(payStatus.data, "页面回调");
      }
      else if (payStatus && payStatus.code == 1 && payStatus.data.trxstatus == "3045") {
        return { code: -330, msg: "超时未支付，请刷新页面" };
      }
      return { code: -130, msg: "请及时支付" };
    } catch (e) {
      logCtl.error({
        optitle: "支付页面回调支付状态---error异常",
        op: "/base/service/impl/orderSve.js/checkPayStatus",
        content: "error：" + e.stack + "，参数=" + JSON.stringify(obj),
        clientIp: obj.client_ip || ""
      });
      return { code: -200, msg: "接口异常" };
    }
  }
  /*

  */
  async getQrCodeInfoTl(obj) {//获取通联支付二维码
    var orderNo = obj.code || "";
    var comanyId = obj.company_id;
    var opType = obj.op_type;
    if (!orderNo || !comanyId || !opType) {
      return { code: -100, msg: "参数信息有误" }
    }
    var orderInfo = await this.findItemByCode(orderNo);
    if (!orderInfo) {
      return { code: -120, msg: "订单信息有误" }
    }
    if (orderInfo.orderPayStatus == "yfk") {
      return { code: -130, msg: "订单已支付，请勿重复付款" }
    }
    var opComanyId = orderInfo.subType == "platform" ? 1 : orderInfo.company_id;

    if (orderInfo.busPayOrderCode != orderInfo.wxPayOrderCode) {
      var wxPayStatus = await this.utilstlbankSve.queryOrder(opComanyId, orderInfo.wxPayOrderCode);
      if (wxPayStatus && wxPayStatus.code == 1 && wxPayStatus.data.trxstatus == "0000") {
        return { code: -140, msg: "订单已支付，请勿重复付款" }
      }
    }
    if (orderInfo.busPayOrderCode != orderInfo.aliPayOrderCode) {
      var aliPayStatus = await this.utilstlbankSve.queryOrder(opComanyId, orderInfo.aliPayOrderCode);
      if (aliPayStatus && aliPayStatus.code == 1 && aliPayStatus.data.trxstatus == "0000") {
        return { code: -150, msg: "订单已支付，请勿重复付款" }
      }
    }
    var tResult = await this.utilstlbankSve.getQrCode(opComanyId, orderNo, orderInfo.totalSum * 100,
      orderInfo.sveItemCode, orderInfo.sveItemName, obj.create_ip, opType);
    //更新支付类型流水号
    var isPut = 0;
    var setField = {};
    if (opType == "wx") {
      if (tResult.code == 1 && tResult.data.trxid != orderInfo.wxPayOrderCode) {
        setField.wxPayOrderCode = tResult.data.trxid;
        orderInfo.wxPayOrderCode = tResult.data.trxid;
        isPut = 1;
      }
    } else {
      //支付宝
      if (tResult.code == 1 && tResult.data.trxid != orderInfo.aliPayOrderCode) {
        setField.aliPayOrderCode = tResult.data.trxid;
        orderInfo.aliPayOrderCode = tResult.data.trxid;
        isPut = 1;
      }
    }
    if (isPut > 0) {
      await this.updateByWhere(setField, { where: { code: orderNo } });
      //充值下单成功后初始化业务锁
      await this.cacheManager["ZxPayLocker"].init(tResult.data.trxid);
    }
    tResult.data.wxPayOrderCode = orderInfo.wxPayOrderCode;
    tResult.data.aliPayOrderCode = orderInfo.aliPayOrderCode;
    return tResult;
  }

  //--------------------------------------------------------------中信，通联-----获取订单二维码结束------------------------------------

  //---------------------------------icp业务----start-----------------------------------------------------------------------
  async opIcpCustomerInfo(self, user, tm, apply, orderitem, orderObj) {//icp订单客户档案添加和修改
    var customerInfoObj = {
      company_id: user.company_id,
      code: apply.code,
      name: apply.name,
      applyAddr: apply.applyAddr,//申请地址
      businessLicensePic: apply.businessLicensePic,  //营业执照图片
      owner_id: user.id,
      credentialsType: apply.credentialsType,
      customerName: apply.customerName,
      customerType: apply.customerType,
      legalRepresentativeCertificateNo: apply.legalRepresentativeCertificateNo,
      legalRepresentativeCertificatePic: apply.legalRepresentativeCertificatePic,
      valueAddedTelecomBusinessApplicationForm: apply.valueAddedTelecomBusinessApplicationForm,
      naturalPersonShareholderIdCard: apply.naturalPersonShareholderIdCard,
      trusteeshipAgreementAndIDC: apply.trusteeshipAgreementAndIDC,
      domainNameCertificate: apply.domainNameCertificate,
      paymentAgreementAndLicense: apply.paymentAgreementAndLicense,
      capitalFlowDesAndMerchantPresenceTemp: apply.capitalFlowDesAndMerchantPresenceTemp
    };
    //订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if (orderitem && orderitem.orderPayStatus == "dfk" && orderObj.orderStatus == "3") {
      orderObj.orderStatus = "1";
    }//针对修改操作
    var customer = await self.icpcustomerinfoSve.findOneByCodeAndUserId(apply.code, user.id);//查询客户档案
    if (customer && customer.id) {//客户已存在 则更新
      customerInfoObj["id"] = customer.id;
      await self.icpcustomerinfoSve.update(customerInfoObj, tm);
    } else {//客户不存在 则创建
      customer = await self.icpcustomerinfoSve.dao.create(customerInfoObj, tm);
    }
    return customer;
  }
  async tcpOrderCostCalculation(user, company, serviceitem, apply, buyProductCount, price) {  //tcp订单费用计算
    var calObj = {};
    var cpjg = serviceitem.price ? Number(serviceitem.price) : 0;//产品价格
    var cpfl = serviceitem.rateConfig ? Number(serviceitem.rateConfig) : 0;//产品费率
    calObj["sveItemRateConfig"] = cpfl;
    var fwf = serviceitem.serviceCharge ? Number(serviceitem.serviceCharge) : 0;//服务费
    var yhfl = serviceitem.discountsRateConfig ? Number(serviceitem.discountsRateConfig) : 0;//最大优惠费率
    calObj["sveDiscountsRateConfig"] = yhfl;
    var gf = serviceitem.publicExpense ? Number(serviceitem.publicExpense) : 0;//产品官费
    var productCount = 1;//产品数量
    productCount = buyProductCount;

    if (price) {
      price = Number(price);
    } else {
      return { code: -401, msg: "订单价格参数错误" };
    }
    calObj["totalSum"] = price;

    var gfze = 0;//官费总额
    gfze = gf * Number(productCount);
    calObj["totalPublicExpense"] = gfze;

    var fwfze = Number(fwf) * Number(productCount);//服务费总额
    calObj["totalServiceCharge"] = fwfze;

    var sfze = Number(price) / (cpfl + 100) * cpfl; //totalTaxes 税费总额
    sfze = sfze.toFixed(2);
    sfze = Number(sfze);
    calObj["totalTaxes"] = sfze;

    var zdyhe = (gfze + fwfze) * yhfl / 100;//最大优惠额
    zdyhe = zdyhe.toFixed(2);
    zdyhe = Number(zdyhe);

    //毛利总额=应付总额-官费总额
    var mlze = Number(price) - gfze;//totalProfitSum 毛利总额
    mlze = mlze.toFixed(2);
    mlze = Number(mlze);
    calObj["totalProfitSum"] = mlze;

    //优惠金额=服务费+官费总额-应付总额(服务费、官费之和小于等于应付总额时，优惠金额为零)
    var yhje = fwfze + gfze - Number(price);
    if (yhje < 0) {
      yhje = 0;
    }
    yhje = yhje.toFixed(2);
    yhje = Number(yhje);
    if (yhje > zdyhe) {
      return { code: -405, msg: "订单价格有误" };
    }
    calObj["totalDiscounts"] = yhje;

    // user.company.companyType---公司类型
    var channelProfitSum = 0;//订单渠道分成毛利润总额
    var pfProfitSum = 0;//订单平台毛利润总额
    var totalProfitSum = Number(mlze);//订单毛利润总额
    if (totalProfitSum > 0) {
      var tmpChannelProfitRate = Number(serviceitem.channelProfitRate);
      if (tmpChannelProfitRate > 0) {
        var channelProfitRate = tmpChannelProfitRate / 100;
        channelProfitSum = totalProfitSum * channelProfitRate;
        pfProfitSum = totalProfitSum - channelProfitSum;
        channelProfitSum = channelProfitSum.toFixed(2);
        pfProfitSum = pfProfitSum.toFixed(2);
        if (channelProfitSum < 0 || pfProfitSum < 0) {
          return { code: -206, msg: "利润计算有误" };
        }
        calObj["channelProfitSum"] = channelProfitSum;
        calObj["pfProfitSum"] = pfProfitSum;
      } else if (tmpChannelProfitRate == 0) {
        pfProfitSum = mlze;//毛利总额
        calObj["channelProfitSum"] = channelProfitSum;
        calObj["pfProfitSum"] = pfProfitSum;
      }
    }//渠道利润分成比率(只分订单中毛利润总额的分成)
    return { code: 1, data: calObj };
  }
  async createIcpOrder(obj) { //创建icp订单
    var itemCode = obj.itemCode;//产品编码
    var self = this;
    var apply = obj.apply;
    var user = obj.user;
    var price = obj.price;
    if (!itemCode) {
      return { code: -101, mag: 'itemCode参数错误' };
    }
    var serviceitem = await this.serviceitemSve.findOneByCode(itemCode, user.company_id);//获取产品
    if (!serviceitem) {
      return { code: -102, mag: '未知的产品' };
    }
    //获取公司信息
    var companyItem = await this.companyDao.model.findOne({
      where: { id: user.company_id },
      attributes: ["id", "companyType"],
      raw: true
    });
    if (!companyItem) {
      return { code: -103, mag: '未知的公司信息' };
    }
    var calObj = await this.tcpOrderCostCalculation(user, companyItem, serviceitem, apply, 1, obj.price);
    if (!calObj || !calObj.code) {
      return { code: -104, mag: '订单价格计算失败' };
    }
    if (calObj.code < 0) {
      return calObj;
    }
    calObj = calObj.data;
    return this.db.transaction(async function (t) {
      var ordercode = await self.getBusUid("icpo");
      var orderObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        name: "icp注册",
        code: ordercode,
        busPayOrderCode: ordercode,//业务支付订单号
        wxPayOrderCode: ordercode,//业务微信支付订单号
        aliPayOrderCode: ordercode,//业务支付宝支付订单号
        orderType: apply.orderType || "zzdd",//订单类型，"zzdd": "自主订单","dkxd": "代客下单"
        salesNum: 1,//项目订单数量（即服务项目的倍数，默认值为1）
        salesDiliverNum: 0,//项目订单交付数量（即与项目订单数量相对应）
        orderPayStatus: "dfk",//订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
        orderFlowStatus: "1",//订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
        orderStatus: "1",//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
        totalServiceCharge: calObj.totalServiceCharge,//服务费总额
        totalPublicExpense: calObj.totalPublicExpense,//官费总额
        totalDiscounts: calObj.totalDiscounts,//优惠总额
        totalTaxes: calObj.totalTaxes,//税费总额
        totalSum: calObj.totalSum,//订单总额（含税）
        totalProfitSum: calObj.totalProfitSum,//订单毛利润总额（含税:订单总额-官费总额）
        pfProfitSum: calObj.pfProfitSum || 0,//订单平台毛利润总额
        channelProfitSum: calObj.channelProfitSum || 0,//订单渠道分成毛利润总额
        sveItemType: "ip",//服务项目类型
        sveItemRateConfig: serviceitem.rateConfig || 0,//产品费率
        sveDiscountsRateConfig: calObj.sveDiscountsRateConfig || 0,//优惠税率
        sveItemCode: itemCode,//项目操作码
        sveItemName: serviceitem.name,//项目名称
        mobilePic: serviceitem.mobilePic,//移动端产品图片
        productonetype_id: serviceitem.producttype_pid_id,//产品大类Id
        producttype_id: serviceitem.producttype_id,//产品小类Id
        serviceItemSnapshot: JSON.stringify(serviceitem),//产品快照
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
        notes: apply.notes, //备注
        subType: companyItem.companyType == "self" ? "self" : "platform",
      };

      //icp订单客户档案添加和修改
      var customer = await self.opIcpCustomerInfo(self, user, t, apply, null, orderObj);
      orderObj["icpcustomerinfo_id"] = customer.id;
      var order = await self.dao.create(orderObj, t);//创建订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: order.code,
        opContent: "创建订单"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程

      return { code: 1, msg: "success", data: order };

    })

  }
  async updateIcpOrder(obj) {//修改icp订单
    var itemCode = obj.itemCode;//产品编码
    var orderNum = obj.orderNum;//订单编号
    var user = obj.user;
    var self = this;
    var apply = obj.apply;
    if (!orderNum) {
      return { code: -100, mag: 'orderNum参数错误' };
    }
    if (!itemCode) {
      return { code: -101, mag: 'itemCode参数错误' };
    }
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    //orderPayStatus订单付款状态"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
    //orderFlowStatus订单审核状态"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
    //orderStatus订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
    if ((["dfk", "yfk", "zfpz", "pzshwtg"].indexOf(orderitem.orderPayStatus) < 0) ||
      (["1", "2"].indexOf(orderitem.orderFlowStatus) < 0) ||
      (["1", "2", "3", "4", "6"].indexOf(orderitem.orderStatus) < 0)) {
      return { code: -104, msg: "目前的订单的状态，不能进行修改" };
    }
    if (!orderitem.serviceItemSnapshot) {
      return { code: -106, mag: '订单产品未知' };
    }
    var serviceitem = JSON.parse(orderitem.serviceItemSnapshot);//获取快照产品
    //获取公司信息
    var companyItem = await this.companyDao.model.findOne({
      where: { id: user.company_id },
      attributes: ["id", "companyType"],
      raw: true
    });
    if (!companyItem) {
      return { code: -107, mag: '未知的公司信息' };
    }
    var calObj = await this.tcpOrderCostCalculation(user, companyItem, serviceitem, apply, 1, obj.price);
    if (!calObj || !calObj.code) {
      return { code: -108, mag: '订单价格计算失败' };
    }
    if (calObj.code < 0) {
      return calObj;
    }
    calObj = calObj.data;
    if (orderitem.orderPayStatus != "dfk") {
      if (Number(orderitem.totalPublicExpense) != Number(calObj.totalPublicExpense)) {
        return { code: -220, msg: "官费总额与原有订单不符" };
      }
      if (Number(orderitem.totalServiceCharge) != Number(calObj.totalServiceCharge)) {
        return { code: -221, msg: "服务费总额与原有订单不符" };
      }
      if (Number(orderitem.totalSum) != Number(calObj.totalSum)) {
        return { code: -222, msg: "订单总额与原有订单不符" };
      }
      if (Number(orderitem.sveItemRateConfig) != Number(calObj.sveItemRateConfig)) {
        return { code: -223, msg: "产品费率与原有订单不符" };
      }
      if (Number(orderitem.sveDiscountsRateConfig) != Number(serviceitem.sveDiscountsRateConfig)) {
        return { code: -224, msg: "优惠税率与原有订单不符" };
      }

    }
    return this.db.transaction(async function (t) {
      var orderObj = {
        id: orderitem.id,
        updateuser_id: user.id,
        totalServiceCharge: calObj.totalServiceCharge,//服务费总额
        totalPublicExpense: calObj.totalPublicExpense,//官费总额
        totalDiscounts: calObj.totalDiscounts,//优惠总额
        totalTaxes: calObj.totalTaxes,//税费总额
        totalSum: calObj.totalSum,//订单总额（含税）
        totalProfitSum: calObj.totalProfitSum,//订单毛利润总额（含税:订单总额-官费总额）
        pfProfitSum: calObj.pfProfitSum || 0,//订单平台毛利润总额
        channelProfitSum: calObj.channelProfitSum || 0,//订单渠道分成毛利润总额
        sveItemRateConfig: serviceitem.rateConfig || 0,//产品费率
        sveDiscountsRateConfig: calObj.sveDiscountsRateConfig || 0,//优惠税率
        contacts: apply.contacts,//联系人
        mobile: apply.mobile,//手机号
        email: apply.email,//邮箱
        notes: apply.notes, //备注
        subType: companyItem.companyType == "self" ? "self" : "platform",
      };
      //订单客户档案添加和修改
      await self.opIcpCustomerInfo(self, user, t, apply, orderitem, orderObj);
      await self.dao.update(orderObj, t);//修改订单
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "修改订单信息"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      return { code: 1, msg: "success", data: orderitem };
    });
  }
  async saveIcpOrder(obj, user) {//修改保存icp订单 //icp订单详情页保存修改功能使用
    var orderNum = obj.orderNum;//订单编号
    var self = this;
    if (!orderNum) {
      return { code: -100, mag: 'orderNum参数错误' };
    }
    var orderitem = await this.findOneByCode(orderNum);//获取订单
    if (!orderitem) {
      return { code: -103, mag: '未知的订单' };
    }
    if (!orderitem.icpcustomerinfo_id) {
      return { code: -104, mag: '未知申请信息' };
    }
    return this.db.transaction(async function (t) {
      if (obj.orderStatus) {
        await self.dao.model.update({ orderStatus: obj.orderStatus }, { where: { id: orderitem.id }, transaction: t });
      }
      await self.icpcustomerinfoSve.dao.model.update(obj, { where: { id: orderitem.icpcustomerinfo_id }, transaction: t });
      var flowObj = {
        company_id: user.company_id,
        createuser_id: user.id,
        sourceOrderNo: orderitem.code,
        opContent: "修改订单信息"
      };
      var orderflow = await self.orderflowSve.dao.create(flowObj, t);//创建订单流程
      return { code: 1, msg: "success" };
    });
  }
  async getIcpOrderDetail(orderNum) {//获取icp订单详情
    if (!orderNum) {
      return { code: -101, msg: "orderNum参数错误" };
    }
    var order = await this.dao.findOne({ code: orderNum });
    var data = {};
    if (order && order.id) {
      data["order"] = order;
      var icpcustomerinfo = await this.icpcustomerinfoSve.dao.findOne({ id: order.icpcustomerinfo_id });//客户信息
      data["icpcustomerinfo"] = icpcustomerinfo;
      var company = await this.companyDao.model.findOne({ where: { id: order.company_id }, attributes: ["contact", "contactmobile", "fax", "zipCode"] });
      data["company"] = company;
      var receiptvoucher = await this.receiptvoucherDao.model.findOne({ where: { sourceOrderNo: order.code }, attributes: ["accountTypeName", "accountType", "payDate", "certifyFileUrl"], 'order': [['created_at', 'ASC']] });
      data["receiptvoucher"] = receiptvoucher;
      return { code: 1, data: data };
    } else {
      return { code: -100, msg: "订单数据为空" };
    }
  }
  //---------------------------------icp业务----end-----------------------------------------------------------------------

}
module.exports = OrderService;
// var task = new OrderService();
// task.orderPaymentReminder().then(d=>{
//   console.log("dddddddddddddddddd");
//   console.log(d);
// })
