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, {
  cancelCurrentPayment: () => cancelCurrentPayment,
  checkEnrollment: () => checkEnrollment,
  checkPARes: () => checkPARes,
  checkTDSAuth: () => checkTDSAuth,
  createChallengeIframe: () => createChallengeIframe,
  createThreeDSMethodIframe: () => createThreeDSMethodIframe,
  paymentEnd: () => paymentEnd,
  preCheckEnrollment: () => preCheckEnrollment,
  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 import_utils3 = require("../../utils");
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 activeCleanup = null;
var cancelCurrentPayment = () => {
  activeCleanup == null ? void 0 : activeCleanup();
  activeCleanup = null;
};
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 setHistoryLog = (log2) => {
  if (!paymentData.logList) {
    paymentData.logList = [];
  }
  paymentData.logList.push(log2);
};
var getCurrentTime = () => {
  return (0, import_dayjs.default)().format("YYYY-MM-DD HH:mm:ss");
};
var startPayment = async ({ orderId, cardInfo, payData }, options) => {
  const { callback, isCancelled, stashAuthToken } = options || {};
  let paymentInfo2 = {
    amount: 0,
    order_id: 0
  };
  try {
    paymentData = {
      orderId,
      logList: []
    };
    setHistoryLog({
      msg: "startPayment 开始",
      time: getCurrentTime(),
      hasPayData: !!payData,
      payDataOrderId: payData == null ? void 0 : payData.order_id,
      payDataPayNumber: payData == null ? void 0 : payData.pay_number
    });
    const step2 = payData ? payData : await checkEnrollment(orderId, cardInfo, {
      callback,
      isCancelled,
      stashAuthToken
    });
    if (isCancelled == null ? void 0 : isCancelled()) {
      closeIframe();
      return;
    }
    setHistoryLog({
      msg: "步骤2完成: 提交卡信息到后端",
      time: getCurrentTime(),
      hasStep2: !!step2
    });
    if (step2 === 0) {
      return;
    }
    paymentData.step2 = step2;
    paymentInfo2.amount = step2.amount;
    paymentInfo2.order_id = step2.order_id;
    console.log("第三步");
    setHistoryLog({
      msg: "步骤3开始: 创建iframe监听postMessage",
      time: getCurrentTime()
    });
    let step3 = await createThreeDSMethodIframe(step2, callback);
    if (isCancelled == null ? void 0 : isCancelled()) {
      closeIframe();
      return;
    }
    paymentData.step3 = step3;
    setHistoryLog({
      msg: "步骤3完成: iframe监听结束",
      time: getCurrentTime(),
      step3Result: step3
    });
    if (step3 === "N") {
      return;
    }
    setHistoryLog({
      msg: "步骤4开始: 调用checkTDSAuth",
      time: getCurrentTime(),
      order_id: step2 == null ? void 0 : step2.order_id,
      pay_number: step2 == null ? void 0 : step2.pay_number
    });
    const step4 = await checkTDSAuth(step2, step3, { callback, isCancelled });
    if (isCancelled == null ? void 0 : isCancelled()) {
      closeIframe();
      return;
    }
    setHistoryLog({
      msg: "步骤4完成: checkTDSAuth 返回",
      time: getCurrentTime(),
      hasStep4: !!step4
    });
    if (step4 === 0) {
      return;
    }
    paymentData.step4 = step4;
    if (step4) {
      setHistoryLog({
        msg: "步骤5开始: 创建challenge iframe",
        time: getCurrentTime()
      });
      const step5 = await createChallengeIframe(step4, callback);
      if (isCancelled == null ? void 0 : isCancelled()) {
        closeIframe();
        return;
      }
      paymentData.step5 = step5;
      setHistoryLog({
        msg: "步骤5完成: challenge iframe结束",
        time: getCurrentTime()
      });
      setHistoryLog({
        msg: "步骤6开始: 调用check_pares接口",
        time: getCurrentTime()
      });
      await checkPARes(step2, step4, step5);
      if (isCancelled == null ? void 0 : isCancelled()) {
        closeIframe();
        return;
      }
      setHistoryLog({
        msg: "步骤6完成: check_pares接口返回",
        time: getCurrentTime()
      });
    }
    if (isCancelled == null ? void 0 : isCancelled()) {
      closeIframe();
      return;
    }
    callback == null ? void 0 : callback({ key: "hideModal" });
    setHistoryLog({
      msg: "支付成功",
      time: getCurrentTime()
    });
    paymentEnd(
      {
        status: "success",
        ...paymentInfo2
      },
      callback
    );
    return true;
  } catch (err) {
    console.log("error", err);
    setHistoryLog({
      msg: "支付异常",
      time: getCurrentTime(),
      error: err,
      errorCode: err == null ? void 0 : err.code
    });
    closeIframe();
    if (isCancelled == null ? void 0 : isCancelled()) return;
    callback == null ? void 0 : callback({ key: "hideModal" });
    if (err === 0) return;
    if ((err == null ? void 0 : err.code) === 700500) {
      callback == null ? void 0 : callback({ key: "bankVerifyFailed" });
      return false;
    }
    paymentData.error = err;
    paymentEnd(
      {
        status: "fail",
        ...paymentInfo2
      },
      callback
    );
    return false;
  }
};
var preCheckEnrollment = async (orderId, cardInfo, stashAuthToken) => {
  try {
    const { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/" + orderId, {
      ...cardInfo
    });
    await (0, import_payGroup.setPayNumber)(orderId, data == null ? void 0 : data.pay_number, stashAuthToken);
    if (!(data == null ? void 0 : data.pay_info)) {
      throw new Error("Card does not support 3DS verification");
    }
    return data;
  } catch (err) {
    log({
      msg: err,
      data: {
        orderId,
        cardInfo
      }
    });
    throw err;
  }
};
var checkEnrollment = async (orderId, cardInfo, options) => {
  const { callback, isCancelled, stashAuthToken } = options || {};
  try {
    let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/" + orderId, {
      ...cardInfo
    });
    if (isCancelled == null ? void 0 : isCancelled()) return 0;
    await (0, import_payGroup.setPayNumber)(orderId, data == null ? void 0 : data.pay_number, stashAuthToken);
    if (!(data == null ? void 0 : data.pay_info)) {
      return null;
    }
    return data;
  } catch (err) {
    log({
      msg: err,
      data: {
        orderId,
        cardInfo
      }
    });
    if (isCancelled == null ? void 0 : isCancelled()) return 0;
    callback == null ? void 0 : 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, _f;
  const defaultReturnParams = {
    threeDSServerTransID: ((_a = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _a.threeDSServerTransID) || ((_b = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _b.paReq) || "",
    threeDSCompInd: ((_c = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _c.threeDSCompInd) || "N"
  };
  if (((_d = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _d.threeDSServerTransID) && ((_e = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _e.threeDSCompInd)) {
    return defaultReturnParams;
  }
  if (!(threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info.acsURL) || typeof ((_f = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _f.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) => {
    var _a2;
    const handleMessage = (event) => {
      if (event.origin.indexOf(postmessageUrl) !== -1 || event.origin.indexOf("securesuite") !== -1) {
        if (typeof event.data.threeDSServerTransID == "string") {
          setHistoryLog({
            msg: "第三步: message 返回 threeDSServerTransID",
            time: getCurrentTime(),
            threeDSServerTransID: event.data.threeDSServerTransID
          });
          if (timer) {
            clearTimeout(timer);
          }
          window.removeEventListener("message", handleMessage);
          res({
            threeDSServerTransID: event.data.threeDSServerTransID,
            threeDSCompInd: "Y"
          });
        }
      }
    };
    timer = setTimeout(() => {
      window.removeEventListener("message", handleMessage);
      res(defaultReturnParams);
      log({
        msg: "第三步: 10秒超时则走N逻辑",
        data: threeDSMethodData
      });
    }, ((_a2 = threeDSMethodData == null ? void 0 : threeDSMethodData.pay_info) == null ? void 0 : _a2.tdsMethodTimeoutMS) || 1e4);
    window.addEventListener("message", handleMessage, false);
    activeCleanup = () => {
      window.removeEventListener("message", handleMessage);
      if (timer) clearTimeout(timer);
      rej(0);
    };
  });
};
var checkTDSAuth = async (step2, step3, options) => {
  const { callback, isCancelled } = options || {};
  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;
    }
    const request_unique_idempotency_token = (0, import_utils3.getUniqueIdempotencyToken)();
    setHistoryLog({
      msg: "步骤4开始: 调用tds_auth_pay接口",
      time: getCurrentTime(),
      order_id,
      pay_number,
      request_unique_idempotency_token
    });
    let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/tds_auth_pay", {
      order_id,
      pay_number,
      request_unique_idempotency_token,
      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，只保留前两部分（如 en-GB-oxendict → en-GB），以符合 MPI API 8字符限制
        browserLanguage: (navigator.language || "").split("-").slice(0, 2).join("-"),
        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 || "N",
        threeDSServerTransID: isPre ? "" : threeDSServerTransID,
        threeDSRequestorAuthenticationInd: "01",
        threeDSRequestorURL: window.location.href,
        notifyURL
      }
    });
    setHistoryLog({
      msg: "步骤4完成: tds_auth_pay接口返回",
      time: getCurrentTime(),
      hasStep4: !!data
    });
    if (!data) {
      return null;
    }
    return data;
  } catch (err) {
    setHistoryLog({
      msg: "步骤4异常",
      time: getCurrentTime(),
      errorCode: err == null ? void 0 : err.code
    });
    log({
      msg: err,
      data: paymentData
    });
    if (isCancelled == null ? void 0 : isCancelled()) return 0;
    if ((err == null ? void 0 : err.code) === 700500) {
      throw err;
    }
    (0, import_materials.PisellToast)({
      content: (err == null ? void 0 : err.message) || "",
      duration: 1e3 * 2
    });
    callback == null ? void 0 : 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);
          }
          window.removeEventListener("message", handleMessage);
          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
    );
    activeCleanup = () => {
      window.removeEventListener("message", handleMessage);
      if (timer) clearTimeout(timer);
      rej(0);
    };
  });
};
var checkPARes = async (step2, step4, step5) => {
  const { pay_number, order_id, pay_info, amount } = step2;
  const { tdsPayKey, tdsPayToken } = step4;
  const cres = step5;
  const request_unique_idempotency_token = (0, import_utils3.getUniqueIdempotencyToken)();
  let { data } = await import_utils.request.getRequest().post("/h5/pay/order/mw-3ds-pay/v2/check_pares", {
    order_id,
    pay_number,
    request_unique_idempotency_token,
    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 = {
  cancelCurrentPayment,
  checkEnrollment,
  checkPARes,
  checkTDSAuth,
  createChallengeIframe,
  createThreeDSMethodIframe,
  paymentEnd,
  preCheckEnrollment,
  startPayment
});
