var System = require("../../system");
var settings = require("../../../config/settings");
const uiconfig = System.getUiConfig2(settings.wxconfig.appId);
const logCtl = System.getObject("web.oplogCtl");
const cacheManager = System.getObject("db.cacheManager");
var moment = require("moment");
const xml2js = require('xml2js');
const md5 = require("MD5");
//商标查询操作
class utilsCloudSve {
  constructor() {
    this.reqZxBankUrl = "https://api.citicbankpay.com/pay/gateway";
    this.wxMethod = "mbupay.wxpay.native";//微信订单支付
    this.wxQueryMethod = "mbupay.wxpay.query";//微信订单查询
    this.aliMethod = "mbupay.alipay.native";//阿里订单支付
    this.aliQueryMethod = "mbupay.alipay.query";//阿里订单查询
    this.reqVersion = "2.0.1";

    this.notifyUrl = "http://igtest.gongsibao.com/api/zx/zxNotify";
    this.restClient = System.getObject("util.restClient");
    this.companypayparamDao = System.getObject("db.companypayparamDao");


    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");
  }
  //----------------------------------------------------------------------------------------请求银行接口开始---------------------------------------------------

  /*
    company_id:公司id、
    order_num：订单号、
    total_fee：订单金额单位为分、
    product_id：产品id、
    body_desc：内容描述（可以是产品名称）、
    create_ip：创建ip、
    opType：操作类型，1微信、2支付宝    
    返回错误码：成功为1
  返回错误码：成功为1
  -210：公司没有对应的支付凭证
  -230：请求参数信息为空
  -250：请求组装签名参数信息为空
  -280：请求结算接口返回失败

  -310：返回值信息data为空
  -230：返回值参数信息为空
  -250：返回值组装签名参数信息为空
  -280：返回值签名验证失败

  -400：请求接口请求返回值错误
  -410：请求结算接口返回空           
  */
  async getQrCode(company_id, order_num, total_fee, product_code, body_desc, create_ip, opType) {//获取微信支付二维码
    var payParam = await this.companypayparamDao.getOneByCompanyId(company_id, 2);
    if (!payParam) {
      return { code: -210, msg: "公司没有对应的支付凭证" }
    }
    var reqMethod = this.wxMethod;
    if (opType == "alipay") {
      reqMethod = this.aliMethod;
    }
    var timestamp = Date.now();
    var jsonAttach = { company_id: company_id, product_code: product_code };
    var jsonObj = {
      appid: payParam.pay_appid,
      body: body_desc,
      mch_id: payParam.mch_id,
      method: reqMethod,
      nonce_str: timestamp.toString(),//随机字符串，不长于32位
      notify_url: this.notifyUrl,
      out_trade_no: order_num,
      spbill_create_ip: create_ip || "127.0.0.1",
      // time_expire:,
      // time_start:,
      total_fee: total_fee,//单位为分
      version: this.reqVersion,
      attach: JSON.stringify(jsonAttach)//商家数据包，原样返回
      // wx_appid: ""//商户微信公众账号ID
    }
    var xml_param_result = await this.getReqBeforeXmlParam(jsonObj, payParam.pay_key);
    if (xml_param_result.code != 1) {
      return xml_param_result;
    }
    var result = await this.execReqInfo("getQrCode", reqMethod, xml_param_result.xml_param);
    if (result.code != 1) {
      return result;
    }
    if (result.data.return_code != "SUCCESS" || result.data.result_code != "SUCCESS") {
      result.code = -280;
      if (result.data.return_msg) {
        result.msg = result.data.return_msg;
      } else if (result.data.err_code_des) {
        result.msg = result.data.err_code_des;
      }
      result.data = {};
      return result;
    }
    var signResult = await this.resultSign(result.data, payParam.pay_key);
    if (signResult.code != 1) {
      return signResult;
    }
    result.data = {
      code_img_url: result.data.code_img_url,
      code_url: result.data.code_url
    };
    return result;
  }

  /*
  company_id:公司id、
  order_num：订单号、
  opType：操作类型，1微信、2支付宝   
  返回错误码：成功为1
  -210：公司没有对应的支付凭证
  -230：请求参数信息为空
  -250：请求组装签名参数信息为空
  -280：请求结算接口返回失败

  -310：返回值信息data为空
  -230：返回值参数信息为空
  -250：返回值组装签名参数信息为空
  -280：返回值签名验证失败
  
  -400：请求接口请求返回值错误
  -410：请求结算接口返回空    
  */
  async queryOrder(company_id, order_num, opType) {//查询订单支付状态
    var payParam = await this.companypayparamDao.getOneByCompanyId(company_id, 2);
    if (!payParam) {
      return { code: -210, msg: "公司没有对应的支付凭证" }
    }
    var reqMethod = this.wxQueryMethod;
    if (opType == "alipay") {
      reqMethod = this.aliQueryMethod;
    }
    var timestamp = Date.now();
    var jsonObj = {
      appid: payParam.pay_appid,
      mch_id: payParam.mch_id,
      method: reqMethod,
      nonce_str: timestamp.toString(),//随机字符串，不长于32位
      out_trade_no: order_num,
      version: this.reqVersion
    }
    var xml_param_result = await this.getReqBeforeXmlParam(jsonObj, payParam.pay_key);
    if (xml_param_result.code != 1) {
      return xml_param_result;
    }
    var result = await this.execReqInfo("queryOrder", reqMethod, xml_param_result.xml_param);
    if (result.code != 1) {
      return result;
    }
    if (result.data.return_code != "SUCCESS" || result.data.result_code != "SUCCESS") {
      result.code = -280;
      if (result.data.return_msg) {
        result.msg = result.data.return_msg;
      } else if (result.data.err_code_des) {
        result.msg = result.data.err_code_des;
      }
      result.data = {};
      return result;
    }
    var signResult = await this.resultSign(result.data, payParam.pay_key);
    if (signResult.code != 1) {
      return signResult;
    }
    result.data = {
      method: result.data.trade_type,
      trade_state: result.data.trade_state,
      out_trade_no: result.data.out_trade_no,
      transaction_id: result.data.transaction_id,
      total_fee: result.data.total_fee,
      openid: result.data.openid,
      pass_trade_no: result.data.pass_trade_no,
      buyer_logon_id: result.data.buyer_logon_id || "",

      // trade_type: result.data.trade_type
    };
    return result;
  }

  async getReqBeforeXmlParam(jsonObj, pay_key) {//获取请求前的xml参数信息
    var reqResult = { code: 1, msg: "ok", xml_param: "" };
    var signArr = [];
    var keys = Object.keys(jsonObj).sort();
    if (keys.length == 0) {
      reqResult.code = -230;
      reqResult.msg = "请求参数信息为空";
      return reqResult;
    }
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (tKey != "sign" && jsonObj[tKey]) {
        signArr.push(tKey + "=" + jsonObj[tKey]);
      }
    }
    if (signArr.length == 0) {
      reqResult.code = -250;
      reqResult.msg = "请求组装签名参数信息为空";
      return reqResult;
    }
    signArr.push("key=" + pay_key);
    var signStr = signArr.join("&");
    // console.log(signStr, "，signStr.......................");
    var tmpSign = md5(signStr).toUpperCase();
    // console.log(tmpSign, "tmpSign....................................");
    jsonObj.sign = tmpSign;
    var jsonBuilder = new xml2js.Builder({
      // rootName: '',
      xmldec: {
        version: '1.0',
        'encoding': 'UTF-8',
        'standalone': false
      }
    }); // jons -> xml
    reqResult.xml_param = jsonBuilder.buildObject(jsonObj);
    return reqResult;
  }

  async resultSign(resultData, pay_key) {//返回值进行验签
    var rtnResult = { code: 1, msg: "SUCCESS" };
    if (!resultData || !resultData.appid) {
      rtnResult.code = -310;
      rtnResult.msg = "返回值信息data为空";
    }
    var resultSignArr = [];
    var keys = Object.keys(resultData).sort();
    if (keys.length == 0) {
      rtnResult.code = -330;
      rtnResult.msg = "返回值参数信息为空";
    }
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (tKey != "sign" && resultData[tKey]) {
        resultSignArr.push(tKey + "=" + resultData[tKey]);
      }
    }
    if (resultSignArr.length == 0) {
      rtnResult.code = -350;
      rtnResult.msg = "返回值组装签名参数信息为空";
    }
    resultSignArr.push("key=" + pay_key);
    var resultSignStr = resultSignArr.join("&");
    console.log(resultSignStr, "resultSignStr.......................");
    var resultTmpSign = md5(resultSignStr).toUpperCase();
    console.log(resultTmpSign, "resultTmpSign....................................");
    if (resultData.sign != resultTmpSign) {
      rtnResult.code = -380;
      rtnResult.msg = "返回值签名验证失败";
    }
    return rtnResult;
  }

  async execReqInfo(self_method_name, channel_method_name, xml_param) {
    try {
      var rtn = await this.restClient.execPostXml(xml_param, this.reqZxBankUrl);
      console.log(rtn, "rtn.........................................!!!!!!!!!")
      var rtnResult = { code: 1, msg: "SUCCESS", data: {} };
      if (rtn && rtn.stdout) {
        var xmlParser = new xml2js.Parser({ explicitArray: false, ignoreAttrs: true }); // xml -> json
        xmlParser.parseString(rtn.stdout, function (err, result) {
          // console.log('xml解析成json:' + JSON.stringify(result));
          if (result.xml.return_code == "FAIL") {
            rtnResult.code = -400;
            rtnResult.msg = result.xml.return_msg;
            rtnResult.data = {
              return_code: result.xml.return_code
            };
          } else {
            rtnResult.data = result.xml;
          }
        });
      } else {
        rtnResult.code = -410;
        rtnResult.msg = '请求结算接口返回空';
      }
      return rtnResult;
    } catch (e) {
      throw new Error(e.stack);
    }
  }

  //----------------------------------------------------------------------------------------请求银行接口结束---------------------------------------------------

  async receiveCallBackNotify(reqBody, client_ip) {//收到中信银行回调通知
    var result = {
      "version": "2.0.1",
      "return_code": "FAIL",
      "return_msg": ""
    };
    var jsonBuilder = new xml2js.Builder({
      // rootName: '',
      xmldec: {
        version: '1.0',
        'encoding': 'UTF-8',
        'standalone': false
      }
    }); // jons -> xml
    try {
      logCtl.info({
        optitle: "中信回调信息记录------------info",
        op: "/base/service/impl/utilszxbankSve.js/receiveCallBackNotify",
        content: JSON.stringify(reqBody),
        clientIp: client_ip
      });
      if (!reqBody) {
        result.return_msg = "回调Body中参数信息为空";
        return jsonBuilder.buildObject(result);
      }
      var getParams = await this.getCallBackParams(reqBody);
      if (!getParams.out_trade_no) {
        result.return_msg = "回调Body中out_trade_no参数信息为空";
        return jsonBuilder.buildObject(result);
      }
      var isVerify = await this.verifyCallBackParams(getParams);
      if (isVerify) {
        result.return_msg = isVerify;
        return jsonBuilder.buildObject(result);
      }
      var attach = getParams.attach ? JSON.parse(getParams.attach) : "";
      if (!attach) {
        result.return_msg = "回调attach参数为空";
        return jsonBuilder.buildObject(result);
      }
      var payParam = await this.companypayparamDao.getOneByCompanyId(attach.company_id, 2);
      if (!payParam) {
        result.return_msg = "回调公司没有对应的支付凭证";
        return jsonBuilder.buildObject(result);
      }
      var signResult = await this.resultSign(getParams, payParam.pay_key);
      if (signResult.code != 1) {
        return signResult;
        result.return_msg = signResult.msg;
        return jsonBuilder.buildObject(result);
      }
      //操作回调
      var backResult = await this.opBackNotify(getParams, "中信回调");
      if (backResult.code != 1) {
        result.return_msg = backResult.msg;
        return jsonBuilder.buildObject(result);
      }
      result.return_code = "SUCCESS";
      result.return_msg = "OPERATION SUCCESS";
      return jsonBuilder.buildObject(result);
    } catch (e) {
      logCtl.error({
        optitle: "中信回调业务处理---error异常",
        op: "web.js",
        content: "error：" + e.stack + "，参数=" + JSON.stringify(reqBody),
        clientIp: client_ip
      });
      result.return_msg = "回调业务处理---error异常";
      return jsonBuilder.buildObject(result);
    }
  }
  async getCallBackParams(reqBody) {//获取回调参数信息
    var returnParams = {};
    var keys = Object.keys(reqBody).sort();
    for (let k = 0; k < keys.length; k++) {
      const tKey = keys[k];
      if (reqBody[tKey]) {
        returnParams[tKey] = reqBody[tKey][0];
      }
    }
    return returnParams;
  }
  async verifyCallBackParams(getParams) {//验证回调参数
    if (!getParams.method) {
      return "回调method参数为空";
    }
    if (getParams.method != "mbupay.alipay.native" && getParams.method != "mbupay.wxpay.native") {
      return "回调method值错误";
    }
    if (!getParams.return_code || getParams.return_code != "SUCCESS") {
      return "回调return_code信息为空或不等于SUCCESS";
    }
    if (!getParams.result_code || getParams.result_code != "SUCCESS") {
      return "回调result_code信息为空或不等于SUCCESS";
    }
    if (!getParams.out_trade_no) {
      return "回调out_trade_no参数为空";
    }
    return "";
  }
  async opBackNotify(getParams, opDesc) {//操作回调业务逻辑
    try {
      //日志记录
      logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "：支付回调信息=====" + opDesc + "，method=" + getParams.method,
        op: "base/service/impl/utilszxbankSve.js/opBackNotify",
        content: JSON.stringify(getParams),
        clientIp: getParams.client_ip || ""
      });
      //获取充值业务锁
      var locker = await cacheManager["ZxPayLocker"].enter(getParams.out_trade_no);
      if (locker && locker == "1") {
        if (getParams.method == "mbupay.wxpay.native") {
          getParams.req_accountType = "wx";
        } else {
          getParams.req_accountType = "alipay";
        }
        // if (getParams.method == "mbupay.alipay.native") {
        // getParams.req_accountType="alipay";
        // }
        return await this.notifyOpDb(getParams);
      }
      else {
        logCtl.info({
          optitle: "中信回调操作频繁---太频繁了，太频繁了",
          op: "/app/config/routes/api.js",
          content: "参数=" + JSON.stringify(getParams),
          clientIp: getParams.client_ip || ""
        });
        return { code: -410, msg: "中信回调操作频繁---太频繁了，太频繁了" };
      }
    } catch (e) {
      await cacheManager["ZxPayLocker"].release(getParams.out_trade_no);
      throw new Error(e.stack);
    }
  }

  /*
  返回值：
  -430：对应的业务支付订单号暂无
  -450：对应的订单支付金额不符
  -480：订单状态有误
  其余为事务处理会抛出异常
  */
  async notifyOpDb(obj) {
    var notifyResult = { code: 1, msg: "ok" };
    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 = {};
    if (obj.req_accountType == "wx") {
      sqlWheres.wxPayOrderCode = obj.out_trade_no;
    } else {
      sqlWheres.aliPayOrderCode = obj.out_trade_no;
    }

    var orderItem = await this.orderDao.model.findOne({
      where: sqlWheres,
      attributes: ["id", "code", "name", "busPayOrderCode", "totalSum", "orderStatus", "orderPayStatus", "company_id", "createuser_id", "sveItemCode", "sveItemName", "subType"],
      include: [
        { model: this.orderDao.db.models.customerinfo, attributes: ["businessLicensePic", "customerType", "identityCardNo", "identityCardPic"] }
      ]
    });
    if (!orderItem) {
      notifyResult.code = -430;
      notifyResult.msg = "对应的业务支付订单号暂无";
      return notifyResult;
    }
    if (Number(orderItem.totalSum * 100) != Number(obj.total_fee)) {
      notifyResult.code = -450;
      notifyResult.msg = "对应的订单支付金额不符";
      return notifyResult;
    }
    if (orderItem.orderPayStatus != "dfk") {
      notifyResult.code = -480;
      notifyResult.msg = "订单状态有误";
      return notifyResult;
    }
    var self = this;
    //平台与中信合作，平台与中信分润的平台收款账户-----------------------------------------------------------------------------------------------------------
    var platformBenefitBank = await self.companyDao.model.findOne({
      where: { id: 1 },
      attributes: ["id", "onlyCode", "companyType"],
      include: [
        {
          model: self.orderDao.db.models.moneyaccount,
          attributes: ["id", "code", "name", "balance", "transferRate", "bankToPtTransferRate"],
          where: { accountType: "bank", payeeName: "汉唐信通（北京）科技有限公司" }
        }
      ]
    });
    if (!platformBenefitBank) {
      throw new Error("平台分润收款账户的公司信息为空！！！");
    }
    if (!platformBenefitBank.moneyaccounts || platformBenefitBank.moneyaccounts.length == 0) {
      throw new Error("平台分润收款账户对应的信息为空！！！");
    }
    //平台与中信合作，平台与中信分润的中信收款账户-----------------------------------------------------------------------------------------------------------
    var platformZxBank = await self.companyDao.model.findOne({
      where: { id: 1 },
      attributes: ["id", "onlyCode", "companyType"],
      include: [
        {
          model: self.orderDao.db.models.moneyaccount,
          attributes: ["id", "code", "name", "balance", "transferRate", "bankToPtTransferRate"],
          where: { accountType: "bank", payeeName: "中信银行尚都国际中心支行" }
        }
      ]
    });
    if (!platformZxBank) {
      throw new Error("平台中信收款账户的公司信息为空！！！");
    }
    if (!platformZxBank.moneyaccounts || platformZxBank.moneyaccounts.length == 0) {
      throw new Error("平台中信收款账户信息为空！！！");
    }

    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 opComanyId = orderItem.subType == "platform" ? 1 : orderItem.company_id;
      //获取操作公司收款账户信息------------------------------------------------------------------------------------------------------------------
      var opCompanyItem = await self.companyDao.model.findOne({
        where: { id: opComanyId },
        attributes: ["id", "onlyCode", "companyType"],
        include: [
          {
            model: self.orderDao.db.models.moneyaccount,
            attributes: ["id", "code", "name", "balance", "transferRate", "bankToPtTransferRate"],
            where: { accountType: "bank", isPlatformAutopay: 1 }
          }
        ]
      });
      if (!opCompanyItem) {
        throw new Error("公司ID:" + opComanyId + "对应公司信息为空");
      }
      if (!opCompanyItem.moneyaccounts || opCompanyItem.moneyaccounts.length == 0) {
        throw new Error("公司ID:" + opComanyId + "对应的" + obj.account_type_name + "收款账户信息为空");
      }
      var receiptvoucherList = [];//收款单
      var moneyjourneyList = [];//账单  
      var expensevoucherList = [];//费用

      var opCompanyItemMoneynfo = {};
      var platformBenefitBankMoneyInfo = {};
      var platformZxBankMoneyInfo = {};
      //操作公司
      await self.opComanyAccountBill(opComanyId, opCompanyItem, obj, orderItem, receiptvoucherList, moneyjourneyList, opCompanyItemMoneynfo);
      //操作服务费
      await self.opServiceCharge(opComanyId, obj, opCompanyItem, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList,
        opCompanyItemMoneynfo, platformBenefitBank, platformZxBank, platformBenefitBankMoneyInfo, platformZxBankMoneyInfo);

      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);
      }
      //-----------------------------------------操作账户开始----------------------------------------
      if (opCompanyItemMoneynfo && opCompanyItemMoneynfo.company_id && opCompanyItemMoneynfo.moneyaccount_id) {
        var pfMoneyTotal = parseFloat(opCompanyItemMoneynfo.moneyTotal || 0);
        pfMoneyTotal = pfMoneyTotal.toFixed(2);
        var pfOldMoneyTotal = Number(opCompanyItemMoneynfo.oldMoneyTotal || 0);
        if (pfMoneyTotal > 0 && pfMoneyTotal > pfOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: pfMoneyTotal },
            { where: { company_id: opCompanyItemMoneynfo.company_id, id: opCompanyItemMoneynfo.moneyaccount_id } }, t);
        }
      }
      if (platformBenefitBankMoneyInfo && platformBenefitBankMoneyInfo.company_id && platformBenefitBankMoneyInfo.moneyaccount_id) {
        var pfBankMoneyTotal = parseFloat(platformBenefitBankMoneyInfo.moneyTotal || 0);
        pfBankMoneyTotal = pfBankMoneyTotal.toFixed(2);
        var pfBankOldMoneyTotal = Number(platformBenefitBankMoneyInfo.oldMoneyTotal || 0);
        if (pfBankMoneyTotal != pfBankOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: pfBankMoneyTotal },
            { where: { company_id: platformBenefitBankMoneyInfo.company_id, id: platformBenefitBankMoneyInfo.moneyaccount_id } }, t);
        }
      }
      if (platformZxBankMoneyInfo && platformZxBankMoneyInfo.company_id && platformZxBankMoneyInfo.moneyaccount_id) {
        var pfBankMoneyTotal = parseFloat(platformZxBankMoneyInfo.moneyTotal || 0);
        pfBankMoneyTotal = pfBankMoneyTotal.toFixed(2);
        var pfBankOldMoneyTotal = Number(platformZxBankMoneyInfo.oldMoneyTotal || 0);
        if (pfBankMoneyTotal != pfBankOldMoneyTotal) {
          await self.moneyaccountDao.updateByWhere({ balance: pfBankMoneyTotal },
            { where: { company_id: platformZxBankMoneyInfo.company_id, id: platformZxBankMoneyInfo.moneyaccount_id } }, t);
        }
      }
      //-----------------------------------------操作账户结束----------------------------------------
    });
    notifyResult.data = {
      "busPayOrderCode": orderItem.busPayOrderCode,
      "code": orderItem.code,
      "company_id": orderItem.company_id,
      "name": orderItem.name,
      "sveItemCode": orderItem.sveItemCode,
      "sveItemName": orderItem.sveItemName,
      "totalSum": orderItem.totalSum,
      "orderPayStatus": "yfk",
    }
    return notifyResult;
  }

  //操作公司帐户金额信息
  async opComanyAccountBill(opComanyId, opCompanyItem, obj, orderItem, receiptvoucherList, moneyjourneyList, opCompanyItemMoneynfo) {
    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    var skCode = await logCtl.getBusUid_Ctl("sk");
    receiptvoucherList.push({
      company_id: opComanyId,//操作公司id
      code: skCode,
      createuser_id: orderItem.createuser_id,//第三方公司订单创建者
      auditStatus: "tg",
      sourceType: "order",
      sourceOrderNo: orderItem.code,
      busPayOrderCode: obj.out_trade_no,//业务支付订单号
      payOrderNo: obj.transaction_id,//支付凭证流水单号，如：微信支付凭证单号
      receiptType: "sk",
      accountType: obj.req_accountType,
      payDate: new Date(),
      payFlowType: 1,
      totalSum: orderItem.totalSum,
      notes: nowTimeStr + "：" + obj.account_type_name + "收款进账",
      moneyaccount_id: opCompanyItem.moneyaccounts[0].id,
      sveItemCode: orderItem.sveItemCode,//项目操作码
      sveItemName: orderItem.sveItemName,//项目名称
      createcompany_id: orderItem.company_id,
      buyerOpenId: obj.openid || "",//用户在商户appid下的唯一标识或买家在支付宝的用户id
      passTradeNo: obj.pass_trade_no || "",//通道的统一订单号
      buyerAliLogonId: obj.buyer_logon_id || "",//买家支付宝账号
    });
    moneyjourneyList.push({
      company_id: opComanyId,//操作公司id      
      code: skCode,
      createuser_id: orderItem.createuser_id,//第三方公司订单创建者
      accountType: obj.req_accountType,
      directionType: "sr",//凭单类型,"sr": "收","zc": "支"
      voucherDate: new Date(),
      recvAmount: orderItem.totalSum,
      sourceType: "receiptvoucher",
      sourceOrderNo: orderItem.code,
      busPayOrderCode: obj.out_trade_no,//业务支付订单号
      payOrderNo: obj.transaction_id,//支付凭证流水单号，如：微信支付凭证单号
      auditStatus: "tg",
      notes: nowTimeStr + "：" + obj.account_type_name + "收款进账",
      moneyaccount_id: opCompanyItem.moneyaccounts[0].id,
      createcompany_id: orderItem.company_id,
      buyerOpenId: obj.openid || "",//用户在商户appid下的唯一标识或买家在支付宝的用户id
      passTradeNo: obj.pass_trade_no || "",//通道的统一订单号
      buyerAliLogonId: obj.buyer_logon_id || "",//买家支付宝账号
    });
    opCompanyItemMoneynfo["company_id"] = opComanyId;
    opCompanyItemMoneynfo["moneyaccount_id"] = opCompanyItem.moneyaccounts[0].id;
    opCompanyItemMoneynfo["oldMoneyTotal"] = Number(opCompanyItem.moneyaccounts[0].balance || 0);
    opCompanyItemMoneynfo["moneyTotal"] = Number(opCompanyItem.moneyaccounts[0].balance || 0) + Number(orderItem.totalSum);
  }

  //操作服务费
  async opServiceCharge(opComanyId, obj, opCompanyItem, orderItem, receiptvoucherList, moneyjourneyList, expensevoucherList,
    opCompanyItemMoneynfo, platformBenefitBank, platformZxBank, platformBenefitBankMoneyInfo, platformZxBankMoneyInfo) {

    var nowTimeStr = (new Date()).Format("yyyy-MM-dd hh:mm:ss");
    var transferRate = (Number(orderItem.totalSum) * Number(opCompanyItem.moneyaccounts[0].transferRate || "0") / 1000);
    transferRate = isNaN(transferRate) ? 0 : transferRate.toFixed(2);

    var bankTransferRate = (Number(orderItem.totalSum) * Number(opCompanyItem.moneyaccounts[0].bankToPtTransferRate || "0") / 1000);
    bankTransferRate = isNaN(bankTransferRate) ? 0 : bankTransferRate.toFixed(2);

    var ptTransferRate = Number(transferRate) - Number(bankTransferRate);
    ptTransferRate = ptTransferRate.toFixed(2);
    if (Number(ptTransferRate) > 0) {
      //-------------------------------------------------------操作公司-----------------------------------------------------------------
      var sxfCode = await logCtl.getBusUid_Ctl("sxf");
      expensevoucherList.push({
        company_id: opComanyId,//操作公司id
        createuser_id: orderItem.createuser_id,
        code: sxfCode,
        sourceType: "order",
        sourceOrderNo: orderItem.code,
        expenseType: "sxf",
        totalSum: transferRate,
        auditStatus: "tg",
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费扣除",
        moneyaccount_id: opCompanyItem.moneyaccounts[0].id,
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      moneyjourneyList.push({
        company_id: opComanyId,//操作公司id
        createuser_id: orderItem.createuser_id,
        code: sxfCode,
        accountType: obj.req_accountType,
        directionType: "zc",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        payAmount: transferRate,
        sourceType: "expensevoucher",
        sourceOrderNo: orderItem.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费扣除",
        moneyaccount_id: opCompanyItem.moneyaccounts[0].id,
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      //减去操作公司对应的biz_moneyaccount表中的余额
      opCompanyItemMoneynfo["moneyTotal"] = Number(opCompanyItemMoneynfo["moneyTotal"]) - Number(transferRate);
      //-------------------------------------------------------平台与中信分润的中信收款账户-------------------------------------------------
      var zxCode = await logCtl.getBusUid_Ctl("zx");
      receiptvoucherList.push({
        company_id: platformZxBank.id,
        code: zxCode,
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        auditStatus: "tg",
        sourceType: "order",
        sourceOrderNo: orderItem.code,
        receiptType: "sk",
        accountType: "bank",
        payDate: new Date(),
        payFlowType: 1,
        totalSum: bankTransferRate,
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费进账",
        moneyaccount_id: platformZxBank.moneyaccounts[0].id,
        sveItemCode: orderItem.sveItemCode,//项目操作码
        sveItemName: orderItem.sveItemName,//项目名称
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      moneyjourneyList.push({
        company_id: 1,
        createuser_id: orderItem.createuser_id,
        code: zxCode,
        accountType: "bank",
        directionType: "sr",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        recvAmount: bankTransferRate,
        sourceType: "receiptvoucher",
        sourceOrderNo: orderItem.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费进账",
        moneyaccount_id: platformZxBank.moneyaccounts[0].id,
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      platformZxBankMoneyInfo["company_id"] = platformZxBank.id;
      platformZxBankMoneyInfo["moneyaccount_id"] = platformZxBank.moneyaccounts[0].id;
      platformZxBankMoneyInfo["oldMoneyTotal"] = Number(platformZxBank.moneyaccounts[0].balance || 0);
      platformZxBankMoneyInfo["moneyTotal"] = Number(platformZxBank.moneyaccounts[0].balance || 0) + Number(bankTransferRate);
      //-------------------------------------------------------平台与中信分润的平台收款账户-------------------------------------------------
      var ptSkCode = await logCtl.getBusUid_Ctl("psk");
      receiptvoucherList.push({
        company_id: platformBenefitBank.id,//公司id
        code: ptSkCode,
        createuser_id: orderItem.createuser_id,//第三方公司订单创建者
        auditStatus: "tg",
        sourceType: "order",
        sourceOrderNo: orderItem.code,
        receiptType: "sk",
        accountType: "bank",
        payDate: new Date(),
        payFlowType: 1,
        totalSum: ptTransferRate,
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费进账",
        moneyaccount_id: platformBenefitBank.moneyaccounts[0].id,
        sveItemCode: orderItem.sveItemCode,//项目操作码
        sveItemName: orderItem.sveItemName,//项目名称
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      moneyjourneyList.push({
        company_id: platformBenefitBank.id,//公司id
        createuser_id: orderItem.createuser_id,
        code: ptSkCode,
        accountType: "bank",
        directionType: "sr",//凭单类型,"sr": "收","zc": "支"
        voucherDate: new Date(),
        recvAmount: ptTransferRate,
        sourceType: "receiptvoucher",
        sourceOrderNo: orderItem.code,
        auditStatus: "tg",
        notes: nowTimeStr + "：" + obj.account_type_name + "收款手续费进账",
        moneyaccount_id: platformBenefitBank.moneyaccounts[0].id,
        createcompany_id: orderItem.company_id,
        busPayOrderCode: obj.out_trade_no,//业务支付订单号
      });
      platformBenefitBankMoneyInfo["company_id"] = platformBenefitBank.id;
      platformBenefitBankMoneyInfo["moneyaccount_id"] = platformBenefitBank.moneyaccounts[0].id;
      platformBenefitBankMoneyInfo["oldMoneyTotal"] = Number(platformBenefitBank.moneyaccounts[0].balance || 0);
      platformBenefitBankMoneyInfo["moneyTotal"] = Number(platformBenefitBank.moneyaccounts[0].balance || 0) + Number(ptTransferRate);

    }
  }
}
module.exports = utilsCloudSve;
