var System = require("../../system");
var settings = require("../../../config/settings");
const uiconfig = System.getUiConfig2(settings.wxconfig.appId);
const logCtl = System.getObject("web.oplogCtl");
var moment = require("moment");
const md5 = require("MD5");
//商标查询操作
class utilsCloudSve {
  constructor() {
    this.zxyTransferAppId = settings.apiconfig.zxyTransferAppId();
    this.zxyTransferMchtId = settings.apiconfig.zxyTransferMchtId();
    this.zxyMainId = settings.apiconfig.zxyMainId();
    this.zxyAppSecretKey = settings.apiconfig.zxyAppSecretKey();
    this.zxyUserSignUrl = settings.apiconfig.zxyUserSignUrl();
    this.zxyTransferUrl = settings.apiconfig.zxyTransferUrl();
    this.restClient = System.getObject("util.restClient");

    this.receiptvoucherDao = System.getObject("db.receiptvoucherDao");//收款单
    this.expensevoucherDao = System.getObject("db.expensevoucherDao");//费用单
    this.moneyjourneyDao = System.getObject("db.moneyjourneyDao");//账单
    this.orderDao = System.getObject("db.orderDao");
    this.orderflowDao = System.getObject("db.orderflowDao");
    this.oplogDao = System.getObject("db.oplogDao");
    this.companyDao = System.getObject("db.companyDao");
    this.customerinfoDao = System.getObject("db.customerinfoDao");
    this.moneyaccountDao = System.getObject("db.moneyaccountDao");
  }
  async aliPayNotify(obj) {
    // obj = {
    //   order_num: attachList.length > 0 ? attachList[0] : "",
    //   user_id: attachList.length > 1 ? attachList[1] : "",
    //   out_trade_no: msg.out_trade_no,
    //   amount: Number(msg.total_fee) / 100
    // }
    //日志记录
    logCtl.info({
      optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "：ali回调信息============================================",
      op: "base/service/impl/utilscloudSve.js/wxPayNotify",
      content: JSON.stringify(obj),
      clientIp: ""
    });
    obj.req_accountType = "alipay";
    await this.notifyOpDb(obj);
  }
  async wxPayNotify(obj) {
    // obj = {
    //   order_num: attachList.length > 0 ? attachList[0] : "",
    //   user_id: attachList.length > 1 ? attachList[1] : "",
    //   out_trade_no: msg.out_trade_no,
    //   amount: Number(msg.total_fee) / 100
    // }
    //日志记录
    logCtl.info({
      optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "：wx回调信息============================================",
      op: "base/service/impl/utilscloudSve.js/wxPayNotify",
      content: JSON.stringify(obj),
      clientIp: ""
    });
    obj.req_accountType = "wx";
    await this.notifyOpDb(obj);
  }

  async notifyOpDb(obj) {
    var account_type_list = uiconfig.config.pdict.accountType;
    var account_type_name = account_type_list[obj.req_accountType];
    obj.account_type_name = account_type_name;

    var sqlWheres = { code: obj.order_num };
    var orderItem = await this.orderDao.model.findOne({
      where: sqlWheres,
      include: [
        { model: this.orderDao.db.models.customerinfo, attributes: ["businessLicensePic", "customerType", "identityCardNo", "identityCardPic"] }
      ]
    });
    if (!orderItem) {
      throw new Error(obj.order_num + "对应的订单信息暂无");
    }
    if (Number(orderItem.totalSum) != Number(obj.amount)) {
      throw new Error(obj.order_num + "对应的订单支付金额不符");
    }
    if (orderItem.orderStatus != "1" && orderItem.orderPayStatus != "dfk") {
      throw new Error(obj.order_num + "订单状态有误");
    }
    //获取平台公司信息
    var platformCompanyItem = await this.companyDao.model.findOne({
      where: { id: 1 },
      include: [
        {
          model: this.orderDao.db.models.moneyaccount,
          attributes: ["id", "code", "name", "balance"],
          where: { accountType: obj.req_accountType, company_id: 1 }
        }
      ]
    });
    if (!platformCompanyItem || !platformCompanyItem.moneyaccounts || platformCompanyItem.moneyaccounts.length == 0) {
      throw new Error(!platformCompanyItem ? "平台的公司信息为空" : "平台账户信息为空");
    }
    var self = this;
    await this.orderDao.db.transaction(async function (t) {
      //订单付款状态orderPayStatus:"dfk": "待付款", "yfk": "已付款", "ddqx": "订单取消", "tkclz": "退款处理中", "ytk": "已退款"
      //订单审核状态orderFlowStatus:"1": "提交订单", "2": "已付款", "3": "已审核-待递交", "4": "已递交", "5": "已完成"
      var putParams = { orderPayStatus: "yfk", orderFlowStatus: "2", auditStatus: "tg" };
      await self.orderDao.updateByWhere(putParams, { where: sqlWheres }, t);
      //订单流程log
      self.orderflowDao.create({
        company_id: orderItem.company_id,
        createuser_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        opContent: "订单已成功支付，方式为" + account_type_name,
      }, t);
      var receiptvoucherList = [];//收款单
      var moneyjourneyList = [];//账单  
      var expensevoucherList = [];//费用


      var pfCompanyMoneyInfo = {};
      var otherMoneyInfo = {};
      var pfBankCompanyMoneyInfo = {};
      //操作平台帐户金额信息
      await self.opPlatformAccountBill(self, platformCompanyItem, pfCompanyMoneyInfo, orderItem, obj, receiptvoucherList, moneyjourneyList);
      //操作给第三方公司转账
      await self.opThirdPartyCompanies(self, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList, pfBankCompanyMoneyInfo, otherMoneyInfo, t);
      if (receiptvoucherList.length > 0) {
        await self.receiptvoucherDao.bulkCreate(receiptvoucherList, t);
      }
      if (moneyjourneyList.length > 0) {
        await self.moneyjourneyDao.bulkCreate(moneyjourneyList, t);
      }
      if (expensevoucherList.length > 0) {
        await self.expensevoucherDao.bulkCreate(expensevoucherList, t);
      }
      //操作平台、第三方公司的biz_moneyaccount表余额
      if (pfCompanyMoneyInfo && pfCompanyMoneyInfo.company_id && pfCompanyMoneyInfo.moneyaccount_id) {
        var pfMoneyTotal = parseFloat(pfCompanyMoneyInfo.moneyTotal || 0);
        pfMoneyTotal = pfMoneyTotal.toFixed(2);
        var pfOldMoneyTotal = Number(pfCompanyMoneyInfo.oldMoneyTotal || 0);
        if (pfMoneyTotal > 0 && pfMoneyTotal > pfOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: pfMoneyTotal },
            { where: { company_id: pfCompanyMoneyInfo.company_id, id: pfCompanyMoneyInfo.moneyaccount_id } }, t);
        }
      }
      if (pfBankCompanyMoneyInfo && pfBankCompanyMoneyInfo.company_id && pfBankCompanyMoneyInfo.moneyaccount_id) {
        var pfBankMoneyTotal = parseFloat(pfBankCompanyMoneyInfo.moneyTotal || 0);
        pfBankMoneyTotal = pfBankMoneyTotal.toFixed(2);
        var pfBankOldMoneyTotal = Number(pfBankCompanyMoneyInfo.oldMoneyTotal || 0);
        if (pfBankMoneyTotal != pfBankOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: pfBankMoneyTotal },
            { where: { company_id: pfBankCompanyMoneyInfo.company_id, id: pfBankCompanyMoneyInfo.moneyaccount_id } }, t);
        }
      }
      if (otherMoneyInfo && otherMoneyInfo.company_id && otherMoneyInfo.moneyaccount_id) {
        var otherMoneyTotal = parseFloat(otherMoneyInfo.moneyTotal || 0);
        otherMoneyTotal = otherMoneyTotal.toFixed(2);
        var otherOldMoneyTotal = Number(otherMoneyInfo.oldMoneyTotal || 0);
        if (otherMoneyTotal > 0 && otherMoneyTotal > otherOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: otherMoneyTotal },
            { where: { company_id: otherMoneyInfo.company_id, id: otherMoneyInfo.moneyaccount_id } }, t);
        }
      }
    });
  }

  //操作平台帐户金额信息
  async opPlatformAccountBill(self, platformCompanyItem, pfCompanyMoneyInfo, orderItem, obj, receiptvoucherList, moneyjourneyList) {
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    var ptskCode = await logCtl.getBusUid_Ctl("ptsk");
    receiptvoucherList.push({
      company_id: 1,//平台公司id
      code: ptskCode,
      createuser_id: orderItem.createuser_id,//第三方公司订单创建者
      auditStatus: "tg",
      sourceType: "order",
      sourceOrderNo: orderItem.code,
      payOrderNo: obj.out_trade_no,
      receiptType: orderItem.company_id == 1 ? "sk" : "ptdsk",
      accountType: obj.req_accountType,
      payDate: new Date(),
      payFlowType: 1,
      totalSum: orderItem.totalSum,
      notes: nowTimeStr + "：平台" + obj.account_type_name + "收款",
      moneyaccount_id: platformCompanyItem.moneyaccounts[0].id,
      sveItemCode: orderItem.sveItemCode,//项目操作码
      sveItemName: orderItem.sveItemName,//项目名称
      createcompany_id: orderItem.company_id,
    });
    moneyjourneyList.push({
      company_id: 1,//平台公司id
      createuser_id: orderItem.createuser_id,//第三方公司订单创建者
      code: ptskCode,
      accountType: obj.req_accountType,
      directionType: "sr",//凭单类型,"sr": "收","zc": "支"
      voucherDate: new Date(),
      recvAmount: orderItem.totalSum,
      sourceType: "receiptvoucher",
      sourceOrderNo: orderItem.code,
      payOrderNo: obj.out_trade_no,
      auditStatus: "tg",
      notes: nowTimeStr + "：平台" + obj.account_type_name + "收款",
      moneyaccount_id: platformCompanyItem.moneyaccounts[0].id,
      createcompany_id: orderItem.company_id,
    });
    pfCompanyMoneyInfo["company_id"] = 1;
    pfCompanyMoneyInfo["moneyaccount_id"] = platformCompanyItem.moneyaccounts[0].id;
    pfCompanyMoneyInfo["oldMoneyTotal"] = Number(platformCompanyItem.moneyaccounts[0].balance || 0);
    pfCompanyMoneyInfo["moneyTotal"] = Number(platformCompanyItem.moneyaccounts[0].balance || 0) + Number(orderItem.totalSum);
  }
  //操作给第三方公司转账
  async opThirdPartyCompanies(self, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList, pfBankCompanyMoneyInfo, otherMoneyInfo, t) {
    if (orderItem.company_id == 1) {
      return;
    }
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    //获取第三方公司转账帐户信息-----------------------------------------------------------------------------------------------------------
    var companyItem = await self.companyDao.model.findOne({
      where: { id: orderItem.company_id },
      include: [
        {
          model: self.orderDao.db.models.moneyaccount,
          attributes: ["id", "code", "name", "balance", "transferRate", "certificateNo"],
          where: { accountType: "bank", isPlatformAutopay: 1 }
          // where: { accountType: "bank", company_id: orderItem.company_id, isPlatformAutopay: 1 }
        }
      ]
    });
    if (!companyItem) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：查询公司信息为空--info",
        logLevel: "info",
        content: nowTimeStr + "：查询公司信息为空--info",
        opLogType: "payCallback",
        opLogStatus: "success",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    if (!companyItem.companyType || companyItem.companyType != "self") {//公司类型，self独立运作，full为全委托，part部分委托
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：为全委托版本，无需给公司转账",
        logLevel: "info",
        content: nowTimeStr + "：为全委托版本，无需给公司转账",
        opLogType: "payCallback",
        opLogStatus: "success",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    if (!companyItem.moneyaccounts || companyItem.moneyaccounts.length == 0) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：公司对应的银行信息为空，无法转账--error",
        logLevel: "error",
        content: nowTimeStr + "：公司对应的银行信息为空，无法转账--error",
        opLogType: "payCallback",
        opLogStatus: "fail",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }

    //获取平台公司转账帐户信息-----------------------------------------------------------------------------------------------------------
    var platformBankCompanyItem = await self.companyDao.model.findOne({
      where: { id: 1 },
      include: [
        {
          model: self.orderDao.db.models.moneyaccount,
          attributes: ["id", "code", "name", "balance"],
          where: { accountType: "bank", isPlatformAutopay: 1 }
          // where: { accountType: "bank", company_id: 1, isPlatformAutopay: 1 }
        }
      ]
    });
    if (!platformBankCompanyItem || !platformBankCompanyItem.moneyaccounts || platformBankCompanyItem.moneyaccounts.length == 0) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：查询平台公司信息为空--info",
        logLevel: "error",
        content: nowTimeStr + "：查询平台公司信息为空--info",
        opLogType: "payCallback",
        opLogStatus: "fail",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    if (!platformBankCompanyItem.moneyaccounts || platformBankCompanyItem.moneyaccounts.length == 0) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：平台公司对应的银行信息为空，无法转账--error",
        logLevel: "error",
        content: nowTimeStr + "：平台公司对应的银行信息为空，无法转账--error",
        opLogType: "payCallback",
        opLogStatus: "fail",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    if (Number(platformBankCompanyItem.moneyaccounts[0].balance || 0) <= 0) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "平台公司转账帐户余额不足，余额小于等于0",
        logLevel: "error",
        content: "",
        opLogType: "payCallback",
        opLogStatus: "fail",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    await self.opThirdPartyCompaniesDb(self, platformBankCompanyItem, companyItem, nowTimeStr, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList, pfBankCompanyMoneyInfo, otherMoneyInfo, t);

  }
  //操作给第三方公司转账操作db
  async opThirdPartyCompaniesDb(self, platformBankCompanyItem, companyItem, nowTimeStr, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList, pfBankCompanyMoneyInfo, otherMoneyInfo, t) {
    var transferRate = (Number(orderItem.totalSum) * Number(companyItem.moneyaccounts[0].transferRate || "0") / 1000);//转账手续费用
    transferRate = isNaN(transferRate) ? 0 : transferRate.toFixed(2);
    var amt = Number(orderItem.totalSum) - transferRate;//转账金额，单位元
    amt = amt.toFixed(2)

    if (Number(platformBankCompanyItem.moneyaccounts[0].balance || 0) < amt) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompaniesDb",
        opTitle: nowTimeStr + "平台公司转账帐户余额不足，余额小于要转账的订单金额",
        logLevel: "info",
        content: "平台公司转账帐户余额为：" + platformBankCompanyItem.moneyaccounts[0].balance,
        opLogType: "payCallback",
        opLogStatus: "fail",
        totalSum: amt
      }, t);
      return;
    }
    var transferParam = {
      orderNo: orderItem.code,
      bizs: [{
        "note": "平台对商标自主提报转账给第三方公司帐号",
        "idType": "00",//证件类型,00=身份证
        "idName": companyItem.contact,
        "seqNo": "1001",
        "accNo": companyItem.moneyaccounts[0].code,//卡号
        "mobile": companyItem.contactmobile,//手机号
        "amt": amt * 100,//单位分
        "accType": "00",//账号类型,00 银行 01 支付宝 02 微信
        "idNo": companyItem.moneyaccounts[0].certificateNo//身份证号
      }]
    }
    var transferRsult = await self.transfer(transferParam);
    if (transferRsult.code != 1) {
      await self.oplogDao.create({
        company_id: orderItem.company_id,
        user_id: orderItem.createuser_id,
        sourceOrderNo: orderItem.code,
        op: "/service/impl/utilscloudSve.js/opThirdPartyCompanies",
        opTitle: nowTimeStr + "：平台通过薪必果给第三方公司转账失败_error",
        logLevel: "error",
        content: "请求薪必果转账参数为：" + JSON.stringify(transferParam) + "结果为：" + JSON.stringify(transferRsult),
        opLogType: "pfTransfer",
        opLogStatus: "fail",
        totalSum: orderItem.totalSum
      }, t);
      return;
    }
    await self.oplogDao.create({
      company_id: orderItem.company_id,
      user_id: orderItem.createuser_id,
      sourceOrderNo: orderItem.code,
      op: "/service/impl/utilscloudSve.js/opThirdPartyCompaniesDb",
      opTitle: nowTimeStr + "：平台通过薪必果给第三方公司转账",
      logLevel: "info",
      content: "请求薪必果转账参数为：" + JSON.stringify(transferParam) + "结果为：" + JSON.stringify(transferRsult),
      opLogType: "pfTransfer",
      opLogStatus: "waitingProcess",
      totalSum: amt
    }, t);
    if (transferRsult.code == 1) {
      //平台---------------------------------------------------------------------------------------------------
      var ptzzCode = await logCtl.getBusUid_Ctl("ptzz");
      receiptvoucherList.push({
        company_id: 1,//平台公司id
        code: ptzzCode,
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        auditStatus: "tg",
        sourceType: "order",
        sourceOrderNo: orderItem.code,
        receiptType: "ptzz",
        accountType: "bank",
        payDate: new Date(),
        payFlowType: 1,
        totalSum: -orderItem.totalSum,
        notes: nowTimeStr + "：平台银行转账到第三方公司银行",
        moneyaccount_id: platformBankCompanyItem.moneyaccounts[0].id,
        sveItemCode: orderItem.sveItemCode,//项目操作码
        sveItemName: orderItem.sveItemName,//项目名称
        createcompany_id: 1,
      });
      moneyjourneyList.push({
        company_id: 1,//平台公司id
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        code: ptzzCode,
        accountType: "bank",
        directionType: "zc",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        payAmount: orderItem.totalSum,
        sourceType: "receiptvoucher",
        sourceOrderNo: orderItem.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：平台银行转账到第三方公司银行",
        moneyaccount_id: platformBankCompanyItem.moneyaccounts[0].id,
        createcompany_id: 1,
      });
      //减去平台转账帐户对应的biz_moneyaccount表中的余额
      pfBankCompanyMoneyInfo["company_id"] = 1;
      pfBankCompanyMoneyInfo["moneyaccount_id"] = platformBankCompanyItem.moneyaccounts[0].id;
      pfBankCompanyMoneyInfo["oldMoneyTotal"] = Number(platformBankCompanyItem.moneyaccounts[0].balance || 0);
      pfBankCompanyMoneyInfo["moneyTotal"] = Number(platformBankCompanyItem.moneyaccounts[0].balance || 0) - orderItem.totalSum;
      //第三方公司收款单---------------------------------------------------------------------------------------------------
      var skCode = await logCtl.getBusUid_Ctl("sk");
      receiptvoucherList.push({
        company_id: orderItem.company_id,//公司id
        code: skCode,
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        auditStatus: "tg",
        sourceType: "order",
        sourceOrderNo: orderItem.code,
        receiptType: "zz",
        accountType: "bank",
        payDate: new Date(),
        payFlowType: 1,
        totalSum: orderItem.totalSum,
        notes: nowTimeStr + "：平台转账进账",
        moneyaccount_id: companyItem.moneyaccounts[0].id,
        sveItemCode: orderItem.sveItemCode,//项目操作码
        sveItemName: orderItem.sveItemName,//项目名称
        createcompany_id: orderItem.company_id,
      });
      moneyjourneyList.push({
        company_id: orderItem.company_id,//公司id
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        code: skCode,
        accountType: "bank",
        directionType: "sr",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        recvAmount: orderItem.totalSum,
        sourceType: "receiptvoucher",
        sourceOrderNo: orderItem.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：平台转账进账",
        moneyaccount_id: companyItem.moneyaccounts[0].id,
        createcompany_id: orderItem.company_id,
      });
      otherMoneyInfo["company_id"] = orderItem.company_id;
      otherMoneyInfo["moneyaccount_id"] = companyItem.moneyaccounts[0].id;
      otherMoneyInfo["oldMoneyTotal"] = Number(companyItem.moneyaccounts[0].balance || 0);
      otherMoneyInfo["moneyTotal"] = Number(companyItem.moneyaccounts[0].balance || 0) + Number(orderItem.totalSum);
      //**************************手续费手续费*******************************************************************************
      if (transferRate > 0) {      
        //第三方公司手续费记录---------------------------------------------------------------------------------------------------
        var fyzzCode = await logCtl.getBusUid_Ctl("sxf");
        expensevoucherList.push({
          company_id: orderItem.company_id,//公司id
          createuser_id: orderItem.createuser_id,
          code: fyzzCode,
          sourceType: "order",
          sourceOrderNo: orderItem.code,
          expenseType: "sxf",
          totalSum: transferRate,
          auditStatus: "tg",
          notes: nowTimeStr + "：平台转账手续费扣除",
          moneyaccount_id: companyItem.moneyaccounts[0].id,
          createcompany_id: orderItem.company_id,
        });
        moneyjourneyList.push({
          company_id: orderItem.company_id,//公司id
          createuser_id: orderItem.createuser_id,
          code: fyzzCode,
          accountType: "bank",
          directionType: "zc",//凭单类型,"sr": "收","zc": "支"
          voucherDate: new Date(),
          payAmount: transferRate,
          sourceType: "expensevoucher",
          sourceOrderNo: orderItem.code,
          auditStatus: "tg",
          notes: nowTimeStr + "：平台转账手续费扣除",
          moneyaccount_id: companyItem.moneyaccounts[0].id,
          createcompany_id: orderItem.company_id,
        });
        //减去第三方公司对应的biz_moneyaccount表中的余额
        otherMoneyInfo["moneyTotal"] = Number(otherMoneyInfo["moneyTotal"]) - transferRate;
      }//第三方公司记录费用单---------------------------------
    }
  }


  //..........................薪必果转账.............................................................开始

  async userSign(obj) {//用户签约
    var result = {};
    // 39.96.42.199 端口：80  appId:1086941347  mchtId:108694134791293777   mainId:57731585  secret:def87140063233abc
    var beginTime = moment().format("YYYYMMDDHHmmss");
    var completeTime = moment().add(1, "hours").format("YYYYMMDDHHmmss");
    var invalidTime = moment().add(1, "years").format("YYYYMMDDHHmmss");

    var param = {
      "accNo": obj.accNo || "",
      "appId": this.zxyTransferAppId,
      "beginTime": beginTime,//签约开始时间
      "completeTime": completeTime,//签约完成时间
      "idName": obj.idName,
      "idNo": obj.idNo,
      "idType": obj.idType,
      "invalidTime": invalidTime,//签约失效时间
      "mainId": this.zxyMainId,//签约主体id
      "mchtId": this.zxyTransferMchtId,
      "mobile": obj.mobile,
      "nonceStr": "nonceStrnonceStr",
      "signType": "MD5",
      "signedName": obj.signedName//签约合同名称
    };

    var signArr = [];
    signArr.push("appId=" + (param.appId || ""));
    signArr.push("beginTime=" + (param.beginTime || ""));
    signArr.push("completeTime=" + (param.completeTime || ""));
    signArr.push("idName=" + (param.idName || ""));
    signArr.push("idNo=" + (param.idNo || ""));
    signArr.push("idType=" + (param.idType || ""));
    signArr.push("invalidTime=" + (param.invalidTime || ""));
    signArr.push("mainId=" + (param.mainId || ""));
    signArr.push("mchtId=" + (param.mchtId || ""));
    signArr.push("mobile=" + (param.mobile || ""));
    signArr.push("nonceStr=" + (param.nonceStr || ""));
    signArr.push("signType=" + (param.signType || ""));
    signArr.push("signedName=" + (param.signedName || ""));
    signArr.push("key=" + this.zxyAppSecretKey);

    param.sign = md5(signArr.join("&")).toUpperCase();

    var reqUrl = this.zxyUserSignUrl + "/merchant/userSigned/asyncNotify";//"https://payadmin.gongsibao.com/merchant/userSigned/asyncNotify";
    return await this.execPostResult(reqUrl, param, "userSign", result);
  }

  async busiAccount(obj) {
    var result = {};

    var param = {
      "appId": this.zxyTransferAppId,
      "sign": "439BAC772B4ECF9B7D9BB2EBB4A1C438",
      "mchtId": this.zxyTransferMchtId,
      "signType": "MD5",
      "nonceStr": obj.orderNo
    }

    var signArr = [];
    signArr.push("appId=" + param.appId);
    signArr.push("mchtId=" + param.mchtId);
    signArr.push("nonceStr=" + param.nonceStr);
    signArr.push("signType=" + param.signType);
    signArr.push("key=" + this.zxyAppSecretKey);

    param.sign = md5(signArr.join("&")).toUpperCase();

    var reqUrl = this.zxyTransferUrl + "/merchant/busiAccount/query"//"https://pay.gongsibao.com/merchant/busiAccount/query";
    return await this.execPostResult(reqUrl, param, "busiAccount", result);
  }

  async transfer(obj, isAwait) {
    var tmpIsAwait = isAwait || 0;
    var result = {};
    var bizs = obj.bizs;
    var bizContent = [];
    if (!bizs || bizs.length == 0) {
      result.code = 0;
      result.msg = "请填写发薪人员";
      return result;
    }
    for (var biz of bizs) {
      bizContent.push({
        "note": "知产平台转账操作",
        "idType": "00",//证件类型,00=身份证
        "idName": biz.idName,//用户名
        "seqNo": "1001",
        "accNo": biz.accNo,//卡号
        "mobile": biz.mobile,//手机号
        "amt": Number(biz.amt || 100),//金额分
        "accType": "00",//账号类型,00 银行 01 支付宝 02 微信
        "idNo": biz.idNo//身份证号
      });
    }

    var now = moment().add(30, 'seconds').format('YYYYMMDDHHmmss');
    var param = {
      "appId": this.zxyTransferAppId,//应用id
      "currency": "CNY",//币种，人民币
      "mchtId": this.zxyTransferMchtId,//商户id
      "nonceStr": "nonceStrnonceStr",//随机数
      "notityUrl": "http://igirl.gongsibao.com/api/xbg/transferNotify",
      "outTradeNo": obj.orderNo,//商户订单号（不允许重复）
      "signType": "MD5",
      "tradeTime": now,//交易时间，格式yyyyMMddHHmmss
      "bizContent": bizContent
    }

    // now
    var signArr = [];
    signArr.push("appId=" + param.appId);
    signArr.push("currency=" + param.currency);
    signArr.push("mchtId=" + param.mchtId);
    signArr.push("nonceStr=" + param.nonceStr);
    signArr.push("notityUrl=" + param.notityUrl);
    signArr.push("outTradeNo=" + param.outTradeNo);
    signArr.push("signType=" + param.signType);
    signArr.push("tradeTime=" + param.tradeTime);
    signArr.push("key=" + this.zxyAppSecretKey);
    param.sign = md5(signArr.join("&")).toUpperCase();

    var reqUrl = this.zxyTransferUrl + "/merchant/order/transfer"//"https://pay.gongsibao.com/merchant/order/transfer";
    if (tmpIsAwait == 0) {
      return this.execPostResult(reqUrl, param, "transfer", result);
    }
    else {
      return await this.execPostResult(reqUrl, param, "transfer", result);
    }
  }

  async execPostResult(reqUrl, param, methodName, result) {
    var rtn = null;
    try {
      rtn = await this.restClient.execPost(param, reqUrl);
      //日志记录
      logCtl.info({
        optitle: "请求薪必果接口返回结果信息===info",
        op: "base/service/impl/utilscloudSve.js/" + methodName,
        content: "请求地址：" + reqUrl + "，param=" + JSON.stringify(param) + "，return=" + rtn.stdout,
        clientIp: ""
      });
      if (rtn && rtn.stdout) {
        var stdout = JSON.parse(rtn.stdout) || {};
        var code = stdout.code;
        if (code == 0) {
          code = 1;
        } else if (code == 1) {
          code = 0;
        } else { }
        result.code = code;
        result.msg = stdout.msg;
        result.data = stdout.data;
      } else {
        result.code = 0;
        result.msg = '结算接口返回空';
      }
    } catch (e) {
      console.log(e.stack, "error.........................>");
      //日志记录
      logCtl.error({
        optitle: "请求薪必果接口异常error",
        op: "base/service/impl/utilscloudSve.js/" + methodName,
        content: rtn.stdout,
        clientIp: ""
      });
      result.code = -200;
      result.msg = '结算接口异常';
    }
    return result;
  }

  //..........................智薪云转账.............................................................结束

}
module.exports = utilsCloudSve;
