const system = require("../../../system");
var settings = require("../../../../config/settings");
const querystring = require('querystring');
const AppServiceBase = require("../../app.base");
const axios = require('axios')
const md5 = require('md5')
class UtilsOrderService extends AppServiceBase {
  constructor() {
    super();
    this.utilsPushSve = system.getObject("service.utilsSve.utilsPushSve");
    this.logCtl = system.getObject("service.common.oplogSve");
    this.centerOrderUrl = settings.centerOrderUrl();
    this.qifuPayAfterH5JumpUrl = settings.qifuPayAfterH5JumpUrl();
    this.qifuPayAfterPcJumpUrl = settings.qifuPayAfterPcJumpUrl();
    this.qifuH5PayNotifyUrl = settings.qifuH5PayNotifyUrl();
    this.centerAppUrl = settings.centerAppUrl();
    this.centerAppPayUrl = settings.centerAppUrl() + "payment/paymentApi/springBoard";
    this.paySecret = settings.paySecret()
  };
  /*
* 订单验证
*/
  async isOrderVerify(pobj, actionBody) {
    var price_list = actionBody.product_info.price_list;
    if (!price_list) {
      return system.getResult(null, "产品价格列表信息有误，100040");
    }
    var productIndex = price_list.findIndex(f => f.pay_code == actionBody.payCode && f.is_show == 1);
    if (productIndex < 0) {
      return system.getResult(null, "支付价格payCode信息有误，100050");
    }
    var totalSum = Number(price_list[productIndex].price) * Number(actionBody.quantity);
    var additions = null;
    var additionsIndex = -1;
    if (actionBody.additions && actionBody.additions.payCode) {
      additionsIndex = price_list.findIndex(f => f.pay_code == actionBody.additions.payCode && f.is_show == 0);
      if (additionsIndex >= 0) {
        totalSum = totalSum + Number(price_list[additionsIndex].price) * Number(actionBody.additions.quantity);
      }
    }
    var buyTotalSum = Number(actionBody.totalSum || 0);
    var buyPayTotalSum = Number(actionBody.payTotalSum || 0);
    if (buyTotalSum == 0) {
      actionBody.totalSum = totalSum;
    }
    if (buyPayTotalSum == 0) {
      actionBody.payTotalSum = totalSum;
    }
    console.log("buyTotalSum",buyTotalSum)
    console.log("totalSum",totalSum)
    if (buyTotalSum < totalSum) {
      return system.getResult(null, "订单金额有误，100060");
    }
    pobj.actionBody.product_info.price_item = price_list[productIndex];
    if (additionsIndex >= 0) {
      pobj.actionBody.product_info.price_additions_item = price_list[additionsIndex];
    }
    return system.getResultSuccess();
  }
  /**
   * 创建订单
   * @param {*} pobj
   * @param {*} actionBody {channelItemCode:渠道产品的编码，id:定价id,quantity:订单数量,totalSum:300}
   */
  async addOrder(pobj, actionBody) {
    if (!actionBody.channelItemCode) {
      return system.getResult(null, "产品编码有误，100010");
    }
    if (!actionBody.payCode) {
      return system.getResult(null, "支付价格payCode不能为空，100020");
    }
    if (!actionBody.quantity || Number(actionBody.quantity) <= 0) {
      return system.getResult(null, "订单数量为空或有误，100030");
    }
    pobj.actionType = "getProductDetail";
    var url = settings.centerAppUrl() + "action/opProduct/springBoard";
    var productItemResult = await this.restPostUrl(pobj, url);
    if (productItemResult.status != 0) {
      return productItemResult;
    }
    pobj.actionBody.product_info = productItemResult.data;
    var verifyResult = await this.isOrderVerify(pobj, pobj.actionBody);
    if (verifyResult.status != 0) {
      return verifyResult;
    }
    pobj.actionType = "getProductInterface";
    pobj.actionBody.product_id = pobj.actionBody.product_info.id;
    var productItemInterfaceResult = await this.restPostUrl(pobj, url);
    pobj.actionBody.product_info.interface_info = productItemInterfaceResult.data;

    pobj.actionType = "addOrder";
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    // console.log(pobj);
    var result = await this.restPostUrl(pobj, reqUrl);
    result.totalSum = actionBody.totalSum;
    return result;
  }
  async delOrder(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100025");
    }
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderInfo(pobj, actionBody) {
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderDetails(pobj, actionBody) {
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderDeliveryInfo(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100290");
    }
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderDeliveryFlowInfo(pobj, actionBody) {
    if (!actionBody.sourceOrderNo) {
      return system.getResult(null, "actionBody.sourceOrderNo can not be empty，100300");
    }
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderDeliveryFlowList(pobj, actionBody) {
    if (!actionBody.sourceOrderNoList) {
      return system.getResult(null, "actionBody.sourceOrderNoList can not be empty，100070");
    }
    if (actionBody.sourceOrderNoList.length == 0) {
      return system.getResult(null, "actionBody.sourceOrderNoList length can not be empty，100080");
    }
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async getOrderLogInfo(pobj, actionBody) {
    if (!actionBody.sourceOrderNo) {
      return system.getResult(null, "actionBody.sourceOrderNo can not be empty，100090");
    }
    var reqUrl = this.centerOrderUrl + "action/order/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  async icOrderStatusNotify(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100100");
    }
    var reqUrl = this.centerOrderUrl + "notifyaction/oporder/springBoard";
    var result = await this.restPostUrl(pobj, reqUrl);
    return result;
  }
  /**
   * 获取H5支付地址
   * @param {*} pobj
   * @param {*} actionBody
   */
  async getH5PayUrl(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100110");
    }
    pobj.actionType = "getPayOrderInfo";
    var orderUrl = settings.centerOrderUrl() + "action/order/springBoard";
    var orderResult = await this.restPostUrl(pobj, orderUrl);
    if (orderResult.status != 0) {
      return orderResult;
    }
    pobj.actionBody.body_desc = orderResult.data.orderProduct.channelItemName;
    pobj.actionBody.total_fee = Number(orderResult.data.receiptVoucher.totalSum) * 100;
    pobj.actionBody.order_num = orderResult.data.receiptVoucher.sourceOrderNo;
    pobj.actionBody.returl = orderResult.data.orderProduct.payAfterJumpH5Url || this.qifuPayAfterH5JumpUrl;
    pobj.actionBody.notify_url = this.qifuH5PayNotifyUrl;
    pobj.actionType = "getH5PayUrl";

    var result = await this.restPostUrl(pobj, this.centerAppPayUrl);
    if (result.status != 0) {
      return result;
    }
    await this.cacheManager["TlPayLocker"].init(orderResult.data.receiptVoucher.sourceOrderNo);
    return result;
  }
  /**
   * 获取二维码
   * @param {*} pobj
   * @param {*} actionBody {orderNo:XXXX,opType:"wx"}---"wx":"微信","alipay":"支付宝"
   */
  async getOrderQrCode(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100120");
    }
    pobj.actionType = "getPayOrderInfo";
    var orderUrl = settings.centerOrderUrl() + "action/order/springBoard";
    var orderResult = await this.restPostUrl(pobj, orderUrl);
    if (orderResult.status != 0) {
      return orderResult;
    }
    //查询支付流水号是否已经支付
    var receiptVoucher = orderResult.data.receiptVoucher;
    pobj.actionType = "queryOrderStatus";
    var url = this.centerAppUrl + "payment/paymentApi/queryOrder";
    if (receiptVoucher.busPayOrderCode != receiptVoucher.wxPayOrderCode) {
      pobj.actionBody.trxid = wxPayOrderCode;
      var wxPayStatus = await this.restPostUrl(pobj, url);
      if (wxPayStatus && wxPayStatus.code == 1 && wxPayStatus.data.trxstatus == "0000") {
        return system.getResultFail(-100130, "订单已支付，请勿重复付款，100130");
      }
    }
    if (receiptVoucher.busPayOrderCode != receiptVoucher.aliPayOrderCode) {
      pobj.actionBody.trxid = aliPayOrderCode;
      var aliPayStatus = await this.restPostUrl(pobj, url);
      if (aliPayStatus && aliPayStatus.code == 1 && aliPayStatus.data.trxstatus == "0000") {
        return system.getResultFail(-100140, "订单已支付，请勿重复付款，100140");
      }
    }

    // pobj.actionBody.body_desc, pobj.actionBody.total_fee, pobj.actionBody.order_num, pobj.actionBody.op_type
    pobj.actionBody.body_desc = orderResult.data.orderProduct.channelItemName;
    pobj.actionBody.total_fee = Number(receiptVoucher.totalSum) * 100;
    pobj.actionBody.order_num = receiptVoucher.sourceOrderNo;
    pobj.actionBody.op_type = actionBody.opType;
    pobj.actionType = "getOrderQrCode";

    var result = await this.restPostUrl(pobj, this.centerAppPayUrl);
    if (result.status != 0) {
      return result;
    }
    //更新DB付款信息
    var isPut = 0;
    var setField = {};
    if (opType == "wx") {
      if (actionBody.trxid != receiptVoucher.wxPayOrderCode) {
        setField.wxPayOrderCode = tResult.data.trxid;
        receiptVoucher.wxPayOrderCode = tResult.data.trxid;
        isPut = 1;
      }
    } else {
      //支付宝
      if (actionBody.trxid != receiptVoucher.aliPayOrderCode) {
        setField.aliPayOrderCode = tResult.data.trxid;
        receiptVoucher.aliPayOrderCode = tResult.data.trxid;
        isPut = 1;
      }
    }
    pobj.actionBody.isPut;
    pobj.actionBody.setField = setField;
    pobj.actionBody.receiptVoucherId = receiptVoucher.id;
    pobj.actionBody.trxid = result.data.trxid;
    pobj.actionType = "putReceiptVoucherInfo";
    var putOrderResult = await this.restPostUrl(pobj, orderUrl);
    if (putOrderResult.status != 0) {
      return putOrderResult;
    }
    if (isPut > 0) {
      await this.cacheManager["TlPayLocker"].init(receiptVoucher.sourceOrderNo);
    }
    result.wxPayOrderCode = receiptVoucher.wxPayOrderCode;
    result.aliPayOrderCode = receiptVoucher.aliPayOrderCode;
    return result;
  }
  /**
   * 查询订单状态
   * @param {*} pobj
   * @param {*} actionBody {orderNo:XXXX,opType:"wx"}---"wx":"微信","alipay":"支付宝"
   */
  async queryOrderStatus(pobj, actionBody) {
    if (!actionBody.orderNo) {
      return system.getResult(null, "actionBody.orderNo can not be empty，100150");
    }
    if (!actionBody.opType) {
      return system.getResult(null, "actionBody.opType can not be empty，100160");
    }
    pobj.actionType = "getPayOrderInfo";
    var orderUrl = settings.centerOrderUrl() + "action/order/springBoard";
    var orderResult = await this.restPostUrl(pobj, url);
    if (orderResult.status != 0) {
      return orderResult;
    }
    //检查流水号是否已经支付
    var receiptVoucher = orderResult.data.receiptVoucher;
    var payTrxid = opType == "wx" ? receiptVoucher.wxPayOrderCode : receiptVoucher.aliPayOrderCode;
    pobj.actionBody.trxid = payTrxid;
    pobj.actionType = "queryOrderStatus";

    var payStatus = await this.restPostUrl(pobj, this.centerAppPayUrl);

    if (payStatus.data && payStatus.data.trxstatus == "0000") {
      //TODO:处理支付成功的业务逻辑
      // payStatus.data.client_ip = obj.client_ip || "";
      // let attachList = [];
      // if (payStatus.data.reqsn.indexOf("_") >= 0) {
      //   attachList = payStatus.data.reqsn.split("_");
      // }
      // else {
      //   attachList.push(payStatus.data.reqsn);
      // }
      // if (attachList.length != 2) {
      //   return {  -120, msg: "reqsn参数错误，没有_标识" };
      // }
      // payStatus.data.out_trade_no = attachList[0];
      // payStatus.data.company_id = attachList[1];
      // return await this.utilstlbankSve.opBackNotify(payStatus.data, "页面回调");
    }
    else if (payStatus.data && payStatus.data.trxstatus == "3045") {
      return system.getResultFail(-100170, "超时未支付，请刷新页面，100170");
    }
    return system.getResultFail(-100180, "请及时支付，100180");
  }
  /**
   * 获取pc端支付二维码--不跟订单关联
   * @param {*} pobj
   * @param {*} actionBody
   * "actionBody": {
        "order_num": order.orderNo,
        "total_fee": Number(order.totalSum) * 100,
        "body_desc": order.itemName,
        "op_type": obj.opType
      }
   */
  async getQrCode(pobj, actionBody) {
    if (!actionBody.order_num) {
      return system.getResult(null, "actionBody.order_num can not be empty，100190");
    }
    if (!actionBody.total_fee) {
      return system.getResult(null, "actionBody.total_fee can not be empty，100200");
    }
    if (!actionBody.body_desc) {
      return system.getResult(null, "actionBody.body_desc can not be empty，100210");
    }
    if (!actionBody.op_type) {
      return system.getResult(null, "actionBody.op_type can not be empty，100220");
    }
    if (actionBody.op_type != "wx" && actionBody.op_type != "alipay") {
      return system.getResult(null, "actionBody.op_type param error，100230");
    }

    return await this.restPostUrl(pobj, this.centerAppPayUrl);
  }
  /**
   * 只是检查支付状态--不跟订单关联
   * @param {*} pobj
   * @param {*} actionBody { "trxid": payTrxid 支付流水号}
   */
  async queryOrder(pobj, actionBody) {
    if (!actionBody.trxid) {
      return system.getResult(null, "actionBody.trxid can not be empty，100240");
    }

    return await this.restPostUrl(pobj, this.centerAppPayUrl);
  }
  async receiveCallBackNotify(parmas, client_ip) {
    try {
      if (!parmas || !parmas.trxcode) {
        return system.getResult(null, "回调parmas中参数信息为空，100250");
      }
      //日志记录
      this.logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "记录回调参数：，method=" + parmas.trxcode,
        op: "service/impl/utilsSve/utilsOrderSve.js/receiveCallBackNotify",
        content: JSON.stringify(parmas),
        clientIp: client_ip || ""
      });
      var param = {
        "actionBody": { parmas: parmas },
        "client_ip": client_ip
      };
      var qftstr = await this.restClient.execPost(param, this.centerAppUrl + "payment/paymentApi/receiveCallBackNotify");
      if (!qftstr.stdout) {
        return system.getResult(null, "回调app中receiveCallBackNotify方法返回信息为空，100255");
      }
      var qftjson = JSON.parse(qftstr.stdout);
      return qftjson;
    } catch (e) {
      this.logCtl.error({
        optitle: "回调业务处理---error异常",
        op: "center-app/app/base/service/impl/utilsSve/utilstlbankSve.js/receiveCallBackNotify",
        content: "参数=" + JSON.stringify(parmas) + "，error：" + e.stack,
        clientIp: client_ip || ""
      });
      return system.getResultFail(-200, e.stack);
    }
  }

  async opBackNotify(parmas, client_ip) { //操作回调业务逻辑
    try {
      if (!parmas.uappid) {
        return system.getResult(null, "uappid参数不能为空，100260");
      }
      //日志记录
      this.logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "回调处理订单参数：，method=" + parmas.trxcode,
        op: "service/impl/utilsSve/utilsOrderSve.js/opBackNotify",
        content: JSON.stringify(parmas),
        clientIp: client_ip || ""
      });

      var url = this.centerAppUrl + "payment/paymentApi/getAppInfo";
      var opResult = await this.restPostUrl({ uappId: parmas.uappid }, url);
      if (opResult.status != 0) {
        opResult.msg = opResult.msg + "，100270";
        return opResult;
      }
      var appInfo = opResult.data;
      var resultSign = await this.verifySign(parmas, appInfo.uapp_secret);
      if (!resultSign || resultSign.status != 0) {
        return resultSign;
      }
      //获取充值业务锁
      // await this.cacheManager["TlPayLocker"].init(parmas.out_trade_no);//---测试时放开
      var locker = await this.cacheManager["TlPayLocker"].enter(parmas.out_trade_no);
      if (!locker || locker != "1") {
        this.logCtl.info({
          appid: appInfo.uapp_id,
          appkey: appInfo.uapp_key,
          op: "service/impl/utilsSve/utilsOrderSve.js/opBackNotify",
          content: "参数=" + JSON.stringify(parmas),
          clientIp: parmas.client_ip || "",
          optitle: "通联回调操作频繁---太频繁了，太频繁了"
        });
        return system.getResultFail(-200, "回调操作频繁---太频繁了，太频繁了");
      }
      if (parmas.trxcode == "VSP501") {
        parmas.pay_type = "wx";
      } else {
        parmas.pay_type = "alipay";
      }
      parmas.appInfo = appInfo;
      parmas.orderNo = parmas.out_trade_no;
      //修改并返回订单支付状态，创建收款单
      var url = this.centerOrderUrl + "opaction/opPayOrder/receivePayCallBackNotify";
      var opResult = await this.restPostUrl(parmas, url);
      if (opResult.status == 0) {
        opResult.data.appInfo = {
          uapp_id: appInfo.uapp_id,
          uapp_key: appInfo.uapp_key,
          app_code: appInfo.app_code,
          app_name: appInfo.app_name
        }; 
        opResult.data.userInfo = {
          channel_userid: opResult.data.order_info.channelUserId,
          channel_username: opResult.data.order_info.channelUserId,
          channel_nickname: opResult.data.order_info.channelUserId
        };
        var pobj = {
          appInfo: opResult.data.appInfo,
          actionBody: opResult.data
        }
        // this.utilsPushSve.pushBusInfo(opResult.data, "pushOrderBusiness",0);
        this.utilsPushSve.pushBusInfo(pobj, "pushOrder", 0);
      }
      opResult.data = null;
      return opResult;

    } catch (e) {
      await this.cacheManager["TlPayLocker"].release(parmas.out_trade_no);
      this.logCtl.error({
        optitle: "回调处理订单---error异常",
        op: "center-app/app/base/service/impl/utilsSve/utilstlbankSve.js/opBackNotify",
        content: "参数=" + JSON.stringify(parmas) + "，error：" + e.stack,
        clientIp: client_ip || ""
      });
      return system.getResultFail(-200, e.stack);
    }
  }
  async opH5AliDingPayBackNotify(parmas, client_ip) { //操作回调业务逻辑
    try {
      //日志记录
      this.logCtl.info({
        optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "阿里钉钉支付回调参数信息",
        op: "service/impl/utilsSve/utilsOrderSve.js/opH5AliDingPayBackNotify",
        content: JSON.stringify(parmas),
        clientIp: client_ip || ""
      });
      if (!parmas.trade_status) {
        return system.getResult(null, "trade_status参数不能为空，100470");
      }
      if (parmas.trade_status != "TRADE_FINISHED" && parmas.trade_status != "TRADE_SUCCESS") {
        return system.getResult(null, "trade_status状态有误，100473");
      }
      // 2020 0621验签操作
      var url = this.centerAppUrl + "payment/aliPayment/verifyAliPayReturnSign";
      var opResult = await this.restPostUrl(parmas, url);
      if (opResult.status != 0) {
        opResult.msg = opResult.msg + "，100480";
        return opResult;
      }
      // data:{
      //   orderNo: outTradeInfo[0],
      //   uappId: outTradeInfo[1],
      //   productId: outTradeInfo.length == 3 ? outTradeInfo[2] : 0
      //  }
      // opResult.data = {
      //   orderNo: "TM36202004191028Sgir",
      //   uappId: 36,
      //   productId: 42
      // };
      // //获取充值业务锁
      // await this.cacheManager["TlPayLocker"].init(opResult.data.orderNo);//---测试时放开
      var locker = await this.cacheManager["TlPayLocker"].enter(opResult.data.orderNo);
      if (!locker || locker != "1") {
        this.logCtl.info({
          appid: opResult.data.uappId,
          appkey: "",
          op: "service/impl/utilsSve/utilsOrderSve.js/opH5AliDingPayBackNotify",
          content: "参数=" + JSON.stringify(parmas),
          clientIp: parmas.client_ip || "",
          optitle: "阿里回调操作频繁---太频繁了，太频繁了"
        });
        return system.getResultFail(-200, "阿里回调操作频繁---太频繁了，太频繁了");
      }
      parmas.appInfo = { appInfo: { uapp_id: opResult.data.uappId } };
      parmas.orderNo = opResult.data.orderNo;
      parmas.pay_type = "alipay";
      //修改并返回订单支付状态，创建收款单
      var url = this.centerOrderUrl + "opaction/opPayOrder/receivePayCallBackNotifyByAliDing";
      var opOrderResult = await this.restPostUrl(parmas, url);
      if (opOrderResult.status != 0) {
        opOrderResult.data = null;
        return opOrderResult;
      }
      opOrderResult.data.appInfo = {
        uapp_id: opResult.data.uappId
      };
      opOrderResult.data.userInfo = {
        channel_userid: opOrderResult.data.order_info.channelUserId,
        channel_username: opOrderResult.data.order_info.channelUserId,
        channel_nickname: opOrderResult.data.order_info.channelUserId
      };
      opOrderResult.data.orderNo = opResult.data.orderNo;
      var pobj = {
        appInfo: opOrderResult.data.appInfo,
        actionBody: opOrderResult.data
      }
      this.utilsPushSve.pushBusInfo(pobj, "createAliTmApply", 1);
      opOrderResult.data = null;
      return opOrderResult;
    } catch (e) {
      await this.cacheManager["TlPayLocker"].release(parmas.out_trade_no);
      this.logCtl.error({
        optitle: "回调处理订单---error异常",
        op: "center-app/app/base/service/impl/utilsSve/utilstlbankSve.js/opBackNotify",
        content: "参数=" + JSON.stringify(parmas) + "，error：" + e.stack,
        clientIp: client_ip || ""
      });
      return system.getResultFail(-200, e.stack);
    }
  }
  async orderClose(pobj) {//阿里退款
    if (!pobj.actionBody.orderNo) {
      return system.getResult(null, "actionBody.prderNo can not be empty");
    }
    try {
      pobj.actionType = "channeldelOrder";
      await this.delOrder(pobj, pobj.actionBody);
      pobj.actionType = "updateStausByRefundOrder";
      var url = settings.centerOrderUrl() + "action/icapi/springBoard";
      await this.execClient.execPost(pobj, url);
      return system.getResultSuccess();
    } catch (e) {
      return system.getResultFail(-200, e.stack);
    }

  }

  async aliPayNotify(parmas, client_ip) { // 支付宝回调
    try {
        console.log("支付宝回调参数信息--------------------start")
        console.log(JSON.stringify(parmas))
        console.log(typeof(parmas))
        console.log(parmas.toString())
        console.log("支付宝回调参数信息--------------------end")
        //日志记录
        this.logCtl.info({
          optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "支付宝回调参数信息",
          op: "service/impl/utilsSve/utilsOrderSve.js/aliPayNotify",
          content: JSON.stringify(parmas),
        //   content: parmas.toString(),
          clientIp: client_ip || ""
        });
        if (!parmas.trade_status) {
          return system.getResult(null, "trade_status参数不能为空，100470");
        }
        if (parmas.trade_status != "TRADE_FINISHED" && parmas.trade_status != "TRADE_SUCCESS") {
          return system.getResult(null, "trade_status状态有误，100473");
        }
        console.log("parmas.trade_status 校验通过--------------")
        // 2020 0621 支付宝验签接口
        var url = "https://yf-api.gongsibao.com/pay/v1/checkAliPaySign";
        let params = {
            "app": "ukgc", //应用名称 固定
            "key": "a1519e2eab53dfb909e4c32a86b2ea2b", //应用 key 固定
            "tData" : parmas
        }
        var sign = JSON.stringify(params);
        // sign +=  "ab53dfb909e4c32a"
        sign += this.paySecret
        sign = md5(sign).toUpperCase()
        params.sign = sign
        console.log("准备验签名params-------------------start")
        console.log(params)
        console.log("准备验签名params-------------------end")
        // let res = await axios.post(url, params)
        // this.logCtl.info({
        //     optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "支付宝回调参数验签结果",
        //     op: "service/impl/utilsSve/utilsOrderSve.js/aliPayNotify",
        //     content: JSON.stringify(res),
        //     clientIp: client_ip || ""
        // });
        // if (res.status != 0) {
        //     res.msg = res.msg + "，100480";
        //   return res;
        // }
        // 模拟验签结果
        var outTradeInfo = parmas.out_trade_no.split('-');
        console.log("模拟验签结果--------------",outTradeInfo)
        // 
        var opResult = {}
        opResult.data = {
            orderNo: outTradeInfo[0],
            uappId: Number(outTradeInfo[1]),
            productId: outTradeInfo.length == 3 ? Number(outTradeInfo[2]) : 0
        }
        // 2020 07.03 lin 修改 获取app信息 推送蜂擎使用
        var url = this.centerAppUrl + "payment/paymentApi/getAppInfo";
        var appInfoResult = await this.restPostUrl({ uappId: opResult.data.uappId }, url);
        if (appInfoResult.status != 0) {
            appInfoResult.msg = appInfoResult.msg + "，100270";
          return appInfoResult;
        }
        var appInfo = appInfoResult.data;
        // 拿锁
        var locker = await this.cacheManager["TlPayLocker"].enter(opResult.data.orderNo);
        console.log("拿锁结果",locker)
        if (!locker || locker != "1") {
          this.logCtl.info({
            appid: opResult.data.uappId,
            appkey: "",
            op: "service/impl/utilsSve/utilsOrderSve.js/aliPayNotify",
            content: "参数=" + JSON.stringify(parmas),
            clientIp: parmas.client_ip || "",
            optitle: "阿里回调操作频繁---太频繁了，太频繁了"
          });
          return system.getResultFail(-200, "阿里回调操作频繁---太频繁了，太频繁了");
        }
        parmas.appInfo = { appInfo: { uapp_id: opResult.data.uappId } };
        parmas.orderNo = opResult.data.orderNo;
        parmas.pay_type = "alipay";
        //修改并返回订单支付状态，创建收款单
        // 这里修改了order_info的状态（status/paytime等）
        var url = this.centerOrderUrl + "opaction/opPayOrder/receivePayCallBackNotifyByAliDing";
        var opOrderResult = await this.restPostUrl(parmas, url);
        if (opOrderResult.status != 0) {
          opOrderResult.data = null;
          return opOrderResult;
        }
        opOrderResult.data.appInfo = {
          uapp_id: opResult.data.uappId,
          uapp_key: appInfo.uapp_key,
          app_code: appInfo.app_code,
          app_name: appInfo.app_name
        };
        opOrderResult.data.userInfo = {
          channel_userid: opOrderResult.data.order_info.channelUserId,
          channel_username: opOrderResult.data.order_info.channelUserId,
          channel_nickname: opOrderResult.data.order_info.channelUserId
        };
        opOrderResult.data.orderNo = opResult.data.orderNo;
        opOrderResult.data.order_info.pay_flow_no = parmas.trade_no;// 2020 0704 lin 新增 推送fq必填字段 
        opOrderResult.data.order_info.pay_channel = "支付宝";//付款方式
        opOrderResult.data.order_info.pay_time = parmas.gmt_payment;//付款时间
        opOrderResult.data.order_info.pay_payer_bank_no = parmas.buyer_email;//付款账号
        opOrderResult.data.order_contact = opOrderResult.data.delivery_content.orderContact;
        var pobj = {
          appInfo: opOrderResult.data.appInfo,
          actionBody: opOrderResult.data
        }
        // 推送
        this.utilsPushSve.pushBusInfo(pobj, "pushOrder", 0);
        opOrderResult.data = null;
        return opOrderResult;
      } catch (e) {
        await this.cacheManager["TlPayLocker"].release(parmas.out_trade_no);
        this.logCtl.error({
          optitle: "回调处理订单---error异常",
          op: "center-app/app/base/service/impl/utilsSve/utilsOrderSve.js/aliPayNotify",
          content: "参数=" + JSON.stringify(parmas) + "，error：" + e.stack,
          clientIp: client_ip || ""
        });
        return system.getResultFail(-200, e.stack);
      }
  }


  async wxPayNotify(parmas, client_ip) { // 微信宝回调
    try {
        //日志记录
        this.logCtl.info({
          optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "微信回调参数信息",
          op: "service/impl/utilsSve/utilsOrderSve.js/wxPayNotify",
          content: JSON.stringify(parmas),
          clientIp: client_ip || ""
        });
        if (!parmas.result_code) {
          return system.getResult(null, "result_code参数不能为空，100670");
        }
        if (parmas.result_code != "SUCCESS") {
          return system.getResult(null, "result_code状态有误，100673");
        }
        // 2020 0621 支付宝验签接口
        // var url = "https://yf-api.gongsibao.com/pay/v1/checkWXPaySign";
        // let params = {
        //     "app": "ukgc", //应用名称 固定
        //     "key": "a1519e2eab53dfb909e4c32a86b2ea2b", //应用 key 固定
        //     "tData" : parmas
        // }
        // var sign = JSON.stringify(params);
        // sign +=  "ab53dfb909e4c32a"
        // sign = md5(sign).toUpperCase()
        // params.sign = sign
        // let res = await axios.post(url, params)
        // this.logCtl.info({
        //     optitle: (new Date()).Format("yyyy-MM-dd hh:mm:ss") + "微信回调参数验签结果",
        //     op: "service/impl/utilsSve/utilsOrderSve.js/wxPayNotify",
        //     content: JSON.stringify(res),
        //     clientIp: client_ip || ""
        // });
        // if (res.status != 0) {
        //     res.msg = res.msg + "，100480";
        //   return res;
        // }
        // 模拟验签结果
        var outTradeInfo = parmas.out_trade_no.split('-');
        // 
        var opResult = {}
        opResult.data = {
            orderNo: outTradeInfo[0],
            uappId: Number(outTradeInfo[1]),
            productId: outTradeInfo.length == 3 ? Number(outTradeInfo[2]) : 0
        }
        // 拿锁
        var locker = await this.cacheManager["TlPayLocker"].enter(opResult.data.orderNo);
        if (!locker || locker != "1") {
          this.logCtl.info({
            appid: opResult.data.uappId,
            appkey: "",
            op: "service/impl/utilsSve/utilsOrderSve.js/wxPayNotify",
            content: "参数=" + JSON.stringify(parmas),
            clientIp: parmas.client_ip || "",
            optitle: "微信回调操作频繁---太频繁了，太频繁了"
          });
          return system.getResultFail(-200, "微信回调操作频繁---太频繁了，太频繁了");
        }
        parmas.appInfo = { appInfo: { uapp_id: opResult.data.uappId } };
        parmas.orderNo = opResult.data.orderNo;
        // 注意 微信支付要写wx 不要wxpay等其他。c_order_receiptvoucher收款单的accountType会对应wx:微信"alipay":"支付宝","other":"其它"等其他方式
        parmas.pay_type = "wx";
        //修改并返回订单支付状态，创建收款单
        // 这里修改了order_info的状态（status/paytime等）
        // var url = this.centerOrderUrl + "opaction/opPayOrder/receivePayCallBackNotifyByAliDing";
        var url = this.centerOrderUrl + "opaction/opPayOrder/receivePayCallBackNotifyByWX";
        var opOrderResult = await this.restPostUrl(parmas, url);
        if (opOrderResult.status != 0) {
          opOrderResult.data = null;
          return opOrderResult;
        }
        opOrderResult.data.appInfo = {
          uapp_id: opResult.data.uappId
        };
        opOrderResult.data.userInfo = {
          channel_userid: opOrderResult.data.order_info.channelUserId,
          channel_username: opOrderResult.data.order_info.channelUserId,
          channel_nickname: opOrderResult.data.order_info.channelUserId
        };
        opOrderResult.data.orderNo = opResult.data.orderNo;
        var pobj = {
          appInfo: opOrderResult.data.appInfo,
          actionBody: opOrderResult.data
        }
        this.utilsPushSve.pushBusInfo(pobj, "createAliTmApply", 1);
        opOrderResult.data = null;
        return opOrderResult;
      } catch (e) {
        await this.cacheManager["TlPayLocker"].release(parmas.out_trade_no);
        this.logCtl.error({
          optitle: "回调处理订单---error异常",
          op: "center-app/app/base/service/impl/utilsSve/utilstlbankSve.js/opBackNotify",
          content: "参数=" + JSON.stringify(parmas) + "，error：" + e.stack,
          clientIp: client_ip || ""
        });
        return system.getResultFail(-200, e.stack);
      }
  }
}
module.exports = UtilsOrderService;
