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/eftposPay/adyenScan/index.tsx
var adyenScan_exports = {};
__export(adyenScan_exports, {
  default: () => adyenScan_default
});
module.exports = __toCommonJS(adyenScan_exports);
var import_react = __toESM(require("react"));
var import_utils = require("@pisell/utils");
var import_index = require("./index.less");
var import_store = require("../store");
var import_hooks = require("../hooks");
var import_const = require("../const");
var import_helper = require("../helper");
var import_Action = require("./Action");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_aggregatePayment = require("../aggregatePayment");
var import_types = require("../aggregatePayment/types");
var ADYEN_SCAN_PAYMENT_CODE_MAP = {
  [import_const.EftposEnum.AdyenAlipay]: "EFTPOS_ADYENALIPAY",
  [import_const.EftposEnum.AdyenWechat]: "EFTPOS_ADYENWECHAT"
};
var ADYEN_SCAN_RETURN_PATH = "/lc/tob_pay_toc-pay-result";
var getAdyenScanReturnUrl = (defaultDomain, query) => {
  if (!defaultDomain) return "";
  const domain = defaultDomain == null ? void 0 : defaultDomain.trim().replace(/\/+$/, "");
  if (!domain) return "";
  const returnUrl = /^https?:\/\//i.test(domain) ? `${domain}${ADYEN_SCAN_RETURN_PATH}` : `https://${domain}${ADYEN_SCAN_RETURN_PATH}`;
  const url = new URL(returnUrl);
  Object.entries(query || {}).forEach(([key, value]) => {
    if (value !== void 0 && value !== null && value !== "") {
      url.searchParams.set(key, `${value}`);
    }
  });
  return url.toString();
};
var AdyenScan = ({ onChange, isNativeApp }) => {
  var _a;
  const data = (0, import_store.useContextData)();
  const context = (0, import_useEngineContext.default)();
  const { interaction, getApp, store, getData, getStore } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const dispatch = (0, import_store.useDispatch)();
  const {
    statusRef,
    modeRef,
    amountRef,
    orderIdRef,
    numRef,
    deviceRef,
    payRef,
    netRef,
    eftposRef
  } = (0, import_hooks.useStoreRef)();
  const fail = (0, import_hooks.useFail)(0);
  const failRef = (0, import_react.useRef)(fail);
  const initRef = (0, import_react.useRef)(false);
  const unloadRef = (0, import_react.useRef)(false);
  const clearRef = (0, import_react.useRef)(null);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [qrCode, setQrCode] = (0, import_react.useState)("");
  const qrCodeRef = (0, import_react.useRef)("");
  const [payMethodType, setPayMethodType] = (0, import_react.useState)("");
  const payment = (0, import_aggregatePayment.usePayment)({
    paymentCode: ADYEN_SCAN_PAYMENT_CODE_MAP[eftposRef.current],
    paymentNum: numRef.current || "",
    config: {
      globalQueryTimeout: modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay ? 1e3 * 60 * 5 : 1e3 * 60 * 2
      // 退款场景轮询超时时间2分钟
    },
    shouldContinue: () => !(unloadRef.current || !netRef.current),
    callback: (_instance, response) => {
      var _a2, _b;
      console.log("response =>>>> ", response);
      const { status, data: data2 } = response || {};
      let needHideLoading = true;
      if (status === import_types.EPaymentStatus.Processing) {
        const { url, paymentMethodType, qrCodeData } = ((_b = (_a2 = data2 == null ? void 0 : data2.data) == null ? void 0 : _a2.external_unified_response) == null ? void 0 : _b.action) || {};
        const _qrCode = url || qrCodeData;
        if (!_qrCode) {
          needHideLoading = false;
        }
        if (_qrCode && _qrCode !== qrCodeRef.current) {
          qrCodeRef.current = _qrCode;
          setQrCode(_qrCode);
          setPayMethodType(paymentMethodType);
        }
      } else if (status === import_types.EPaymentStatus.Success) {
        handleSuccess();
      } else if (status === import_types.EPaymentStatus.Failed) {
        handleFail(data2);
      }
      if (needHideLoading) {
        setLoading(false);
      }
    }
  });
  (0, import_react.useEffect)(() => {
    failRef.current = fail;
  }, [fail]);
  (0, import_react.useEffect)(() => {
    var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
    if (statusRef.current === import_const.StatusEnum.Success || statusRef.current === import_const.StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    if (numRef.current) {
      console.log("payment.query");
      payment.query();
      return;
    }
    const isPay = modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay;
    setLoading(true);
    updateToLoading();
    if (isPay) {
      let defaultDomain = (_c = (_b = (_a2 = store == null ? void 0 : store.getState()) == null ? void 0 : _a2.global) == null ? void 0 : _b.globalConfig) == null ? void 0 : _c.default_domain;
      if (!defaultDomain) {
        defaultDomain = (_j = (_i = (_h = (_g = (_f = (_e = (_d = getApp == null ? void 0 : getApp()) == null ? void 0 : _d.data) == null ? void 0 : _e.store) == null ? void 0 : _f.getStore) == null ? void 0 : _g.call(_f)) == null ? void 0 : _h.getDataByModel) == null ? void 0 : _i.call(_h, "core", "core")) == null ? void 0 : _j.default_domain;
      }
      const shopId = ((_o = (_n = (_m = (_l = (_k = getStore == null ? void 0 : getStore()) == null ? void 0 : _k.getState) == null ? void 0 : _l.call(_k)) == null ? void 0 : _m.global) == null ? void 0 : _n.shop) == null ? void 0 : _o.id) || (getData == null ? void 0 : getData("shop_id")) || ((_s = (_r = (_q = (_p = store == null ? void 0 : store.getState) == null ? void 0 : _p.call(store)) == null ? void 0 : _q.global) == null ? void 0 : _r.globalConfig) == null ? void 0 : _s.id) || void 0;
      payment.run({
        getParams: ({ uniquePaymentNumber }) => ({
          adyenscan: {
            return_url: getAdyenScanReturnUrl(defaultDomain, {
              payment_number: uniquePaymentNumber,
              shop_id: shopId
            }) || ""
          }
        })
      });
    } else {
      payment.run({
        params: {
          adyenscan: { order_payment_id: (_t = data == null ? void 0 : data.custom) == null ? void 0 : _t.order_payment_id }
        }
      });
    }
  }, []);
  (0, import_react.useEffect)(() => {
    var _a2, _b;
    if (isNativeApp && (data == null ? void 0 : data.status) === import_const.StatusEnum.Init) {
      (_b = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b.call(_a2, {
        module: "pos",
        key: "other",
        data: {
          key: "show_close_button"
        }
      });
    }
  }, [isNativeApp, data == null ? void 0 : data.status]);
  (0, import_react.useEffect)(() => {
    return () => {
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);
  const updateToLoading = () => {
    var _a2, _b;
    if (isNativeApp) {
      (_b = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b.call(_a2, {
        module: "pos",
        key: "other",
        data: {
          key: "hide_close_button"
        }
      });
    }
    dispatch((0, import_store.updateStatus)(import_const.StatusEnum.Loading));
    dispatch(
      (0, import_store.updateState)({
        title: import_utils.locales.getText("page.eftpos-pay.text.loading")(modeRef.current)
      })
    );
  };
  const handleSuccess = () => {
    dispatch((0, import_store.updateNextStep)());
    dispatch((0, import_store.updateCustom)({ card_reader_surcharge: 0, receipt: [] }));
    dispatch(
      (0, import_store.updateState)({
        status: "success",
        title: import_utils.locales.getText("page.eftpos-pay.text.successful")(
          modeRef.current
        )
      })
    );
    clearRef.current = setTimeout(() => {
      if (unloadRef.current) return;
      const params = (0, import_helper.getPayParams)(
        {
          mode: modeRef.current,
          amount: amountRef.current,
          order_id: orderIdRef.current,
          number: numRef.current,
          device: deviceRef.current,
          pay: payRef.current,
          custom: { card_reader_surcharge: 0, receipt: [] }
        },
        "success"
      );
      onChange("success", { ...params, receipt: [] });
    }, 1e3);
  };
  const handleFail = (errorData) => {
    var _a2, _b;
    const { message, response_code } = ((_a2 = errorData == null ? void 0 : errorData.data) == null ? void 0 : _a2.external_unified_response) || {};
    const _code = `${response_code || ""}` || import_const.PayStatus.PaymentFailed;
    const _message = message || (errorData == null ? void 0 : errorData.message) || "";
    console.log("handleFail =>>>> ", errorData, _code, _message);
    (_b = failRef.current) == null ? void 0 : _b.call(failRef, { code: _code, message: _message }, true);
  };
  const handleClose = () => {
    onChange("fail", {
      number: data.number,
      uniquePaymentNumber: data.number,
      order_id: data.order_id
    });
  };
  const handleCancelModalOk = () => {
    payment.reset();
    handleClose();
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-eftpos-pay-adyen-scan" }, (data == null ? void 0 : data.status) === import_const.StatusEnum.Loading ? /* @__PURE__ */ import_react.default.createElement(
    import_Action.AdyenScanQrcode,
    {
      loading,
      qrCode,
      payMethodType,
      onCancelPay: handleCancelModalOk,
      isPay: modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay,
      message: import_utils.locales.getText("page.eftpos-pay.text.processing")
    }
  ) : null);
};
var adyenScan_default = AdyenScan;
