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/eftpos/index.tsx
var eftpos_exports = {};
__export(eftpos_exports, {
  default: () => eftpos_default
});
module.exports = __toCommonJS(eftpos_exports);
var import_react = __toESM(require("react"));
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_utils = require("@pisell/utils");
var import_table = __toESM(require("./table"));
var import_device = __toESM(require("./device"));
var import_pos = __toESM(require("./pos"));
var import_drawer = __toESM(require("../booking/components/drawer"));
var import_log = __toESM(require("./log"));
var import_locales = __toESM(require("./locales"));
var import_hooks = require("./hooks");
var import_apiKey = __toESM(require("./icon/apiKey"));
var import_device2 = __toESM(require("./icon/device"));
var import_locales2 = require("../../utils/locales");
var import_hooks2 = require("./PairModal/hooks");
var import_PairModal = __toESM(require("./PairModal/index"));
var import_const = require("./const");
var import_materials = require("@pisell/materials");
var import_mx51SCI = __toESM(require("./assets/mx51SCI.svg"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_utils2 = require("../../utils");
var import_index = require("./index.less");
import_utils.locales.init(import_locales.default, (0, import_locales2.getLocale)());
var PosTabs = (0, import_react.forwardRef)(
  ({ Table: Table2, PosForm, style, onChange }, ref) => {
    const [active, setActive] = (0, import_react.useState)("device");
    const onClick = (event) => {
      const target = event.currentTarget;
      if (!target) {
        return;
      }
      const { key } = target.dataset;
      if (key) {
        setActive(key);
        onChange(key);
      }
    };
    (0, import_react.useImperativeHandle)(ref, () => ({
      setActive
    }));
    const items = [
      {
        key: "device",
        label: (active2) => /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_tabs-tab-label" }, /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `pisell-lowcode__pos_circle ${active2 ? "active" : ""}`
          },
          /* @__PURE__ */ import_react.default.createElement(import_apiKey.default, { color: active2 ? "#fff" : "#98A2B3" })
        ), /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            className: `pisell-lowcode__pos_tabs-tab-label-tlt ${active2 ? "active" : ""}`
          },
          import_utils.locales.getText("page.eftpos.text.device")
        )),
        children: Table2
      },
      {
        key: "setting",
        label: (active2) => /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_tabs-tab-label" }, /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            className: `pisell-lowcode__pos_circle ${active2 ? "active" : ""}`
          },
          /* @__PURE__ */ import_react.default.createElement(import_device2.default, { color: active2 ? "#fff" : "#98A2B3" })
        ), /* @__PURE__ */ import_react.default.createElement(
          "span",
          {
            className: `pisell-lowcode__pos_tabs-tab-label-tlt ${active2 ? "active" : ""}`
          },
          import_utils.locales.getText("page.eftpos.text.setting")
        )),
        children: PosForm
      }
    ];
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_tabs", style }, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_tabs-nav" }, items.map((item) => {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          key: item.key,
          style: {
            display: "contents"
          },
          "data-key": item.key,
          onClick
        },
        item.label(active === item.key)
      );
    })), /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_tab-content" }, items.map((item) => {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: `pisell-lowcode__pos_tabs-tabpane ${active === item.key ? "active" : ""}`,
          key: item.key
        },
        item.children
      );
    })));
  }
);
var eftpos_default = (props) => {
  const {
    name,
    zIndex,
    type = import_const.Eftpos.Payo,
    tableSize,
    getList,
    getField,
    getComm,
    onDel,
    onEdit,
    getPosComm,
    savePos,
    config,
    tyroUrl,
    tyroVersion,
    useTyroLog
  } = props;
  const context = (0, import_useEngineContext.default)();
  const utils = context.appHelper.utils || {};
  import_utils2.request.setRequest(utils == null ? void 0 : utils.request);
  const [page, setPage] = (0, import_react.useState)("list");
  const [messageApi, contextHolder] = import_antd.message.useMessage({
    prefixCls: "pisell-lowcode__pos_message"
  });
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [status, setStatus] = (0, import_react.useState)(import_const.DeviceEnum.Add);
  const tableRef = (0, import_react.useRef)();
  const deviceIdRef = (0, import_react.useRef)("");
  const [deviceItemList, setDeviceCommList] = (0, import_react.useState)([]);
  const [posItemList, setPosCommList] = (0, import_react.useState)([]);
  const [deviceItem, setDeviceItem] = (0, import_react.useState)();
  const [pairStatus, setPairStatus] = (0, import_react.useState)("");
  const [pairMessage, setPairMessage] = (0, import_react.useState)("");
  const [systemConfigStatus, setSystemConfigStatus] = (0, import_react.useState)(true);
  const posTabRef = (0, import_react.useRef)(null);
  const [posLoading, setPosLoading] = (0, import_react.useState)(false);
  const pairModalHook = (0, import_hooks2.usePairModal)();
  const pairRequest = (0, import_hooks.usePairRequest)();
  const checkPairRequest = (0, import_hooks.useCheckPairRequest)();
  const onDelDevice = (id) => {
    return onDel(id);
  };
  const onEditDevice = async (device) => {
    if (device) {
      deviceIdRef.current = device.id;
      const field2 = getField(type, import_const.DeviceEnum.Edit);
      const list2 = await (0, import_const.getCommByFields)({ field: field2, value: device, getComm });
      setStatus(import_const.DeviceEnum.Edit);
      setDeviceCommList(list2);
      setPage("edit");
      return;
    }
    setStatus(import_const.DeviceEnum.Add);
    const field = getField(type);
    const list = await (0, import_const.getCommByFields)({ field, getComm });
    console.log(list);
    setDeviceCommList(list);
    setPage("edit");
  };
  const onRepair = async (device) => {
    console.log("onRepair device = ", device);
    if (type === import_const.Eftpos.MX51) {
      try {
        setLoading(true);
        const checkPairResponse = await checkPairRequest.run({
          type,
          pair_response: device == null ? void 0 : device.response
        });
        console.log("checkPairResponse = ", checkPairResponse);
        if ((checkPairResponse == null ? void 0 : checkPairResponse.code) == 200) {
          messageApi.open({
            type: "warning",
            style: {
              zIndex: (zIndex || 9999) + 1
            },
            content: import_utils.locales.getText("page.eftpos.text.repair.message.warning")
          });
          return;
        }
      } catch (error) {
        console.error("onRepair error =>", error);
      } finally {
        setLoading(false);
      }
    }
    const field = getField(type, import_const.DeviceEnum.Repair);
    const list = await (0, import_const.getCommByFields)({ field, value: device, getComm });
    deviceIdRef.current = device.id;
    setDeviceCommList(list);
    setStatus(import_const.DeviceEnum.Repair);
    setPage("edit");
  };
  const pair = (0, import_hooks.usePairTerminalo)(type, { url: tyroUrl, version: tyroVersion });
  const onLog = (device) => {
    console.log(device);
    setDeviceItem(device);
    setPage("log");
  };
  const onSave = async (device, pair_response) => {
    console.log("device = ", device);
    console.log("pair_response = ", pair_response);
    const update = async () => {
      var _a;
      try {
        await onEdit({ ...device, type, pair_response }, status || "add");
        if (type === import_const.Eftpos.MX51 && (status === import_const.DeviceEnum.Add || status === import_const.DeviceEnum.Repair)) {
          messageApi.open({
            type: "success",
            style: {
              zIndex: (zIndex || 9999) + 1
            },
            content: /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__pos_message-custom-content_mx51" }, /* @__PURE__ */ import_react.default.createElement("span", null, "Terminal paired successfully."), /* @__PURE__ */ import_react.default.createElement("span", null, /* @__PURE__ */ import_react.default.createElement("span", null, "Pairing Name: ", ((_a = device == null ? void 0 : device.connection) == null ? void 0 : _a.pairing_nickname) || "-"), /* @__PURE__ */ import_react.default.createElement("span", null, "Pairing ID: ", (pair_response == null ? void 0 : pair_response.pairing_id) || "-")))
          });
        }
      } catch (error) {
        console.error("onSave error =>", error);
        messageApi.open({
          type: "error",
          style: {
            zIndex: (zIndex || 9999) + 1
          },
          content: (error == null ? void 0 : error.message) || import_utils.locales.getText("page.eftpos.text.pair.error")
        });
        return;
      } finally {
        setLoading(false);
      }
      await tableRef.current.loadData();
      setPage("list");
    };
    setLoading(true);
    if (type === "tyro" && status !== "edit") {
      pair({ ...config, ...device.connection }, (response) => {
        console.log("response =", response);
        setPairStatus(response.status);
        setPairMessage(response.message);
        if (response.status === "inProgress") {
          messageApi.open({
            type: "info",
            style: {
              zIndex: (zIndex || 9999) + 1
            },
            content: response.message
          });
          return;
        }
        if (response.status === "success") {
          messageApi.open({
            type: "success",
            style: {
              zIndex: (zIndex || 9999) + 1
            },
            content: response.message
          });
          device.connection.integrationKey = response.integrationKey;
          device.status = "paired";
          update();
          return;
        }
        messageApi.open({
          type: "warning",
          style: {
            zIndex: (zIndex || 9999) + 1
          },
          content: response.message
        });
        device.status = "unpaired";
        update();
      });
      return;
    }
    update();
  };
  const onClickByTip = () => {
    var _a;
    (_a = posTabRef.current) == null ? void 0 : _a.setActive("setting");
  };
  const getPos = (0, import_react.useCallback)(async () => {
    if (typeof getPosComm === "function") {
      setPosLoading(true);
      const list = (await getPosComm(type).catch(() => {
        setPosLoading(false);
      })).map((item) => {
        return {
          ...item,
          __sourceName: item.name
        };
      });
      setPosLoading(false);
      const obj = (0, import_const.getDefaultValue)(list);
      const status2 = Object.values(obj).every(Boolean);
      setSystemConfigStatus(status2);
      setPosCommList(list);
    }
  }, [getPosComm]);
  const onSavePos = (pos) => {
    if (typeof savePos === "function") {
      setPosLoading(true);
      savePos(type, pos).then(() => {
        getPos();
      }).catch(() => {
        setPosLoading(false);
      });
    }
  };
  (0, import_react.useEffect)(() => {
    setPairStatus("");
    setPairMessage("");
  }, [page]);
  const onBack = () => {
    setPage("list");
  };
  const onChangeTabs = (key) => {
    setPage("list");
  };
  (0, import_ahooks.useMount)(() => {
    if (typeof getPos === "function") {
      getPos();
    }
  });
  (0, import_react.useEffect)(() => {
    setPage("list");
  }, [type]);
  const onSavePair = async (device) => {
    const eftposList = [import_const.Eftpos.MX51];
    if (eftposList.includes(type) && (status === import_const.DeviceEnum.Add || status === import_const.DeviceEnum.Repair)) {
      try {
        setLoading(true);
        const response = await pairRequest.run({
          ...(device == null ? void 0 : device.connection) || {},
          type
        });
        if ((response == null ? void 0 : response.code) == 200) {
          pairModalHook.open({
            data: {
              type,
              device,
              pairResponse: response == null ? void 0 : response.data
            },
            onCancel: () => {
              pairModalHook.close();
            },
            onConfirm: () => {
              pairModalHook.close();
              onSave(device, response == null ? void 0 : response.data);
            }
          });
        }
      } catch (error) {
        console.error("onSavePair error =>", error);
        messageApi.open({
          type: "error",
          style: {
            zIndex: (zIndex || 9999) + 1
          },
          content: (error == null ? void 0 : error.message) || import_utils.locales.getText("page.eftpos.text.pair.error")
        });
      } finally {
        setLoading(false);
      }
    } else {
      onSave(device);
    }
  };
  if (type === import_const.Eftpos.Windcave) {
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
      PosTabs,
      {
        ref: posTabRef,
        Table: /* @__PURE__ */ import_react.default.createElement(
          import_table.default,
          {
            ref: tableRef,
            eftposName: name,
            type,
            useTyroLog,
            tableSize,
            getList,
            onDel: onDelDevice,
            onRepair,
            onEdit: onEditDevice,
            onLog,
            key: `postable${type}`,
            systemConfigStatus,
            onClickByTip
          }
        ),
        PosForm: /* @__PURE__ */ import_react.default.createElement(
          import_antd.Spin,
          {
            tip: "Loading...",
            spinning: posLoading,
            wrapperClassName: "pisell-lowcode__pos_setting_box"
          },
          /* @__PURE__ */ import_react.default.createElement(
            import_pos.default,
            {
              eftposName: name,
              onSave: onSavePos,
              formItemList: posItemList
            }
          )
        ),
        onChange: onChangeTabs
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_drawer.default,
      {
        open: page === "edit",
        onClose: onBack,
        title: import_utils.locales.getText("page.eftpos.text.device.add")(status, name),
        titleNoWrap: true,
        zIndex: zIndex || 9999,
        destroyOnClose: true,
        className: "pisell-lowcode__pos_drawer"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Spin,
        {
          tip: "Loading...",
          spinning: loading,
          wrapperClassName: "pisell-lowcode__pos_box"
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_device.default,
          {
            formItemList: deviceItemList,
            onSave,
            key: `posdevice${type}`
          },
          pairStatus ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: "Status" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { value: pairStatus, disabled: true })) : null,
          pairMessage ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: "Message" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { value: pairMessage, disabled: true })) : null
        )
      )
    ), /* @__PURE__ */ import_react.default.createElement(
      import_drawer.default,
      {
        open: page === "log",
        onClose: onBack,
        title: import_utils.locales.getText("page.eftpos.text.log"),
        titleNoWrap: true,
        zIndex: zIndex || 9999,
        destroyOnClose: true,
        className: "pisell-lowcode__pos_drawer pisell-lowcode__pos_drawer_log"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_log.default,
        {
          type,
          tyroUrl,
          tyroVersion,
          device: deviceItem
        }
      )
    ), contextHolder);
  }
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_table.default,
    {
      eftposName: name,
      ref: tableRef,
      type,
      useTyroLog,
      tableSize,
      getList,
      onDel: onDelDevice,
      onRepair,
      onLog,
      onEdit: onEditDevice,
      key: `table${type}`,
      systemConfigStatus,
      onClickByTip
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_drawer.default,
    {
      open: page === "edit",
      onClose: onBack,
      title: type === import_const.Eftpos.MX51 ? /* @__PURE__ */ import_react.default.createElement(
        "span",
        {
          style: {
            display: "inline-flex",
            alignItems: "center",
            gap: "4px"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(import_materials.Image, { src: import_mx51SCI.default, preview: false, width: 24 }),
        /* @__PURE__ */ import_react.default.createElement("span", null, import_utils.locales.getText("page.eftpos.text.simple.cloud.integration"))
      ) : import_utils.locales.getText("page.eftpos.text.device.add")(status, name),
      titleNoWrap: true,
      zIndex: zIndex || 9999,
      destroyOnClose: true,
      className: "pisell-lowcode__pos_drawer"
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Spin,
      {
        tip: "Loading...",
        spinning: loading,
        wrapperClassName: "pisell-lowcode__pos_box"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_device.default,
        {
          formItemList: deviceItemList,
          onSave: onSavePair,
          key: `device${type}`,
          type,
          status
        },
        pairStatus ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: "Status" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { value: pairStatus, disabled: true })) : null,
        pairMessage ? /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: "Message" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Input, { value: pairMessage, disabled: true })) : null
      )
    )
  ), /* @__PURE__ */ import_react.default.createElement(
    import_drawer.default,
    {
      open: page === "log",
      onClose: onBack,
      title: import_utils.locales.getText("page.eftpos.text.log"),
      titleNoWrap: true,
      zIndex: zIndex || 9999,
      destroyOnClose: true,
      className: "pisell-lowcode__pos_drawer pisell-lowcode__pos_drawer_log"
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_log.default,
      {
        type,
        tyroUrl,
        tyroVersion,
        device: deviceItem
      }
    )
  ), contextHolder, pairModalHook.visible && /* @__PURE__ */ import_react.default.createElement(import_PairModal.default, { ...pairModalHook.modalProps }));
};
