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/device.tsx
var device_exports = {};
__export(device_exports, {
  default: () => device_default
});
module.exports = __toCommonJS(device_exports);
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_react = __toESM(require("react"));
var import_titlebar = __toESM(require("./component/header/titlebar"));
var import_const = require("./const");
var import_helper = require("./helper");
var import_ChevronRight = __toESM(require("@pisell/icon/es/ChevronRight"));
var import_store = require("./store");
var import_manufacturer = require("./manufacturer");
var import_device = require("./device.less");
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_payLog = __toESM(require("./utils/payLog"));
var device_default = ({
  api,
  onChange,
  onClose,
  className = "",
  device_number,
  isMobile,
  net,
  client,
  formatAmount = (number, precision, symbol) => `${symbol}${number}`,
  containerStyle = {}
}) => {
  const context = (0, import_useEngineContext.default)();
  const { isTerminal, interaction } = context.appHelper.utils || {};
  const store = (0, import_store.useContextData)();
  const { device, symbol, mode, eftpos, order_id } = store;
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [dataStaus, setDataStaus] = (0, import_react.useState)(true);
  const [list, setList] = (0, import_react.useState)([]);
  const dispatch = (0, import_store.useDispatch)();
  const timerRef = (0, import_react.useRef)();
  const onClick = (event) => {
    var _a;
    if (!net) {
      import_antd.message.open({
        key: "net-warning",
        type: "warning",
        content: import_utils.locales.getText("page.eftpos-pay.text.not.connected")
      });
      return;
    }
    const [index] = [Number(event.currentTarget.dataset.index)];
    import_payLog.default.log("手动选择设备", { deviceId: (_a = list[index]) == null ? void 0 : _a.id, index });
    setDevice(list[index]);
  };
  const triggerCloseButton = (bool) => {
    var _a, _b;
    if (!(isTerminal == null ? void 0 : isTerminal())) {
      return;
    }
    (_b = (_a = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a.postMessageToApp) == null ? void 0 : _b.call(_a, {
      module: "pos",
      key: "other",
      data: {
        key: bool ? "show_close_button" : "hide_close_button"
      }
    });
  };
  const closeFirstWithDelayShow = () => {
    timerRef.current && clearTimeout(timerRef.current);
    if (!(isTerminal == null ? void 0 : isTerminal())) {
      return;
    }
    triggerCloseButton(false);
    timerRef.current = setTimeout(() => {
      triggerCloseButton(true);
    }, 5e3);
  };
  const clearTimer = () => {
    if (timerRef.current) {
      clearTimeout(timerRef.current);
      timerRef.current = void 0;
    }
  };
  (0, import_ahooks.useMount)(() => {
    import_payLog.default.log("设备选择页展示");
    setLoading(true);
    closeFirstWithDelayShow();
    api.getDeviceList({ type: eftpos, status: "paired" }).then(
      (res) => {
        clearTimer();
        setLoading(false);
        if (res && Array.isArray(res.list) && res.list.length > 0) {
          import_payLog.default.log("设备列表加载成功", { count: res.list.length, hasDeviceNumber: !!device_number });
          if (device_number) {
            const hostDeviceList = res.list.filter(
              (item) => {
                var _a, _b;
                return (_b = (_a = item == null ? void 0 : item.setting) == null ? void 0 : _a.devices) == null ? void 0 : _b.some(
                  (i) => i.number === device_number
                );
              }
            );
            if (hostDeviceList.length >= 1) {
              setDataStaus(true);
              setList(setDeviceList(hostDeviceList));
              if (hostDeviceList.length === 1) {
                import_payLog.default.log("自动选择设备（device_number匹配）", { device: hostDeviceList[0] });
                setDevice(hostDeviceList[0]);
              }
              return;
            }
          }
          setDataStaus(true);
          setList(setDeviceList(res.list));
          if (res.list.length === 1) {
            import_payLog.default.log("自动选择设备（单设备）", { device: res.list[0] });
            setDevice(res.list[0]);
          } else {
            triggerCloseButton(true);
          }
          return;
        }
        import_payLog.default.log("设备列表为空");
        triggerCloseButton(true);
        setDataStaus(false);
      },
      () => {
        clearTimer();
        import_payLog.default.log("设备列表加载失败");
        triggerCloseButton(true);
        setDataStaus(false);
        setLoading(false);
      }
    );
  });
  (0, import_ahooks.useUnmount)(() => {
    timerRef.current && clearTimeout(timerRef.current);
  });
  const checkIsActiveWithDelay = async (time = 100) => {
    var _a, _b, _c;
    if (!(isTerminal == null ? void 0 : isTerminal())) {
      return true;
    }
    await new Promise((resolve) => setTimeout(resolve, time));
    if ((_a = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a.asyncDataManager) {
      try {
        const activeStatus = await ((_c = (_b = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _b.asyncDataManager) == null ? void 0 : _c.call(_b, {
          module: "get",
          key: "pay_webview_active"
        }));
        return activeStatus !== "unActive";
      } catch (error) {
        return true;
      }
    }
    return true;
  };
  const setDevice = async (device2) => {
    import_payLog.default.setContext({ deviceId: device2 == null ? void 0 : device2.id });
    dispatch((0, import_store.updateDevice)({ device: device2 }));
    if (typeof api.selectDevice === "function") {
      api.selectDevice(device2);
    }
    if (typeof onChange === "function") {
      if (mode === import_const.ModeEnum.Pay) {
        triggerCloseButton(false);
        const isActive = await checkIsActiveWithDelay(100);
        if (!isActive) {
          import_payLog.default.log("页面非活跃状态，阻断支付", { order_id, isActive });
          return;
        }
        if (device2.pay) {
          dispatch(
            (0, import_store.updateState)({
              pay: device2.pay
            })
          );
        } else {
          const amonunt = (0, import_manufacturer.getAmonunt)({ ...store, device: device2 });
          const pay = (0, import_helper.getPayAmonunt)(
            amonunt,
            (total) => formatAmount(total, 2, symbol)
          );
          dispatch((0, import_store.updateState)({ pay }));
        }
      }
      onChange("page", mode === import_const.ModeEnum.FullPay ? "amount" : "pay");
    }
  };
  const setDeviceList = (list2) => {
    return list2.map((item) => {
      const amonunt = (0, import_manufacturer.getAmonunt)({ ...store, device: item });
      const pay = (0, import_helper.getPayAmonunt)(
        amonunt,
        (total) => formatAmount(total, 2, symbol)
      );
      return { ...item, pay };
    });
  };
  return /* @__PURE__ */ import_react.default.createElement("div", { className: `pisell-lowcode__eft-pay-device-box ${className}` }, isMobile ? null : /* @__PURE__ */ import_react.default.createElement(import_titlebar.default, { type: "left-title-close", onClose }, dataStaus ? import_utils.locales.getText("page.eftpos-pay.text.device") : ""), dataStaus ? /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__eft-pay-device-list",
      style: {
        ...isMobile ? { marginTop: "20px" } : {},
        ...containerStyle || {}
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Spin,
      {
        spinning: loading,
        size: "large",
        style: { flex: 1, overflow: "auto", minHeight: "200px" }
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: { display: "flex", flexDirection: "column", gap: "10px" }
        },
        list.map(({ id, name, pay }, index) => /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: id,
            className: `pisell-lowcode__eft-pay-device ${id === (device == null ? void 0 : device.id) ? "active" : ""}`,
            "data-index": index,
            onClick,
            role: "button",
            tabIndex: index
          },
          /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-content" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-name" }, name), mode === import_const.ModeEnum.Refund ? null : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-money" }, pay.totalUnit), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-sucharge" }, import_utils.locales.getText(
            "page.eftpos-pay.text.surcharge.edit.inc.surcharge"
          ), ": ", formatAmount(`${pay.surcharge}`, 2, symbol), " (", import_utils.locales.getText(
            "page.eftpos-pay.text.surcharge.edit.rate"
          ), ":", pay.surRate, "% +", " ", formatAmount(`${pay.surMoney}`, 2, symbol), ")"))),
          /* @__PURE__ */ import_react.default.createElement("div", { style: { flexShrink: 0 } }, /* @__PURE__ */ import_react.default.createElement(
            import_ChevronRight.default,
            {
              style: { fontWeight: "600", fontSize: "24px" }
            }
          ))
        ))
      )
    )
  ) : /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__eft-pay-device-error",
      style: isMobile ? { marginTop: "20px" } : {}
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-tit" }, import_utils.locales.getText("page.eftpos-pay.text.device.no.title")),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, import_utils.locales.getText("page.eftpos-pay.text.device.no.add")),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, import_utils.locales.getText("page.eftpos-pay.text.device.no.web")),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-device-error-txt" }, import_utils.locales.getText("page.eftpos-pay.text.device.no.terminal"))
  ));
};
