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/payo/config.tsx
var config_exports = {};
__export(config_exports, {
  Action: () => Action,
  POS: () => POS
});
module.exports = __toCommonJS(config_exports);
var import_utils = require("@pisell/utils");
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_step = __toESM(require("../component/step"));
var import_const = require("../const");
var import_helper = require("../helper");
var import_hooks = require("../hooks");
var import_store = require("../store");
var import_hooks2 = require("./hooks");
var import_payment = require("./payment");
var import_payLog = __toESM(require("../utils/payLog"));
var POS = ({
  api,
  onChange
}) => {
  const { steps, custom } = (0, import_store.useContextData)();
  const {
    deviceRef,
    payRef,
    numRef,
    statusRef,
    modeRef,
    netRef,
    orderIdRef,
    amountRef,
    eftposRef,
    dataRef
  } = (0, import_hooks.useStoreRef)();
  const dispatch = (0, import_store.useDispatch)();
  const { key, ...props } = steps[0];
  const fail = (0, import_hooks.useFail)(0);
  const failRef = (0, import_react.useRef)(fail);
  const controllerRef = (0, import_react.useRef)();
  const clearRef = (0, import_react.useRef)(null);
  const initRef = (0, import_react.useRef)(false);
  const unloadRef = (0, import_react.useRef)(false);
  const [check] = (0, import_hooks2.useValidate)(1e3 * 60);
  const { run: paymentRun, clean: paymentClean } = (0, import_payment.usePayment)({
    payApi: api.pay,
    checkApi: api.check,
    shouldContinue: () => {
      return !(unloadRef.current || !netRef.current);
    }
  });
  (0, import_react.useEffect)(() => {
    failRef.current = fail;
  }, [fail]);
  const success = (res) => {
    var _a, _b, _c, _d;
    let receipt = Array.isArray((_a = res == null ? void 0 : res.data) == null ? void 0 : _a.receipt) ? (_b = res == null ? void 0 : res.data) == null ? void 0 : _b.receipt : [(_c = res == null ? void 0 : res.data) == null ? void 0 : _c.receipt];
    receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
    dispatch((0, import_store.updateNextStep)());
    dispatch(
      (0, import_store.updateCustom)({
        card_reader_surcharge: ((_d = res == null ? void 0 : res.data) == null ? void 0 : _d.card_reader_surcharge) || 0,
        receipt
      })
    );
    clearRef.current = setTimeout(() => {
      var _a2, _b2, _c2;
      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: ((_a2 = res == null ? void 0 : res.data) == null ? void 0 : _a2.card_reader_surcharge) || 0,
            receipt
          }
        },
        "success"
      );
      onChange("success", {
        ...params,
        receipt: ((_c2 = (_b2 = deviceRef.current) == null ? void 0 : _b2.setting) == null ? void 0 : _c2.receipts) ? [] : receipt
      });
    }, 1e3);
  };
  const checkApi = () => {
    check(api.check, numRef.current).then(
      (res) => {
        if (unloadRef.current || !netRef.current) {
          return;
        }
        if (res && `${res.code}` === "200") {
          success(res);
          return;
        }
        failRef.current(res, true);
      },
      (res) => {
        if (unloadRef.current || !netRef.current) {
          return;
        }
        failRef.current(res, true);
      }
    );
  };
  (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) {
      checkApi();
      return;
    }
    numRef.current = (0, import_helper.getUuid)();
    dispatch(
      (0, import_store.updateState)({
        number: numRef.current
      })
    );
    controllerRef.current = new AbortController();
    const isPay = modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay;
    const apiParams = isPay ? {
      ...(custom == null ? void 0 : custom.platform) ? {
        operator_id: custom.operator_id,
        operator_type: custom.operator_type,
        platform: custom.platform,
        custom_payment_id: custom.custom_payment_id
      } : {},
      original_amount: payRef.current.amount,
      service_charge: {
        amount: payRef.current.surMoney,
        percentage: payRef.current.surPercentRate
      },
      order_id: orderIdRef.current,
      amount: payRef.current.total,
      card_reader_type: eftposRef.current,
      card_reader_id: (_a = deviceRef.current) == null ? void 0 : _a.id,
      number: numRef.current,
      pay_param_base64: encodeURIComponent(
        btoa(
          encodeURIComponent(
            JSON.stringify({
              ...dataRef.current,
              number: numRef.current
            })
          )
        )
      )
    } : {
      order_id: orderIdRef.current,
      amount: amountRef.current,
      card_reader_type: eftposRef.current,
      card_reader_id: (_b = deviceRef.current) == null ? void 0 : _b.id,
      number: numRef.current,
      original_payment_number: custom == null ? void 0 : custom.original_payment_number,
      pay_param_base64: encodeURIComponent(
        btoa(
          encodeURIComponent(
            JSON.stringify({
              ...dataRef.current,
              number: numRef.current
            })
          )
        )
      )
    };
    import_payLog.default.setContext({ transactionNumber: numRef.current });
    if (isPay) {
      import_payLog.default.log("Payo：发起支付", { isPay, number: numRef.current });
      paymentRun({
        paymentType: import_payment.ActionType.Pay,
        paymentNum: numRef.current,
        orderId: orderIdRef.current,
        deviceId: (_c = deviceRef.current) == null ? void 0 : _c.id,
        params: apiParams,
        callbacks: {
          onSuccess: (res) => {
            import_payLog.default.log("Payo：支付成功", { code: res == null ? void 0 : res.code });
            success(res);
          },
          onError: (err) => {
            import_payLog.default.log("Payo：支付失败", { code: err == null ? void 0 : err.code });
            failRef.current(err, true);
          }
        }
      });
      return;
    } else {
      import_payLog.default.log("Payo：发起退款", { isPay, number: numRef.current });
      const resultPromise = api.refund(apiParams, { signal: controllerRef.current.signal });
      resultPromise.then((res) => {
        console.log("netRef.current111 = ", netRef.current);
        if (unloadRef.current || !netRef.current) {
          import_payLog.default.log("Payo：退款拦截", { isUnload: unloadRef.current, isNet: netRef.current });
          return;
        }
        if (res && `${res.code}` === "200") {
          import_payLog.default.log("Payo：退款成功", { res: JSON.stringify(res) });
          success(res);
          return;
        }
        return Promise.reject(res);
      }).catch((err) => {
        if (unloadRef.current || !netRef.current) {
          import_payLog.default.log("Payo：退款失败拦截", { isUnload: unloadRef.current, isNet: netRef.current });
          return;
        }
        if (!(err == null ? void 0 : err.code) || `${err.code}` === import_const.PayStatus.Timeout) {
          import_payLog.default.log("Payo：退款超时，转查询");
          checkApi();
          return;
        }
        import_payLog.default.log("Payo：退款失败", { code: err == null ? void 0 : err.code, message: err == null ? void 0 : err.message });
        failRef.current(err, true);
      });
    }
  }, [api, check, dispatch, onChange]);
  (0, import_react.useEffect)(
    () => () => {
      var _a;
      (_a = controllerRef.current) == null ? void 0 : _a.abort();
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
      paymentClean();
    },
    []
  );
  return /* @__PURE__ */ import_react.default.createElement(import_step.default, { ...props });
};
var Action = ({ onChange }) => {
  const dispatch = (0, import_store.useDispatch)();
  const { mode, client, order_id, number, device } = (0, import_store.useContextData)();
  const [isShowCancel, setIsShowCancel] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    const timer = setTimeout(() => {
      setIsShowCancel(true);
      import_payLog.default.log("Payo：30秒后显示取消按钮");
    }, 30 * 1e3);
    return () => {
      clearTimeout(timer);
    };
  }, []);
  const onManually = () => {
    import_payLog.default.log("Payo：点击手动标记");
    dispatch(
      (0, import_store.updateState)({
        manual: {
          title: import_utils.locales.getText("page.eftpos-pay.text.request.title")(mode),
          text: import_utils.locales.getText("page.eftpos-pay.text.request.text")(mode)
        }
      })
    );
    dispatch((0, import_store.updateComponent)("Manual", true));
  };
  const onCancel = () => {
    import_payLog.default.log("Payo：点击取消");
    onChange("fail", { number, uniquePaymentNumber: number, device, order_id });
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, client !== import_const.ClientEnum.Merchant && isShowCancel && /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onCancel
    },
    import_utils.locales.getText("page.eftpos-pay.text.cancel")
  ), client === import_const.ClientEnum.Merchant ? /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onManually
    },
    import_utils.locales.getText("page.eftpos-pay.text.manual.marking")
  ) : null);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  Action,
  POS
});
