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/index.tsx
var eftposPay_exports = {};
__export(eftposPay_exports, {
  default: () => eftposPay_default
});
module.exports = __toCommonJS(eftposPay_exports);
var import_utils = require("@pisell/utils");
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_app = __toESM(require("./app"));
var import_tip = __toESM(require("./tip"));
var import_const = require("./const");
var import_locales = __toESM(require("./locales"));
var import_manufacturer = require("./manufacturer");
var import_store = require("./store");
var import_index = require("./index.less");
var import_locales2 = require("../../utils/locales");
var import_payLog = __toESM(require("./utils/payLog"));
var eftposPay_default = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h;
  import_utils.locales.init(import_locales.default, (0, import_locales2.getLocale)());
  const [check, setCheckStatus] = (0, import_react.useState)(
    props.type === import_const.EftposEnum.Tyro ? import_const.OrderEumn.Null : props.source === import_const.RestoreEumn.Restore ? import_const.OrderEumn.Restore : import_const.OrderEumn.Normal
  );
  const context = (0, import_useEngineContext.default)();
  (0, import_payLog.usePayLog)({
    paymentType: props.type,
    mode: props.mode || import_const.ModeEnum.Pay,
    orderId: (_a = props.params) == null ? void 0 : _a.order_id,
    extra: {
      initialParams: (props == null ? void 0 : props.params) || null,
      initialSource: (props == null ? void 0 : props.source) || "",
      initialDevice: (props == null ? void 0 : props.device) || null
    }
  });
  const [cardSurcharge, setCardSurcharge] = (0, import_react.useState)(0);
  const [receipt, setReceipt] = (0, import_react.useState)([]);
  const [updateTime, setTime] = (0, import_react.useState)("");
  console.log("context = ", context);
  const [historyData, setHistory] = (0, import_react.useState)();
  const { formatAmount, storage, store } = ((_b = context.appHelper) == null ? void 0 : _b.utils) || {
    store: {},
    formatAmount: (number, precision, symbol2) => `${symbol2}${number}`,
    storage: () => ({
      get: () => ""
    })
  };
  const channel = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    if (((_a2 = props == null ? void 0 : props.params) == null ? void 0 : _a2.platform) === "kiosk") {
      return "kiosk";
    }
    const rawChannel = ((_b2 = storage == null ? void 0 : storage.get) == null ? void 0 : _b2.call(storage, "channel")) || "";
    if (rawChannel === "terminal") {
      return "terminal";
    }
    if (rawChannel === "android_kiosk") {
      return "kiosk";
    }
    return "";
  }, [(_c = props == null ? void 0 : props.params) == null ? void 0 : _c.platform, storage]);
  (0, import_react.useEffect)(() => {
    import_payLog.default.setContext({ channel: channel || "web" });
  }, [channel]);
  const isMobile = (0, import_react.useMemo)(() => {
    if ((props == null ? void 0 : props.isWebPos) !== void 0 && typeof (props == null ? void 0 : props.isWebPos) === "boolean") {
      return !props.isWebPos;
    }
    return Boolean(channel);
  }, [channel, props.isWebPos]);
  const symbol = ((_f = (_e = (_d = store == null ? void 0 : store.getState) == null ? void 0 : _d.call(store)) == null ? void 0 : _e.global) == null ? void 0 : _f.symbol) || "$";
  const mode = (0, import_react.useMemo)(() => {
    if (props.source === import_const.RestoreEumn.Restore) {
      if (props.params) {
        if (props.params.mode) {
          return props.params.mode;
        }
      }
      return import_const.ModeEnum.Pay;
    }
    if (props.mode) {
      return props.mode;
    }
    return import_const.ModeEnum.Pay;
  }, [props.mode, props.source, props.params]);
  const state = (0, import_react.useMemo)(() => {
    const current = props.params && props.params.symbol ? props.params.symbol : symbol;
    if (props.source === import_const.RestoreEumn.Restore) {
      return props.params;
    }
    const initState = (0, import_manufacturer.getInitState)(
      props.type,
      props.params ? { mode, ...props.params, symbol: current } : { mode, symbol: current }
    );
    return {
      ...initState || {},
      originalParams: props.params || {}
    };
  }, [mode, props.params, props.type, symbol]);
  const stateRef = (0, import_react.useRef)(state);
  (0, import_react.useEffect)(() => {
    stateRef.current = state;
  }, [state]);
  const onChangeStatus = (0, import_react.useCallback)(
    (status, params, other) => {
      import_payLog.default.log("支付状态回调", { status, params, other });
      props.onChangeStatus(status, params, other);
    },
    []
  );
  const action = (0, import_react.useMemo)(() => {
    const act = (() => {
      if (state.action) {
        return state.action;
      }
      if (mode === import_const.ModeEnum.Pay || mode === import_const.ModeEnum.FullPay) {
        if (state.device && state.pay) {
          return import_const.RouteEnum.Pay;
        }
        if (state.device) {
          return import_const.RouteEnum.Amount;
        }
        return import_const.RouteEnum.DeviceList;
      }
      if (mode === import_const.ModeEnum.Refund) {
        if (state.device) {
          return import_const.RouteEnum.Pay;
        }
        return import_const.RouteEnum.DeviceList;
      }
      if (mode === import_const.ModeEnum.Query) {
        return import_const.RouteEnum.Pay;
      }
      throw Error("未知模式");
    })();
    onChangeStatus("page", act);
    return act;
  }, [mode, state]);
  (0, import_react.useEffect)(() => {
    document.body.id = "body";
  }, []);
  console.log("props?.params?.device_number = ", (_g = props == null ? void 0 : props.params) == null ? void 0 : _g.device_number);
  const api = (0, import_react.useMemo)(() => {
    if (typeof props.getApi === "function") {
      return props.getApi();
    }
    return {};
  }, [props.getApi]);
  (0, import_react.useEffect)(() => {
    if (props.source === import_const.RestoreEumn.Restore || props.type === import_const.EftposEnum.Tyro) {
      return;
    }
    import_payLog.default.log("交易检查：开始检查交易");
    api.getTransaction({
      order_id: stateRef.current.order_id,
      card_reader_type: stateRef.current.eftpos,
      receive_status: "unprocessed"
    }).then((res) => {
      if (!Array.isArray(res.data) || res.data.length === 0) {
        import_payLog.default.log("交易检查：无未处理交易");
        setCheckStatus(import_const.OrderEumn.Null);
        return;
      }
      const currentMode = stateRef.current.mode === import_const.ModeEnum.FullPay ? import_const.ModeEnum.Pay : stateRef.current.mode;
      const list = res.data.filter(
        (item) => item.action === currentMode
      );
      if (list.length === 0) {
        setCheckStatus(import_const.OrderEumn.Null);
        return;
      }
      const latest = list.pop();
      const numberList = list.map((item) => item.number);
      if (latest.status === import_const.OrderEumn.Failed) {
        import_payLog.default.log("交易检查：最新交易已失败", { number: latest.number });
        setCheckStatus(latest.status);
        onChangeStatus("mark_tx_processed", [
          ...numberList,
          latest.number
        ]);
        return;
      }
      if (list.length > 0) {
        onChangeStatus("mark_tx_processed", numberList);
      }
      const { pay_param_base64, card_reader_surcharge, receipt: receipt2 } = (latest == null ? void 0 : latest.metadata) || {};
      setTime(latest.updated_at);
      setCardSurcharge(card_reader_surcharge || 0);
      setReceipt(receipt2 || []);
      if (!pay_param_base64) {
        setCheckStatus(import_const.OrderEumn.Failed);
        return;
      }
      try {
        const data = JSON.parse(
          decodeURIComponent(atob(decodeURIComponent(pay_param_base64)))
        );
        setHistory(data);
        import_payLog.default.log("交易检查：发现待处理交易", {
          status: latest.status,
          number: latest.number
        });
        setCheckStatus(latest.status);
      } catch (e) {
        import_payLog.default.log("交易检查：解析交易数据失败", { error: e });
        setCheckStatus(import_const.OrderEumn.Failed);
        return;
      }
    });
  }, []);
  if (check === import_const.OrderEumn.Normal) {
    return null;
  }
  if (check === import_const.OrderEumn.Succeed) {
    return /* @__PURE__ */ import_react.default.createElement(import_store.Provider, { state: historyData }, /* @__PURE__ */ import_react.default.createElement(
      import_tip.default,
      {
        cardSurcharge,
        receipts: receipt,
        onChangeStatus,
        onChangeParams: props.onChangeParams,
        formatAmount,
        successTime: updateTime,
        className: isMobile ? "pisell-lowcode__eft-pay-terminal" : ""
      }
    ));
  }
  return /* @__PURE__ */ import_react.default.createElement(import_store.Provider, { state: check === import_const.OrderEumn.Pending ? historyData : state }, /* @__PURE__ */ import_react.default.createElement(
    import_app.default,
    {
      api,
      channel,
      params: props.params,
      onChangeStatus,
      terminal: props.terminal,
      onChangeParams: props.onChangeParams,
      action: check === import_const.OrderEumn.Pending ? import_const.ModeEnum.Pay : action,
      source: props.source,
      tyroUrl: props.tyroUrl,
      tyroVersion: props.tyroVersion,
      device_number: (_h = props == null ? void 0 : props.params) == null ? void 0 : _h.device_number,
      isMobile,
      formatAmount,
      styles: props.styles
    }
  ));
};
