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/TDSPay/index.tsx
var TDSPay_exports = {};
__export(TDSPay_exports, {
  default: () => TDSPay_default
});
module.exports = __toCommonJS(TDSPay_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_ThreedsLoading = __toESM(require("./ThreedsLoading"));
var import_tds2 = require("../tds2");
var import_serve = require("../List/serve");
var import_model = require("../../../model");
var import_payGroup = require("../../../payGroup");
var import_index = require("./index.less");
var import_utils = require("@pisell/utils");
var import_useEngineContext = __toESM(require("../../../../../../hooks/useEngineContext"));
var TDSPay = (props, ref) => {
  var _a;
  const { onChange, closeAll } = props;
  const [open, setOpen] = (0, import_react.useState)(false);
  const [showCloseConfirm, setShowCloseConfirm] = (0, import_react.useState)(false);
  const sessionIdRef = (0, import_react.useRef)(0);
  const payingRef = (0, import_react.useRef)(false);
  const { state } = (0, import_react.useContext)(import_model.Context);
  const engineContext = (0, import_useEngineContext.default)();
  const { token } = ((_a = engineContext.appHelper) == null ? void 0 : _a.utils) || {};
  (0, import_react.useEffect)(() => {
    return () => {
      sessionIdRef.current += 1;
      (0, import_tds2.cancelCurrentPayment)();
    };
  }, []);
  const createSessionCallback = (session) => (res) => {
    if (sessionIdRef.current !== session) return;
    setOpen(false);
    setShowCloseConfirm(false);
    payingRef.current = false;
    if (res.key === "hideModal") return;
    onChange == null ? void 0 : onChange(res);
  };
  const init = async (res, order, preCheckData) => {
    var _a2;
    if (payingRef.current) return;
    payingRef.current = true;
    sessionIdRef.current += 1;
    (0, import_tds2.cancelCurrentPayment)();
    const session = sessionIdRef.current;
    setOpen(true);
    const isCancelled = () => sessionIdRef.current !== session;
    const callback = createSessionCallback(session);
    if (preCheckData) {
      (0, import_tds2.startPayment)(
        { payData: preCheckData },
        { callback, isCancelled, stashAuthToken: (_a2 = token == null ? void 0 : token.get) == null ? void 0 : _a2.call(token) }
      );
      return;
    }
    if (res.id) {
      _fastPayNew(res, callback, isCancelled);
    } else {
      newCardPay(res, callback, isCancelled);
    }
  };
  const handleCloseClick = () => {
    setShowCloseConfirm(true);
  };
  const handleContinueWaiting = () => {
    setShowCloseConfirm(false);
  };
  const handleViewOrder = () => {
    sessionIdRef.current += 1;
    (0, import_tds2.cancelCurrentPayment)();
    payingRef.current = false;
    setShowCloseConfirm(false);
    setOpen(false);
    closeAll == null ? void 0 : closeAll();
    onChange == null ? void 0 : onChange({ key: "cancel" });
  };
  const _fastPayNew = async (res, callback, isCancelled) => {
    var _a2, _b, _c, _d;
    try {
      const params = (0, import_payGroup.getPayGroupParamsFromStorage)(
        (_a2 = state.payGroup) == null ? void 0 : _a2.order_id,
        { card_id: res.id }
      );
      if (!params) {
        callback({
          key: "fail",
          data: {
            res,
            fn: "_fastPayNew1",
            message: import_utils.locales.getText("tocPay.text.getParamsFail")
          }
        });
        return;
      }
      const { data } = await (0, import_serve.fastPayNew)({
        order_id: (_b = state.payGroup) == null ? void 0 : _b.order_id,
        params
      });
      if (isCancelled()) return;
      await (0, import_payGroup.setPayNumber)(
        (_c = state.payGroup) == null ? void 0 : _c.order_id,
        data == null ? void 0 : data.pay_number,
        (_d = token == null ? void 0 : token.get) == null ? void 0 : _d.call(token)
      );
      if ((data == null ? void 0 : data.type) === "token") {
        callback({ key: "success", data });
      }
      if ((data == null ? void 0 : data.type) === "3ds") {
        (0, import_tds2.startPayment)({ payData: data }, { callback, isCancelled });
      }
    } catch (e) {
      callback({
        key: "fail",
        data: {
          res,
          fn: "_fastPayNew2",
          message: import_utils.locales.getText("tocPay.text.getParamsFail")
        }
      });
    }
  };
  const newCardPay = (res, callback, isCancelled) => {
    var _a2, _b, _c;
    let _cardInfo = {
      card_name: res.card_name,
      card_number: res.card_number,
      card_expiry_month: res.date.format("MM"),
      card_expiry_year: res.date.format("YY"),
      card_ccv: res.card_ccv,
      is_save: res.is_save ? 1 : 0
    };
    _cardInfo = (0, import_payGroup.getPayGroupParamsFromStorage)(
      (_a2 = state.payGroup) == null ? void 0 : _a2.order_id,
      _cardInfo
    );
    if (!_cardInfo) {
      callback({
        key: "fail",
        data: {
          _cardInfo,
          message: import_utils.locales.getText("tocPay.text.getParamsFail"),
          fn: "newCardPay"
        }
      });
      return;
    }
    (0, import_tds2.startPayment)(
      { orderId: (_b = state.payGroup) == null ? void 0 : _b.order_id, cardInfo: _cardInfo },
      { callback, isCancelled, stashAuthToken: (_c = token == null ? void 0 : token.get) == null ? void 0 : _c.call(token) }
    );
  };
  (0, import_react.useImperativeHandle)(
    ref,
    () => ({
      init
    })
  );
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      platform: "h5",
      open,
      footer: false,
      header: false,
      closable: true,
      onCancel: handleCloseClick,
      bodyStyle: { padding: 0 }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, /* @__PURE__ */ import_react.default.createElement(
      import_ThreedsLoading.default,
      {
        title: import_utils.locales.getText("tocPay.text.processingPayment"),
        subtitle: import_utils.locales.getText("tocPay.text.securityCheckRequired"),
        description: import_utils.locales.getText("tocPay.text.doNotClosePage")
      }
    ), /* @__PURE__ */ import_react.default.createElement("div", { id: "threeds-container" }))
  ), /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open: showCloseConfirm,
      closable: false,
      footer: null,
      header: false,
      mobileModalHeight: "auto",
      headerDivider: false,
      footerDivider: false,
      bodyStyle: { padding: 24 },
      transitionName: "pisell-move-down"
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "tds-close-confirm-modal" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "tds-close-confirm-title" }, import_utils.locales.getText("tocPay.text.stopWaitingTitle")), /* @__PURE__ */ import_react.default.createElement("div", { className: "tds-close-confirm-desc" }, import_utils.locales.getText("tocPay.text.stopWaitingDesc")), /* @__PURE__ */ import_react.default.createElement("div", { className: "tds-close-confirm-actions" }, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        type: "primary",
        block: true,
        className: "tds-close-confirm-btn-primary",
        onClick: handleContinueWaiting
      },
      import_utils.locales.getText("tocPay.text.continueWaiting")
    ), /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "tds-close-confirm-link",
        onClick: handleViewOrder
      },
      import_utils.locales.getText("tocPay.text.viewOrder")
    )))
  ));
};
var TDSPay_default = (0, import_react.forwardRef)(TDSPay);
