var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pay/toC/PaymentMethods/MWCreditCard/tds2.tsx
var tds2_exports = {};
__export(tds2_exports, {
  checkEnrollment: () => checkEnrollment,
  checkPARes: () => checkPARes,
  checkTDSAuth: () => checkTDSAuth,
  createChallengeIframe: () => createChallengeIframe,
  createThreeDSMethodIframe: () => createThreeDSMethodIframe,
  paymentEnd: () => paymentEnd,
  startPayment: () => startPayment
});
module.exports = __toCommonJS(tds2_exports);
var import_utils = require("../../../../../utils");
var import_dayjs = __toESM(require("dayjs"));
var import_utils2 = require("@pisell/utils");
var import_materials = require("@pisell/materials");
var import_payGroup = require("../../payGroup");
var { REACT_APP_API_ENV } = process.env;
var paymentInfo = {
  transactionInfo: {
    transactionProduct: "TEST 3DSv2",
    transactionAmount: "1.00",
    transactionCurrency: "AUD"
  },
  customerName: "Jim Bob",
  billingAddress: {
    billAddrLine1: "123 Test Street",
    billAddrCity: "Brisbane",
    billAddrState: "QLD",
    billAddrPostCode: "4000",
    billAddrCountry: "AU"
  }
};
var paymentData = {};
var postmessageUrl = "merchantwarrior";
var log = (data) => {
  let _template = {
    module,
    contents: {
      path: location.href,
      data,
      date: (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm")
    }
  };
  (0, import_utils2.sendWarningLog)({
    title: "3ds支付失败",
    content: [{ key: "res", value: JSON.stringify(_template) }]
  });
};
var startPayment = async ({ orderId, cardInfo, payData }, callback) => {
  let paymentInfo2 = {
    amount: 0,
    order_id: 0
  };
  try {
    paymentData = {};
    const step2 = payData ? payData : await checkEnrollment(orderId, cardInfo, callback);
    if (step2 === 0) {
      return;
    }
    paymentData.step2 = step2;
    paymentInfo2.amount = step2.amount;
    paymentInfo2.order_id = step2.order_id;
    console.log("第三步");
    let step3 = await createThreeDSMethodIframe(step2, callback);
    paymentData.step3 = step3;
    if (step3 === "N") {
      return;
    }
    const step4 = await checkTDSAuth(step2, step3, callback);
    if (step4 === 0) {
      return;
    }
    paymentData.step4 = step4;
    if (step4) {
      const step5 = await createChallengeIframe(step4, callback);
      paymentData.step5 = step5;
      await checkPARes(step2, step4, step5);
    }
    callback({ key: "hideModal" });
    paymentEnd(
      {
        status: "success",
        ...paymentInfo2
      },
      callback
    );
    return true;
  } catch (err) {
    console.log("error", err);
    callback({ key: "hideModal" });
    closeIframe();
    if (err === 0) return;
    paymentData.error = err;
    paymentEnd(
      {
        status: "fail",
        ...paymentInfo2
      },
      callback
    );
    return false;
  }
};
var checkEnrollment = async (orderId, cardInfo, callback) => {
  try {
    let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/" + orderId, {
      ...cardInfo
    });
    (0, import_payGroup.setPayNumber)(orderId, data == null ? void 0 : data.pay_number);
    if (!(data == null ? void 0 : data.pay_info)) {
      return null;
    }
    return data;
  } catch (err) {
    log({
      msg: err,
      data: {
        orderId,
        cardInfo
      }
    });
    callback({ key: "hideModal" });
    closeIframe();
    (0, import_materials.PisellToast)({
      content: (err == null ? void 0 : err.message) || "",
      duration: 2
    });
    console.log("error", err);
    return 0;
  }
};
var createThreeDSMethodIframe = async (threeDSMethodData, callback) => {
  var _a, _b, _c, _d, _e;
  const defaultReturnParams = {
    threeDSServerTransID: ((_a = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _a.threeDSServerTransID) || "",
    threeDSCompInd: ((_b = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _b.threeDSCompInd) || ""
  };
  if (((_c = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _c.threeDSServerTransID) && ((_d = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _d.threeDSCompInd)) {
    return defaultReturnParams;
  }
  if (!(threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info.acsURL) || typeof ((_e = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _e.acsURL) !== "string") {
    return defaultReturnParams;
  }
  const displayBox = document.getElementById("threeds-container");
  displayBox.innerHTML = "";
  let iframe = document.createElement("iframe");
  iframe.classList.add("hidden_TDS_From");
  iframe.name = "threeDSMethodIframe";
  displayBox.appendChild(iframe);
  var form = document.createElement("form");
  form.classList.add("hidden_TDS_From");
  form.id = "threeDSMethodForm";
  form.type = "hidden";
  displayBox.appendChild(form);
  var input = document.createElement("input");
  input.id = "threeDSMethodData";
  input.name = "threeDSMethodData";
  input.type = "hidden";
  input.value = threeDSMethodData.pay_info.paReq;
  form.appendChild(input);
  form.action = threeDSMethodData.pay_info.acsURL;
  form.target = iframe.name;
  form.method = "post";
  form.submit();
  let timer = null;
  return new Promise((res, rej) => {
    timer = setTimeout(() => {
      res(defaultReturnParams);
      log({
        msg: "第三步: 10秒超时则走N逻辑",
        data: threeDSMethodData
      });
    }, 1e4);
    window.addEventListener(
      "message",
      (event) => {
        if (event.origin.indexOf(postmessageUrl) !== -1 || event.origin.indexOf("securesuite") !== -1) {
          if (typeof event.data.threeDSServerTransID == "string") {
            if (timer) {
              clearTimeout(timer);
            }
            res({
              threeDSServerTransID: event.data.threeDSServerTransID,
              threeDSCompInd: "Y"
            });
          }
        }
      },
      false
    );
  });
};
var checkTDSAuth = async (step2, step3, callback) => {
  try {
    const { pay_number, order_id, pay_info, amount, notifyURL } = step2;
    const { threeDSServerTransID, threeDSCompInd } = step3;
    var currentData = /* @__PURE__ */ new Date();
    let isPre = false;
    if (REACT_APP_API_ENV === "pre" && pay_info.check_tds_auth.card_name === "aa bb") {
      isPre = true;
    }
    let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/tds_auth_pay", {
      order_id,
      pay_number,
      mw_data: {
        accessToken: pay_info.check_tds_auth.access_token,
        method: "checkTDSAuth",
        cardID: pay_info.check_tds_auth.card_id,
        // paymentCardNumber: cardInfo.paymentCardNumber,
        paymentCardExpiry: pay_info.check_tds_auth.card_expiry,
        paymentCardName: pay_info.check_tds_auth.card_name,
        // paymentCardCSC: cardInfo.paymentCardCSC,
        customerName: pay_info.check_tds_auth.card_name,
        transactionAmount: amount,
        transactionCurrency: paymentInfo.transactionInfo.transactionCurrency,
        transactionProduct: pay_info.check_tds_auth.product_name,
        browserAcceptHeader: "*/*",
        browserColorDepth: screen.colorDepth,
        browserJavaEnabled: navigator.javaEnabled(),
        browserJavascriptEnabled: true,
        browserLanguage: navigator.language,
        browserScreenHeight: screen.height,
        browserScreenWidth: screen.width,
        browserTZ: currentData.getTimezoneOffset(),
        browserUserAgent: navigator.userAgent,
        purchaseDate: "20220420165834",
        billAddrCity: paymentInfo.billingAddress.billAddrCity,
        billAddrCountry: paymentInfo.billingAddress.billAddrCountry,
        billAddrLine1: paymentInfo.billingAddress.billAddrLine1,
        billAddrPostCode: paymentInfo.billingAddress.billAddrPostCode,
        billAddrState: paymentInfo.billingAddress.billAddrState,
        threeDSCompInd: isPre ? "" : threeDSCompInd,
        threeDSServerTransID: isPre ? "" : threeDSServerTransID,
        threeDSRequestorAuthenticationInd: "01",
        threeDSRequestorURL: window.location.href,
        notifyURL
      }
    });
    if (!data) {
      return null;
    }
    return data;
  } catch (err) {
    log({
      msg: err,
      data: paymentData
    });
    (0, import_materials.PisellToast)({
      content: (err == null ? void 0 : err.message) || "",
      duration: 1e3 * 200,
      onClose() {
        callback({ key: "hideModal" });
        closeIframe();
      }
    });
    return 0;
  }
};
var createChallengeIframe = (challengeData, callback) => {
  const displayBox = document.getElementById("threeds-container");
  displayBox.innerHTML = "";
  let iframe = document.createElement("iframe");
  iframe.classList.add("tdsv2challengeIframe");
  iframe.name = "challengeIframe";
  iframe.id = "3dsv2challengeIframe";
  displayBox.appendChild(iframe);
  var form = document.createElement("form");
  form.classList.add("hidden_TDS_From");
  form.id = "3dsv2challengeForm";
  displayBox.appendChild(form);
  var input = document.createElement("input");
  input.id = "creq";
  input.name = "creq";
  input.value = challengeData.challengeData;
  input.type = "hidden";
  form.appendChild(input);
  form.action = challengeData.acsURL;
  form.target = iframe.name;
  form.method = "post";
  form.submit();
  iframe.onload = function() {
  };
  return new Promise((res, rej) => {
    let timer = null;
    const handleMessage = (event) => {
      if (event.origin.indexOf(postmessageUrl) !== -1 || event.origin.indexOf("securesuite") !== -1) {
        if (typeof event.data.cres == "string") {
          if (timer) {
            clearTimeout(timer);
          }
          res(event.data.cres);
          closeIframe();
        }
      }
    };
    timer = setTimeout(() => {
      log({
        msg: "第五步: 60秒超时则走N逻辑",
        data: challengeData
      });
      window.removeEventListener("message", handleMessage);
      rej("time out");
    }, 2 * 60 * 1e3);
    window.addEventListener(
      "message",
      handleMessage,
      false
    );
  });
};
var checkPARes = async (step2, step4, step5) => {
  const { pay_number, order_id, pay_info, amount } = step2;
  const { tdsPayKey, tdsPayToken } = step4;
  const cres = step5;
  let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/check_pares", {
    order_id,
    pay_number,
    mw_data: {
      transactionProduct: pay_info.check_tds_auth.product_name,
      cres,
      accessToken: pay_info.check_tds_auth.access_token,
      tdsPayKey,
      tdsPayToken,
      paymentCardName: pay_info.check_tds_auth.card_name,
      transactionAmount: amount,
      card_id: pay_info.check_tds_auth.card_id
    }
  });
  return data;
};
var paymentEnd = (props, callback) => {
  const { status } = props;
  callback({ key: status, data: props });
  if (status !== "success") {
    log({
      msg: "支付失败",
      data: paymentData
    });
  }
};
var closeIframe = () => {
  let dom = document.querySelector(".tdsv2challengeIframe");
  if (dom) {
    dom.classList.add("tdsv2challengeIframeClose");
  }
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  checkEnrollment,
  checkPARes,
  checkTDSAuth,
  createChallengeIframe,
  createThreeDSMethodIframe,
  paymentEnd,
  startPayment
});
