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/plus/saasDevice/appPeripheral/components/PeripheralConnectionCardContainer.tsx
var PeripheralConnectionCardContainer_exports = {};
__export(PeripheralConnectionCardContainer_exports, {
  default: () => PeripheralConnectionCardContainer_default
});
module.exports = __toCommonJS(PeripheralConnectionCardContainer_exports);
var import_react = __toESM(require("react"));
var import_classnames = __toESM(require("classnames"));
var import_materials = require("@pisell/materials");
var import_deviceDetail = require("../../devicePlanning/modules/deviceDetail");
var import_usePeripheralRuntime = require("../hooks/usePeripheralRuntime");
var import_usePeripheralLogger = require("../hooks/usePeripheralLogger");
var import_peripheralCardModel = require("../utils/peripheralCardModel");
var import_PeripheralActionModal = __toESM(require("./PeripheralActionModal"));
var import_PeripheralConnectionCard = __toESM(require("./PeripheralConnectionCard"));
var import_PhysicalDeviceSelectModal = __toESM(require("./PhysicalDeviceSelectModal"));
var toDeviceDetailRecord = (device, translation) => {
  var _a, _b, _c;
  if (!device) return void 0;
  const link = device.link || "unlinked";
  return {
    id: device.id,
    name: translation(device.name),
    typeName: translation((_a = device.type) == null ? void 0 : _a.name) || device.type_code,
    modelName: translation((_b = device.model) == null ? void 0 : _b.name) || device.model_code,
    profileName: translation((_c = device.profile) == null ? void 0 : _c.name) || (device.profile_id ? String(device.profile_id) : "-"),
    link,
    status: device.type_kind === "dumb" ? device.status || "unknown" : link === "linked" ? device.status || "offline" : "unknown",
    structure: device.structure,
    typeCode: device.type_code,
    modelCode: device.model_code,
    _raw: device
  };
};
var PeripheralConnectionCardContainer = ({
  row,
  variant,
  getText,
  translation,
  getAppInstance,
  onPhysicalChange,
  onUsageChange,
  onTest,
  onEdit,
  onRemove,
  onDeleteDevice,
  setupFlowState,
  onSetupFlowChange,
  autoOpenPhysicalSelect,
  onAutoOpenPhysicalSelectHandled
}) => {
  const { addLog: addActionLog } = (0, import_usePeripheralLogger.usePeripheralLogger)();
  const [actionsOpen, setActionsOpen] = (0, import_react.useState)(false);
  const [physicalSelectOpen, setPhysicalSelectOpen] = (0, import_react.useState)(false);
  const [ignoreConfirmOpen, setIgnoreConfirmOpen] = (0, import_react.useState)(false);
  const [detailOpen, setDetailOpen] = (0, import_react.useState)(false);
  const [removing, setRemoving] = (0, import_react.useState)(false);
  const [testLoading, setTestLoading] = (0, import_react.useState)(false);
  const autoConnectKeyRef = (0, import_react.useRef)("");
  const {
    isRuntimeSubmitting,
    connectKnownPhysicalDevice,
    handleRemovePeripheral,
    handleUpdatePeripheralUsage,
    connectSelectedPhysicalDevice
  } = (0, import_usePeripheralRuntime.usePeripheralRuntime)({
    row,
    getAppInstance,
    getText,
    onPhysicalChange,
    onUsageChange
  });
  const model = (0, import_peripheralCardModel.createPeripheralConnectionCardModel)({
    row,
    setupFlowState,
    translation
  });
  const isPhone = variant === "phone";
  const submitting = isRuntimeSubmitting || removing || (setupFlowState == null ? void 0 : setupFlowState.step) === "connecting";
  const isComponentConnection = row.connection.type === "component";
  const candidates = (setupFlowState == null ? void 0 : setupFlowState.candidates) || [];
  const detailRecord = (0, import_react.useMemo)(
    () => toDeviceDetailRecord(row.peripheral, translation),
    [row.peripheral, translation]
  );
  const getNextFlowAfterConnection = (physicalDevice) => {
    var _a;
    if ((physicalDevice == null ? void 0 : physicalDevice.is_connect) && ((_a = row.peripheral) == null ? void 0 : _a.type_code) === "label_printer" && !row.usage) {
      return { step: "configuring" };
    }
    return { step: "idle" };
  };
  const openPhysicalSelect = () => {
    addActionLog("appPeripheral-打开物理设备选择弹窗", {
      connectionId: row.id,
      candidateCount: candidates.length,
      uuids: candidates.map((device) => device.uuid)
    });
    setPhysicalSelectOpen(true);
  };
  const handleOpenCardActions = () => {
    addActionLog("appPeripheral-点击外设卡片", {
      connectionId: row.id,
      status: model.status,
      isPhysicalSetupAction: model.isPhysicalSetupAction
    });
    if (model.isPhysicalSetupAction) {
      openPhysicalSelect();
      return;
    }
    setActionsOpen(true);
  };
  const openIgnoreConfirm = () => {
    addActionLog(
      isComponentConnection ? "appPeripheral-卡片点击删除组件" : "appPeripheral-卡片点击忘记连接",
      {
        connectionId: row.id
      }
    );
    setIgnoreConfirmOpen(true);
  };
  const getHardwareInfo = () => {
    const device = model.physicalDevice || row.physical;
    if (device == null ? void 0 : device.ip) {
      return {
        label: getText("pisell2.saas.app-peripheral.hardware.ip"),
        value: device.ip
      };
    }
    if (device == null ? void 0 : device.mac) {
      return {
        label: getText("pisell2.saas.app-peripheral.hardware.mac"),
        value: device.mac
      };
    }
    if (device == null ? void 0 : device.port) {
      return {
        label: getText("pisell2.saas.app-peripheral.hardware.port"),
        value: device.port
      };
    }
    return void 0;
  };
  const hardware = getHardwareInfo();
  const handleTest = async () => {
    var _a, _b;
    addActionLog("appPeripheral-点击测试外设", {
      connectionId: row.id,
      uuid: ((_a = model.physicalDevice) == null ? void 0 : _a.uuid) || ((_b = row.physical) == null ? void 0 : _b.uuid),
      usage: row.usage
    });
    setTestLoading(true);
    try {
      await (onTest == null ? void 0 : onTest({
        connection: row.connection,
        targetDevice: row.peripheral,
        physicalDevice: model.physicalDevice || row.physical,
        peripheralUsage: row.usage
      }));
      addActionLog("appPeripheral-测试外设完成", {
        connectionId: row.id
      });
    } finally {
      setTestLoading(false);
    }
  };
  const handleOpenDetail = () => {
    if (!detailRecord) return;
    addActionLog("appPeripheral-操作弹窗点击详情", {
      connectionId: row.id,
      targetDeviceId: row.peripheralId
    });
    setActionsOpen(false);
    setDetailOpen(true);
  };
  const handleConnect = async () => {
    var _a;
    addActionLog("appPeripheral-用户点击connect", {
      connectionId: row.id,
      uuid: (_a = row.physical) == null ? void 0 : _a.uuid
    });
    onSetupFlowChange(row.id, { step: "connecting" });
    try {
      const result = await connectKnownPhysicalDevice(row);
      onSetupFlowChange(
        row.id,
        getNextFlowAfterConnection(result == null ? void 0 : result.physicalDevice)
      );
    } catch (e) {
      onSetupFlowChange(row.id, { step: "idle", error: e });
    }
  };
  (0, import_react.useEffect)(() => {
    const target = setupFlowState == null ? void 0 : setupFlowState.target;
    const targetKey = (setupFlowState == null ? void 0 : setupFlowState.step) === "connecting" && setupFlowState.autoStart ? `${row.id}:${(target == null ? void 0 : target.ip) || (target == null ? void 0 : target.uuid) || "manual"}` : "";
    if (!targetKey || autoConnectKeyRef.current === targetKey) return;
    autoConnectKeyRef.current = targetKey;
    const runAutoConnect = async () => {
      addActionLog("appPeripheral-精确IP自动connect", {
        connectionId: row.id,
        target
      });
      try {
        const result = await connectKnownPhysicalDevice(row, { silent: true });
        onSetupFlowChange(
          row.id,
          getNextFlowAfterConnection(result == null ? void 0 : result.physicalDevice)
        );
      } catch (e) {
        onSetupFlowChange(row.id, { step: "idle", error: e });
      }
    };
    runAutoConnect();
  }, [
    connectKnownPhysicalDevice,
    onSetupFlowChange,
    row,
    setupFlowState == null ? void 0 : setupFlowState.autoStart,
    setupFlowState == null ? void 0 : setupFlowState.step,
    setupFlowState == null ? void 0 : setupFlowState.target
  ]);
  (0, import_react.useEffect)(() => {
    if (!autoOpenPhysicalSelect || !model.isPhysicalSetupAction) return;
    openPhysicalSelect();
    onAutoOpenPhysicalSelectHandled == null ? void 0 : onAutoOpenPhysicalSelectHandled(row.id);
  }, [
    autoOpenPhysicalSelect,
    model.isPhysicalSetupAction,
    onAutoOpenPhysicalSelectHandled,
    openPhysicalSelect,
    row.id
  ]);
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_PeripheralConnectionCard.default,
    {
      model,
      getText,
      onOpenActions: handleOpenCardActions,
      onOpenPhysicalSelect: openPhysicalSelect,
      onConnect: handleConnect
    }
  ), /* @__PURE__ */ import_react.default.createElement(
    import_PeripheralActionModal.default,
    {
      open: actionsOpen,
      model,
      variant,
      submitting,
      testLoading,
      getText,
      onClose: () => {
        addActionLog("appPeripheral-关闭外设操作弹窗", {
          connectionId: row.id
        });
        setActionsOpen(false);
      },
      onEdit: () => {
        addActionLog("appPeripheral-操作弹窗点击编辑", {
          connectionId: row.id,
          targetDeviceId: row.peripheralId
        });
        setActionsOpen(false);
        onEdit(row.connection);
      },
      onDetail: handleOpenDetail,
      onConnect: () => {
        addActionLog("appPeripheral-操作弹窗点击连接", {
          connectionId: row.id
        });
        handleConnect();
      },
      onTest: handleTest,
      onIgnore: () => {
        openIgnoreConfirm();
      },
      onSelectUsage: (usage) => {
        addActionLog("appPeripheral-选择打印机角色", {
          connectionId: row.id,
          usage
        });
        handleUpdatePeripheralUsage(row, usage).then(() => {
          onSetupFlowChange(row.id, { step: "idle" });
        });
      }
    }
  ), detailOpen && detailRecord ? /* @__PURE__ */ import_react.default.createElement(
    import_deviceDetail.DeviceDetailDrawer,
    {
      key: detailRecord.id,
      open: true,
      readonly: true,
      initialTab: "info",
      record: detailRecord,
      getText,
      translation,
      onClose: () => {
        addActionLog("appPeripheral-关闭设备详情抽屉", {
          connectionId: row.id,
          targetDeviceId: row.peripheralId
        });
        setDetailOpen(false);
      }
    }
  ) : null, ignoreConfirmOpen ? /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open: true,
      title: getText(
        isComponentConnection ? "pisell2.saas.app-peripheral.delete-component" : "pisell2.saas.app-peripheral.ignore-connection"
      ),
      headerDivider: false,
      okText: getText(
        isComponentConnection ? "pisell2.saas.app-peripheral.delete-confirm" : "pisell2.saas.app-peripheral.ignore-confirm"
      ),
      cancelText: getText("pisell2.saas.app-peripheral.cancel"),
      okButtonProps: {
        block: true,
        size: "large",
        danger: true,
        loading: removing,
        onClick: async () => {
          var _a, _b;
          addActionLog(
            isComponentConnection ? "appPeripheral-确认删除组件" : "appPeripheral-确认忘记连接",
            {
              connectionId: row.id,
              uuid: ((_a = model.physicalDevice) == null ? void 0 : _a.uuid) || ((_b = row.physical) == null ? void 0 : _b.uuid)
            }
          );
          setRemoving(true);
          try {
            if (isComponentConnection) {
              await onDeleteDevice(row.connection);
            } else {
              await onRemove(row.connection);
              await handleRemovePeripheral(row);
            }
            setIgnoreConfirmOpen(false);
            setPhysicalSelectOpen(false);
            setActionsOpen(false);
            addActionLog(
              isComponentConnection ? "appPeripheral-删除组件完成" : "appPeripheral-忘记连接完成",
              {
                connectionId: row.id
              }
            );
          } finally {
            setRemoving(false);
          }
        }
      },
      cancelButtonProps: {
        block: true,
        size: "large",
        type: "default",
        disabled: removing,
        onClick: () => {
          addActionLog(
            isComponentConnection ? "appPeripheral-取消删除组件确认" : "appPeripheral-取消忘记连接确认",
            {
              connectionId: row.id
            }
          );
          setIgnoreConfirmOpen(false);
        }
      },
      width: isPhone ? "100%" : 460,
      platform: isPhone ? "h5" : void 0,
      mobileModalHeight: isPhone ? "auto" : void 0,
      destroyOnClose: true,
      maskClosable: !removing,
      className: (0, import_classnames.default)("saas-app-peripheral-ignore-modal", {
        "saas-app-peripheral-ignore-modal--phone": isPhone
      }),
      onCancel: () => {
        if (removing) return;
        addActionLog(
          isComponentConnection ? "appPeripheral-关闭删除组件确认弹窗" : "appPeripheral-关闭忘记连接确认弹窗",
          {
            connectionId: row.id
          }
        );
        setIgnoreConfirmOpen(false);
      },
      bodyStyle: { paddingBottom: "24px" }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-peripheral-ignore-modal__desc" }, getText(
      isComponentConnection ? "pisell2.saas.app-peripheral.delete-component-desc" : "pisell2.saas.app-peripheral.ignore-desc"
    )),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "saas-app-peripheral-ignore-modal__details" }, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("span", null, getText("pisell2.saas.app-peripheral.connection-type")), /* @__PURE__ */ import_react.default.createElement("strong", null, model.connectionTypeLabel || "-")), hardware ? /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("span", null, hardware.label), /* @__PURE__ */ import_react.default.createElement("strong", null, hardware.value)) : null)
  ) : null, /* @__PURE__ */ import_react.default.createElement(
    import_PhysicalDeviceSelectModal.default,
    {
      state: physicalSelectOpen ? {
        row,
        devices: candidates
      } : void 0,
      variant,
      submitting,
      searching: (setupFlowState == null ? void 0 : setupFlowState.step) === "searching",
      getText,
      onClose: () => setPhysicalSelectOpen(false),
      onForgetConnection: () => {
        openIgnoreConfirm();
      },
      onSelect: (device) => {
        addActionLog("appPeripheral-选择物理设备候选", {
          connectionId: row.id,
          uuid: device.uuid,
          connectType: device.connect_type
        });
        setPhysicalSelectOpen(false);
        onSetupFlowChange(row.id, {
          step: device.is_connect ? "idle" : "connecting",
          target: device
        });
        connectSelectedPhysicalDevice(row, device).then((result) => {
          onSetupFlowChange(
            row.id,
            getNextFlowAfterConnection(result == null ? void 0 : result.physicalDevice)
          );
        }).catch((error) => {
          onSetupFlowChange(row.id, { step: "idle", error });
        });
      }
    }
  ));
};
var PeripheralConnectionCardContainer_default = PeripheralConnectionCardContainer;
