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");
const querystring = require('querystring');
var moment = require("moment");
const md5 = require("MD5");
class utilsTlBankSve {
  constructor() {
    this.wxMethod = "W01";//微信订单支付
    this.aliMethod = "A01";//阿里订单支付

    this.notifyUrl = "https://igirl.gongsibao.com/api/tl/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");
    this.tlorderDao = System.getObject("db.tlorderDao");

  }

  //-------------------------------------------h5支付-----------------开始

  /**
   * 唤起H5支付---只供简单应用
   * @param {*} company_id 公司ID
   * @param {*} pay_title 支付显示标题
   * @param {*} total_sum 支付金额
   * @param {*} order_no 订单号
   * @param {*} returl 支付成功后返回的url
   */
  async getH5Url(company_id, pay_title, total_sum, order_no, returl) {
    // appid:00000003,商户号（mch_id）:990440148166000,md5key（pay_key）:a0ea3fa20dbd7bb4d5abf1d59d63bae8
    var payParam = await this.companypayparamDao.getOneByCompanyId(company_id, 1);
    if (!payParam) {
      return { code: -210, msg: "公司没有对应的支付凭证" }
    }
    var timestamp = Date.now();
    var jsonObj = {
      appid: payParam.pay_appid,
      cusid: payParam.mch_id,
      version: 12,
      trxamt: total_sum,//单位为分
      reqsn: order_no,//order_num + "_" + company_id.toString(),
      charset: "UTF-8",
      returl: returl,
      notify_url: payParam.notifyUrl || this.notifyUrl,
      body: pay_title,
      remark: "h5paypagesywdy",
      randomstr: timestamp.toString()//随机字符串，不长于32位    
    }
    var param_result = await this.getReqBeforeParam(jsonObj, "1352105537612345789");
    if (param_result.code != 1) {
      return param_result;
    }
    var paramStr = Object.keys(jsonObj).sort().map(key => {
      return `${encodeURIComponent(key)}=${encodeURIComponent(jsonObj[key])}`
    }).join('&');

    return { code: 1, payUrl: "https://syb.allinpay.com/apiweb/h5unionpay/unionorder?" + paramStr };
  }



  //-------------------------------------------h5支付-----------------结束

  //----------------------------------------------------------------------------------------请求银行接口开始---------------------------------------------------

  /*
    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, 1);
    if (!payParam) {
      return { code: -210, msg: "公司没有对应的支付凭证" }
    }
    var reqMethod = this.wxMethod;
    if (opType == "alipay") {
      reqMethod = this.aliMethod;
    }
    var timestamp = Date.now();
    var jsonObj = {
      appid: payParam.pay_appid,
      cusid: payParam.mch_id,
      trxamt: total_fee,//单位为分
      reqsn: order_num + "_" + company_id.toString(),
      paytype: reqMethod,
      randomstr: timestamp.toString(),//随机字符串，不长于32位
      body: body_desc,
      notify_url: this.notifyUrl,
    }
    var param_result = await this.getReqBeforeParam(jsonObj, payParam.pay_key);
    if (param_result.code != 1) {
      return param_result;
    }
    var reqUrl = payParam.pay_url + "/pay";
    var result = await this.execReqInfo("getQrCode", reqUrl, param_result.req_param);
    if (result.code != 1) {
      return result;
    }
    var signResult = await this.resultSign(result.data, payParam.pay_key);
    if (signResult.code != 1) {
      return signResult;
    }
    result.data = {
      payinfo: result.data.payinfo,
      reqsn: result.data.reqsn,//商户订单号
      chnltrxid: result.data.chnltrxid,// 支付渠道交易单号,如支付宝,微信平台的交易单号
      trxid: result.data.trxid,// 交易单号,平台的交易流水号
      // 交易状态，0000：交易成功、1001：交易不存在、
      //2008或者2000 : 交易处理中,请查询交易,如果是实时交易(例如刷卡支付,交易撤销,退货),建议每隔一段时间(10秒)查询交易、
      //3888-流水号重复、其他3开头的错误码代表交易失败
      trxstatus: result.data.trxstatus,
      fintime: result.data.fintime,// 交易完成时间 yyyyMMddHHmmss
      errmsg: result.data.errmsg,// 错误原因
    };
    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, trxid) {//查询订单支付状态
    var payParam = await this.companypayparamDao.getOneByCompanyId(company_id, 1);
    if (!payParam) {
      return { code: -210, msg: "公司没有对应的支付凭证" }
    }
    var timestamp = Date.now();
    var jsonObj = {
      appid: payParam.pay_appid,
      cusid: payParam.mch_id,
      // reqsn: order_num + "_" + company_id.toString(),//reqsn和trxid必填其一
      trxid: trxid,//平台交易流水
      randomstr: timestamp.toString(),//随机字符串，不长于32位
    }
    var param_result = await this.getReqBeforeParam(jsonObj, payParam.pay_key);
    if (param_result.code != 1) {
      return param_result;
    }
    var reqUrl = payParam.pay_url + "/query";
    console.log(param_result.req_param, "data............");

    var result = await this.execReqInfo("queryOrder", reqUrl, param_result.req_param);
    if (result.code != 1) {
      return result;
    }

    var signResult = await this.resultSign(result.data, payParam.pay_key);
    if (signResult.code != 1) {
      return signResult;
    }
    result.data = {
      trxcode: result.data.trxcode,//交易类型，VSP501	微信支付、VSP511	支付宝支付
      trxamt: result.data.trxamt,//交易金额 单位为分
      reqsn: result.data.reqsn,//商户订单号
      chnltrxid: result.data.chnltrxid,// 支付渠道交易单号,如支付宝,微信平台的交易单号
      trxid: result.data.trxid,// 交易单号,平台的交易流水号
      // 交易状态，0000：交易成功、1001：交易不存在、
      //2008或者2000 : 交易处理中,请查询交易,如果是实时交易(例如刷卡支付,交易撤销,退货),建议每隔一段时间(10秒)查询交易、
      //3888-流水号重复、其他3开头的错误码代表交易失败
      trxstatus: result.data.trxstatus,
      fintime: result.data.fintime,// 交易完成时间 yyyyMMddHHmmss
      errmsg: result.data.errmsg,// 错误原因
    };
    return result;
  }

  async getReqBeforeParam(jsonObj, pay_key) {//获取请求前的参数信息
    jsonObj.key = pay_key;
    var reqResult = { code: 1, msg: "ok", req_param: null };
    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;
    }
    var signStr = signArr.join("&");
    var tmpSign = md5(signStr).toUpperCase();
    jsonObj.sign = tmpSign;
    delete jsonObj["key"];
    reqResult.req_param = jsonObj;
    return reqResult;
  }

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

  async execReqInfo(self_method_name, reqUrl, param) {
    try {
      var req_param = querystring.stringify(param);
      var rtn = await this.restClient.execPost2(req_param, reqUrl);
      var rtnResult = { code: 1, msg: "SUCCESS", data: {} };
      if (rtn && rtn.stdout) {
        var tmpResult = JSON.parse(rtn.stdout);
        if (tmpResult.retcode == "FAIL") {
          rtnResult.code = -400;
          rtnResult.msg = tmpResult.retmsg;
        } else {
          rtnResult.data = tmpResult;
        }
      } else {
        rtnResult.code = -410;
        rtnResult.msg = '请求结算接口返回空';
      }
      return rtnResult;
    } catch (e) {
      throw new Error(e.stack);
    }
  }

  async execOtherReqInfo(reqUrl, param) {
    try {
      var rtn = await this.restClient.execPost(param, reqUrl);
      var rtnResult = { code: 1, msg: "SUCCESS", data: {} };
      if (rtn && rtn.stdout) {
        var tmpResult = JSON.parse(rtn.stdout);
        if (tmpResult.code != 1) {
          rtnResult.code = tmpResult.code;
          rtnResult.msg = tmpResult.msg;
        }
      } else {
        rtnResult.code = -410;
        rtnResult.msg = '请求结算接口返回空';
      }
      return rtnResult;
    } catch (e) {
      throw new Error(e.stack);
    }
  }
  //----------------------------------------------------------------------------------------请求银行接口结束---------------------------------------------------

  async receiveCallBackNotify(parmas, client_ip) {//收到通联回调通知---post请求
    var result = "FAIL";
    try {
      logCtl.info({
        optitle: "通联回调信息记录------------info",
        op: "/base/service/impl/utilstlbankSve.js/receiveCallBackNotify",
        content: JSON.stringify(parmas),
        clientIp: client_ip
      });
      if (!parmas) {
        result = "回调parmas中参数信息为空";
        return result;
      }
      var isVerify = await this.verifyCallBackParams(parmas);
      if (isVerify) {
        result = isVerify;
        return result;
      }
      let attachList = [];
      if (parmas.cusorderid.indexOf("_") >= 0) {
        attachList = parmas.cusorderid.split("_");
      }
      else {
        attachList.push(parmas.cusorderid);
      }
      if (attachList.length < 2) {
        result = "回调cusorderid参数错误，没有_标识";
        return result;
      }
      var tmpCompanyId = attachList.length == 2 ? attachList[1] : attachList[2];

      var payParam = await this.companypayparamDao.getOneByCompanyId(tmpCompanyId, 1);
      if (!payParam) {
        result.return_msg = "回调公司没有对应的支付凭证";
        return jsonBuilder.buildObject(result);
      }
      var signResult = await this.resultSign(parmas, payParam.pay_key);
      if (signResult.code != 1) {
        result = signResult.msg;
        return result;
      }
      //解析支付参数
      parmas.out_trade_no = attachList[0];
      parmas.company_id = attachList.length == 2 ? attachList[1] : attachList[2];
      parmas.other_company_id = attachList.length == 2 ? "0" : attachList[1];
      //操作回调
      if (parmas.other_company_id && Number(parmas.other_company_id) > 0) {
        var otherPayParam = await this.companypayparamDao.getOneByCompanyId(parmas.other_company_id, 1);
        if (!otherPayParam) {
          result.return_msg = "回调其他公司公司没有对应的配置信息";
          return jsonBuilder.buildObject(result);
        }
        return await this.opOtherCompanyNotify(otherPayParam.notifyUrl, parmas, "通联回调");
      }//是别的公司则进行回调别的接口信息
      else {
        var backResult = await this.opBackNotify(parmas, "通联回调");
        if (backResult.code != 1) {
          result = backResult.msg;
          return result;
        }
        return result;
      }
    } catch (e) {
      logCtl.error({
        optitle: "通联回调业务处理---error异常",
        op: "web.js",
        content: "error：" + e.stack + "，参数=" + JSON.stringify(parmas),
        clientIp: client_ip
      });
      result = "回调业务处理---error异常";
      return result;
    }
  }
  async verifyCallBackParams(getParams) {//验证回调参数
    if (!getParams.trxcode) {
      return "回调trxcode参数为空";
    }
    if (getParams.trxcode != "VSP501" && getParams.trxcode != "VSP511") {
      return "回调trxcode值错误";
    }
    if (!getParams.trxstatus || getParams.trxstatus != "0000") {
      return "回调trxstatus信息为空或不等于0000";
    }
    if (!getParams.cusorderid) {
      return "回调商户订单号cusorderid参数为空";
    }
    return "";
  }
  async opBackNotify(getParams, opDesc) {//操作回调业务逻辑
    try {
      //日志记录
      logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "：支付回调信息=====" + opDesc + "，method=" + getParams.trxcode,
        op: "base/service/impl/utilszxbankSve.js/opBackNotify",
        content: JSON.stringify(getParams),
        clientIp: getParams.client_ip || ""
      });
      //获取充值业务锁
      var locker = await cacheManager["ZxPayLocker"].enter(getParams.trxid);
      if (locker && locker == "1") {
        if (getParams.trxcode == "VSP501") {
          getParams.req_accountType = "wx";
        } else {
          getParams.req_accountType = "alipay";
        }
        // if (getParams.method == "VSP511") {
        // getParams.req_accountType="alipay";
        // }
        return await this.notifyOpDb(getParams);
      }
      else {
        // await cacheManager["ZxPayLocker"].release(getParams.trxid);//---测试时放开
        logCtl.info({
          optitle: "通联回调操作频繁---太频繁了，太频繁了",
          op: "/app/config/routes/api.js",
          content: "参数=" + JSON.stringify(getParams),
          clientIp: getParams.client_ip || ""
        });
        return { code: -510, msg: "中信回调操作频繁---太频繁了，太频繁了" };
      }
    } catch (e) {
      await cacheManager["ZxPayLocker"].release(getParams.trxid);
      throw new Error(e.stack);
    }
  }
  async opOtherCompanyNotify(sveItemCode,orderNo){
    if(["zcdy3gy","zcdy6gy","zcdy1n"].indexOf(sveItemCode)>=0) {
      //TODO:操作别的公司回调
    }
  }
  async opOtherCompanyNotify(notifyUrl, getParams, opDesc) {//操作别的公司回调信息
    try {
      //日志记录
      logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "：支付回调信息=====" + opDesc + "，method=" + getParams.trxcode,
        op: "base/service/impl/utilszxbankSve.js/opOtherCompanyNotify",
        content: JSON.stringify(getParams),
        clientIp: getParams.client_ip || ""
      });

      //获取充值业务锁
      var locker = await cacheManager["ZxPayLocker"].enter(getParams.trxid);
      if (locker && locker == "1") {
        if (getParams.trxcode == "VSP501") {
          getParams.req_accountType = "wx";
        } else {
          getParams.req_accountType = "alipay";
        }
        // if (getParams.method == "VSP511") {
        // getParams.req_accountType="alipay";
        // }

        //更新订单状态
        var setField = { orderPayStatus: "yfk" };
        this.tlorderDao.updateByOrderNo(setField, getParams.out_trade_no);
        getParams.req_key = "sygyqbpogszc";
        var result = await this.execOtherReqInfo(notifyUrl, getParams);
        return result;
        // if (result.code != 1) {
        //   return result;
        // }
        // return result;
      }
      else {
        // await cacheManager["ZxPayLocker"].release(getParams.trxid);//---测试时放开
        logCtl.info({
          optitle: "通联回调opOtherCompanyNotify操作频繁---太频繁了，太频繁了",
          op: "/app/config/routes/api.js",
          content: "参数=" + JSON.stringify(getParams),
          clientIp: getParams.client_ip || ""
        });
        return { code: -510, msg: "回调操作频繁---太频繁了，太频繁了" };
      }
    } catch (e) {
      await cacheManager["ZxPayLocker"].release(getParams.trxid);
      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 = { code: obj.out_trade_no };
    var orderItem = await this.orderDao.model.findOne({
      where: sqlWheres,
      attributes: ["id", "code", "name","sveItemCode", "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;
    }
    //操作别的回调信息
    this.opOtherCompanyNotify(orderItem.sveItemCode,obj.out_trade_no);
    if (Number(orderItem.totalSum * 100) != Number(obj.trxamt)) {
      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" };
      if (orderItem.sveItemCode != "dlrfzzc" && orderItem.sveItemCode != "zzsbzc" && orderItem.sveItemCode != "dbsbzc") {
        // orderStatus: {//订单状态"1": "提交订单", "2": "待上传材料", "3": "待审核", "4": "审核不通过", "5": "待递交" , "6": "部分递交异常", "7": "已完成"
        putParams["orderStatus"] = "5";
        putParams.orderFlowStatus = "3";
      }
      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(3);
        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(3);
        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(3);
        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.chnltrxid,//支付凭证流水单号，如：微信支付凭证单号
      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,
      passTradeNo: obj.trxid || "",//通道的统一订单号

      // buyerOpenId: obj.openid || "",//用户在商户appid下的唯一标识或买家在支付宝的用户id
      // 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.chnltrxid,//支付凭证流水单号，如：微信支付凭证单号
      auditStatus: "tg",
      notes: nowTimeStr + "：" + obj.account_type_name + "收款进账",
      moneyaccount_id: opCompanyItem.moneyaccounts[0].id,
      createcompany_id: orderItem.company_id,
      passTradeNo: obj.trxid || "",//通道的统一订单号

      // buyerOpenId: obj.openid || "",//用户在商户appid下的唯一标识或买家在支付宝的用户id
      // 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(3);

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

    var ptTransferRate = Number(transferRate) - Number(bankTransferRate);
    ptTransferRate = ptTransferRate.toFixed(3);
    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 = utilsTlBankSve;
