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/linkly/index.tsx
var linkly_exports = {};
__export(linkly_exports, {
  default: () => linkly_default
});
module.exports = __toCommonJS(linkly_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_store = require("../store");
var import_hooks = require("../hooks");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils2 = require("../../../utils");
var import_step = __toESM(require("../component/step/step"));
var import_const = require("../const");
var import_hooks2 = require("./hooks");
var import_const2 = require("./const");
var import_helper = require("../helper");
var import_payLog = __toESM(require("../utils/payLog"));
var Linkly = ({ api, onChange }) => {
  const context = (0, import_useEngineContext.default)();
  const utils = context.appHelper.utils || {};
  import_utils2.request.setRequest(utils == null ? void 0 : utils.request);
  const { custom, status } = (0, import_store.useContextData)();
  const {
    statusRef,
    netRef,
    modeRef,
    amountRef,
    orderIdRef,
    numRef,
    deviceRef,
    payRef
  } = (0, import_hooks.useStoreRef)();
  const dispatch = (0, import_store.useDispatch)();
  const stepRef = (0, import_react.useRef)(custom == null ? void 0 : custom.step);
  const fail = (0, import_hooks.useFail)(0);
  const failRef = (0, import_react.useRef)(fail);
  const initRef = (0, import_react.useRef)(false);
  const controllerRef = (0, import_react.useRef)();
  const unloadRef = (0, import_react.useRef)(false);
  const clearRef = (0, import_react.useRef)();
  const handleCheck = () => !(unloadRef.current || !netRef.current);
  const handleLinklySuccess = (res) => {
    import_payLog.default.log("Linkly：最终支付成功");
    const resData = (res == null ? void 0 : res.data) || {};
    let receipt = Array.isArray(resData == null ? void 0 : resData.receipt) ? resData.receipt : [resData.receipt];
    receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
    dispatch((0, import_store.updateNextStep)());
    dispatch(
      (0, import_store.updateCustom)({
        card_reader_surcharge: (resData == null ? void 0 : resData.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(() => {
      var _a, _b;
      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: (resData == null ? void 0 : resData.card_reader_surcharge) || 0,
            receipt
          }
        },
        "success"
      );
      onChange("success", {
        ...params,
        receipt: ((_b = (_a = deviceRef.current) == null ? void 0 : _a.setting) == null ? void 0 : _b.receipts) ? [] : receipt
      });
    }, 1e3);
  };
  const { payOrRefund } = (0, import_hooks2.useLinklyPayOrRefund)(handleCheck);
  const { linklyCancel } = (0, import_hooks2.useLinklyCancel)(handleCheck);
  const { run: resultQuery, stop: stopResultQuery } = (0, import_hooks2.useTimeResultQuery)(
    api,
    handleCheck,
    handleLinklySuccess
  );
  const { linklySignature } = (0, import_hooks2.useLinklySignature)(handleCheck);
  (0, import_react.useEffect)(() => {
    stepRef.current = custom == null ? void 0 : custom.step;
  }, [custom == null ? void 0 : custom.step]);
  (0, import_react.useEffect)(() => {
    failRef.current = fail;
  }, [fail]);
  (0, import_react.useEffect)(() => {
    var _a, _b, _c;
    if (statusRef.current === import_const.StatusEnum.Success || statusRef.current === import_const.StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    if (numRef.current) {
      resultQuery();
      return;
    }
    if (((_a = utils == null ? void 0 : utils.isTerminal) == null ? void 0 : _a.call(utils)) && ((_c = (_b = utils == null ? void 0 : utils.interaction) == null ? void 0 : _b.utils) == null ? void 0 : _c.asyncDataManager)) {
      const _payOrRefund = async () => {
        var _a2, _b2, _c2;
        try {
          const activeStatus = await ((_c2 = (_b2 = (_a2 = utils == null ? void 0 : utils.interaction) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.asyncDataManager) == null ? void 0 : _c2.call(_b2, {
            module: "get",
            key: "pay_webview_active"
          }));
          if (activeStatus !== "unActive") {
            payOrRefund(resultQuery, handleLinklySuccess);
          } else {
            import_payLog.default.log("Linkly：页面非活跃状态，阻断支付", { activeStatus });
          }
        } catch (error) {
          import_payLog.default.log("Linkly：获取页面活跃状态失败", { error });
          payOrRefund(resultQuery, handleLinklySuccess);
        }
      };
      _payOrRefund();
    } else {
      payOrRefund(resultQuery, handleLinklySuccess);
    }
  }, []);
  (0, import_react.useEffect)(() => {
    return () => {
      var _a;
      (_a = controllerRef.current) == null ? void 0 : _a.abort();
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);
  const onCancel = () => {
    import_payLog.default.log("Linkly：点击取消支付");
    stopResultQuery();
    linklyCancel(resultQuery);
  };
  const onDecline = () => {
    import_payLog.default.log("Linkly：签名-点击拒绝");
    stopResultQuery();
    linklySignature(2, resultQuery);
  };
  const onAccept = () => {
    import_payLog.default.log("Linkly：签名-点击接受");
    stopResultQuery();
    linklySignature(3, resultQuery);
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, ((custom == null ? void 0 : custom.list) || []).map((item) => /* @__PURE__ */ import_react.default.createElement(
    import_step.default,
    {
      key: item.index,
      pedding: item.pedding,
      resolve: item.resolve,
      reject: item.reject,
      status: item.status
    }
  )), status === import_const.StatusEnum.Loading ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, import_utils.locales.getText("page.eftpos-pay.text.processing")) : null, status === import_const.StatusEnum.Question ? /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, import_utils.locales.getText("page.eftpos-pay.text.receipt.again.title")), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, import_utils.locales.getText("page.eftpos-pay.text.receipt.again.text"))) : null, status === import_const.StatusEnum.Success ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip" }, import_utils.locales.getText("page.eftpos-pay.text.transaction.end")) : null), (custom == null ? void 0 : custom.actionStatus) === import_const2.LinklyActionStatus.Cancel ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onCancel,
      disabled: !!(custom == null ? void 0 : custom.buttonDisabled)
    },
    import_utils.locales.getText("page.eftpos-pay.text.cancel")
  )) : null, (custom == null ? void 0 : custom.actionStatus) === import_const2.LinklyActionStatus.CancelWaiting || (custom == null ? void 0 : custom.actionStatus) === import_const2.LinklyActionStatus.SignatureWaiting ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      disabled: true
    },
    import_utils.locales.getText("page.eftpos-pay.text.leave")
  )) : null, (custom == null ? void 0 : custom.actionStatus) === import_const2.LinklyActionStatus.Signature ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onDecline
    },
    import_utils.locales.getText("page.eftpos-pay.text.decline")
  ), /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      type: "primary",
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onAccept
    },
    import_utils.locales.getText("page.eftpos-pay.text.accept")
  )) : null);
};
var linkly_default = Linkly;
