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/windcave/windcave.tsx
var windcave_exports = {};
__export(windcave_exports, {
  default: () => windcave_default
});
module.exports = __toCommonJS(windcave_exports);
var import_utils = require("@pisell/utils");
var import_react = __toESM(require("react"));
var import_step = __toESM(require("../component/step/step"));
var import_const = require("../const");
var import_helper = require("../helper");
var import_hooks = require("../hooks");
var import_store = require("../store");
var import_const2 = require("./const");
var import_helper2 = require("./helper");
var import_receiptAction = __toESM(require("./receiptAction"));
var Minute = 1e3 * 60;
var windcave_default = ({
  api,
  onChange,
  formatAmount = (number, precision, symbol) => `${symbol}${number}`
}) => {
  const { custom, status } = (0, import_store.useContextData)();
  const {
    deviceRef,
    payRef,
    numRef,
    orderIdRef,
    modeRef,
    statusRef,
    netRef,
    symbolRef,
    amountRef,
    eftposRef,
    dataRef
  } = (0, import_hooks.useStoreRef)();
  const dispatch = (0, import_store.useDispatch)();
  const fail = (0, import_helper2.useFail)();
  const failRef = (0, import_react.useRef)(fail);
  const unloadRef = (0, import_react.useRef)(false);
  const stepRef = (0, import_react.useRef)(custom == null ? void 0 : custom.step);
  const listRef = (0, import_react.useRef)(custom == null ? void 0 : custom.list);
  const initRef = (0, import_react.useRef)(false);
  const clearRef = (0, import_react.useRef)();
  const isReceiptPage = (0, import_react.useMemo)(
    () => (custom == null ? void 0 : custom.step) === import_const2.StepStatusEnum.Receipt,
    [custom == null ? void 0 : custom.step]
  );
  const receiptPage = (0, import_react.useMemo)(
    () => (custom == null ? void 0 : custom.step) !== import_const2.StepStatusEnum.Receipt ? "" : (custom == null ? void 0 : custom.receiptPage) || "receipt",
    [custom == null ? void 0 : custom.step, custom == null ? void 0 : custom.receiptPage]
  );
  const [disabled, setDisabled] = (0, import_react.useState)(false);
  (0, import_react.useEffect)(() => {
    listRef.current = custom == null ? void 0 : custom.list;
  }, [custom == null ? void 0 : custom.list]);
  (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]);
  const [run, validateRef] = (0, import_helper2.useValidate)(api.check, Minute, (res) => {
    let receipt = Array.isArray(res == null ? void 0 : res.receipt) ? res.receipt : [res.receipt];
    receipt = receipt.filter((item) => typeof item === "string").filter(Boolean);
    dispatch(
      (0, import_store.updateCustom)({
        list: listRef.current.map((item) => ({
          ...item,
          status: "resolve"
        })),
        card_reader_surcharge: (res == null ? void 0 : res.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: (res == null ? void 0 : res.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 controllerRef = (0, import_react.useRef)();
  (0, import_react.useEffect)(() => {
    var _a, _b;
    if (statusRef.current === import_const.StatusEnum.Success || statusRef.current === import_const.StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    if (stepRef.current === import_const2.StepStatusEnum.Receipt) {
      if (import_const.StatusEnum.Loading === statusRef.current) {
        run();
      } else {
        run(-1);
      }
      return;
    }
    controllerRef.current = new AbortController();
    if (numRef.current) {
      run();
      return;
    }
    console.log("modeRef.current = ", modeRef.current);
    numRef.current = (0, import_helper.getUuid)();
    dispatch(
      (0, import_store.updateState)({
        number: numRef.current
      })
    );
    const isPay = modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay;
    let _params = {};
    if (isPay) {
      _params = {
        ...(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,
          "service_charge": {
            "amount": payRef.current.surMoney,
            "percentage": payRef.current.surPercentRate
          },
          "original_amount": payRef.current.amount
        } : {},
        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
              })
            )
          )
        )
      };
    } else {
      _params = {
        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,
        pay_param_base64: encodeURIComponent(
          btoa(
            encodeURIComponent(
              JSON.stringify({
                ...dataRef.current,
                number: numRef.current
              })
            )
          )
        )
      };
    }
    const resultPromise = isPay ? api.pay(_params, { signal: controllerRef.current.signal }) : api.refund(_params, { signal: controllerRef.current.signal });
    resultPromise.then((res) => {
      var _a2, _b2;
      if (unloadRef.current || !netRef.current) {
        return;
      }
      if (res && `${res.code}` === "200" && res.data && res.data.txn_status_id) {
        (_a2 = validateRef.current) == null ? void 0 : _a2.call(validateRef, res, true);
        return;
      }
      (0, import_utils.sendWarningLog)({
        title: "windcave支付失败",
        content: [
          { key: "res", value: JSON.stringify(res) },
          { key: "params", value: JSON.stringify(_params) }
        ]
      });
      (_b2 = failRef.current) == null ? void 0 : _b2.call(
        failRef,
        res,
        stepRef.current >= import_const2.StepStatusEnum.Account
      );
    }).catch((res) => {
      var _a2;
      let isNoNet = unloadRef.current || !netRef.current;
      (0, import_utils.sendWarningLog)({
        title: "windcave支付失败",
        content: [
          { key: "error", value: JSON.stringify(res) },
          { key: "params", value: JSON.stringify(_params) },
          { key: "isNoNet", value: isNoNet ? "1" : "0" }
        ]
      });
      if (isNoNet) {
        return;
      }
      (_a2 = failRef.current) == null ? void 0 : _a2.call(
        failRef,
        res,
        stepRef.current >= import_const2.StepStatusEnum.Account
      );
    });
    return;
  }, [api, run, dispatch]);
  const onCancel = () => {
    setDisabled(true);
    api.update({
      type: "CANCEL",
      number: numRef.current
    });
  };
  (0, import_react.useEffect)(
    () => () => {
      var _a, _b;
      unloadRef.current = true;
      (_b = (_a = controllerRef.current) == null ? void 0 : _a.abort) == null ? void 0 : _b.call(_a);
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    },
    []
  );
  const onChangeReceipt = (status2) => {
    if (status2) {
      run();
    }
  };
  (0, import_react.useEffect)(() => {
    var _a;
    if (listRef.current.length === 0) {
      let totalUnit = "";
      if (modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay) {
        totalUnit = (_a = payRef.current) == null ? void 0 : _a.totalUnit;
      } else if (modeRef.current === import_const.ModeEnum.Refund) {
        if (payRef.current) {
          totalUnit = payRef.current.totalUnit;
        } else {
          totalUnit = formatAmount(amountRef.current, 2, symbolRef.current);
          dispatch(
            (0, import_store.updateState)({
              pay: {
                total: amountRef.current,
                totalUnit
              }
            })
          );
        }
      }
      const nextStep = (0, import_const2.getStepMapping)(import_const2.StepStatusEnum.Free, {
        money: totalUnit,
        mode: modeRef.current
      });
      dispatch(
        (0, import_store.updateCustom)({
          list: [nextStep],
          step: import_const2.StepStatusEnum.Free
        })
      );
    }
  }, [dispatch]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, receiptPage !== "again" ? (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,
      className: item.type === import_const2.StemTypeEnum.Passive && item.status === "pedding" ? "pisell-lowcode__eft-pay-step-item-warn" : ""
    }
  )) : null, receiptPage === "again" ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-warn-text pisell-lowcode__eft-pay-body" }, import_utils.locales.getText("page.eftpos-pay.text.signature.text")(
    modeRef.current
  )) : null, 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.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), !isReceiptPage && status !== import_const.StatusEnum.Success ? /* @__PURE__ */ import_react.default.createElement(
    import_receiptAction.default,
    {
      index: custom == null ? void 0 : custom.step,
      onCancel,
      disabled
    }
  ) : null, isReceiptPage ? /* @__PURE__ */ import_react.default.createElement(import_receiptAction.ReceiptAction, { api, onChange: onChangeReceipt }) : null);
};
