var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/appPeripheral/hooks/usePeripheralRuntime.ts
var usePeripheralRuntime_exports = {};
__export(usePeripheralRuntime_exports, {
  usePeripheralRuntime: () => usePeripheralRuntime
});
module.exports = __toCommonJS(usePeripheralRuntime_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_peripheralConnectionService = require("../services/peripheralConnectionService");
var import_peripheralRuntime = require("../utils/peripheralRuntime");
var isLabelPrinter = (connection) => {
  var _a;
  return ((_a = connection.target_device) == null ? void 0 : _a.type_code) === "label_printer";
};
var usePeripheralRuntime = ({
  row,
  getAppInstance,
  getText,
  onPhysicalChange,
  onUsageChange
}) => {
  const [runtimeState, setRuntimeState] = (0, import_react.useState)();
  const [physicalSelect, setPhysicalSelect] = (0, import_react.useState)();
  const inspectingRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const bootstrappedRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const markedDisconnectedRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const rowRef = (0, import_react.useRef)(row);
  const getPeripheralPlugin = (0, import_ahooks.useMemoizedFn)(
    () => {
      var _a, _b;
      return (_b = (_a = getAppInstance()) == null ? void 0 : _a.getPlugin) == null ? void 0 : _b.call(_a, "peripheral");
    }
  );
  const addRuntimeLog = (0, import_ahooks.useMemoizedFn)(
    (title, metadata, type = "info") => {
      var _a, _b, _c;
      (_c = (_b = (_a = getAppInstance()) == null ? void 0 : _a.logger) == null ? void 0 : _b.addLog) == null ? void 0 : _c.call(_b, {
        type,
        title,
        metadata
      });
    }
  );
  const patchRuntimeState = (0, import_ahooks.useMemoizedFn)((state) => {
    setRuntimeState((prev) => ({
      ...prev,
      ...state
    }));
  });
  const applyBinding = (0, import_ahooks.useMemoizedFn)(
    (nextRow, binding) => {
      onPhysicalChange(nextRow.id, binding.physical_device);
      onUsageChange(nextRow.id, binding.peripheral_usage);
      patchRuntimeState({
        status: binding.is_connect ? "connected" : "disconnected",
        physicalDevice: binding.physical_device,
        loading: false
      });
    }
  );
  const getKnownPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    (targetRow) => (runtimeState == null ? void 0 : runtimeState.physicalDevice) || targetRow.physical
  );
  const findPhysicalDevices = (0, import_ahooks.useMemoizedFn)(
    async (targetConnection, uuid) => {
      const plugin = getPeripheralPlugin();
      if (!(plugin == null ? void 0 : plugin.findList)) {
        throw new Error("Peripheral plugin is not available.");
      }
      const statuses = ["CONNECTED", "NOT_CONNECT"];
      const requests = statuses.map((status) => (0, import_peripheralRuntime.buildFindListParams)(targetConnection, status, uuid)).filter(Boolean);
      if (!requests.length) return [];
      addRuntimeLog("appPeripheral-插件findList开始", {
        connectionId: targetConnection.id,
        uuid,
        requests
      });
      const results = await Promise.allSettled(
        requests.map((params) => {
          var _a;
          return (_a = plugin.findList) == null ? void 0 : _a.call(plugin, params);
        })
      );
      const devices = (0, import_peripheralRuntime.uniquePeripheralDevices)(
        results.flatMap((result) => {
          var _a;
          if (result.status !== "fulfilled") return [];
          const devices2 = (_a = result.value) == null ? void 0 : _a.data;
          return Array.isArray(devices2) ? devices2 : [];
        })
      );
      addRuntimeLog("appPeripheral-插件findList完成", {
        connectionId: targetConnection.id,
        uuid,
        resultCount: devices.length,
        failedCount: results.filter((result) => result.status === "rejected").length
      });
      return devices;
    }
  );
  const markDisconnectedOnce = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice) => {
      const alreadyMarked = markedDisconnectedRef.current.has(targetRow.id);
      if (!alreadyMarked) {
        markedDisconnectedRef.current.add(targetRow.id);
      }
      const knownPhysicalDevice = physicalDevice || getKnownPhysicalDevice(targetRow);
      const nextPhysicalDevice = knownPhysicalDevice ? {
        ...knownPhysicalDevice,
        is_connect: false,
        status_code: knownPhysicalDevice.status_code || "-1"
      } : void 0;
      if (nextPhysicalDevice && !alreadyMarked) {
        const result = await (0, import_peripheralConnectionService.savePeripheralConnectionStatus)({
          app: getAppInstance(),
          connection: targetRow.connection,
          physicalDevice: nextPhysicalDevice,
          peripheralUsage: targetRow.usage
        });
        applyBinding(targetRow, result.binding);
      }
      addRuntimeLog("appPeripheral-运行态收敛为断连", {
        connectionId: targetRow.id,
        uuid: nextPhysicalDevice == null ? void 0 : nextPhysicalDevice.uuid,
        alreadyMarked
      });
      patchRuntimeState({
        status: "disconnected",
        physicalDevice: nextPhysicalDevice,
        loading: false
      });
    }
  );
  const showConnectFailed = (0, import_ahooks.useMemoizedFn)((silent) => {
    var _a;
    if (silent) return;
    const connectType = (0, import_peripheralRuntime.normalizeConnectType)((_a = rowRef.current.connection.config) == null ? void 0 : _a.connection_type);
    const messageKey = connectType === "USB" ? "pisell2.saas.app-peripheral.connect-failed.usb" : connectType === "BLUETOOTH" ? "pisell2.saas.app-peripheral.connect-failed.bluetooth" : connectType === "ETHERNET" || connectType === "WIFI" ? "pisell2.saas.app-peripheral.connect-failed.network" : "pisell2.saas.app-peripheral.connect-failed";
    (0, import_materials.PisellToast)({
      content: getText(messageKey),
      duration: 2
    });
  });
  const connectPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice, peripheralUsage, options = {}) => {
      patchRuntimeState({
        status: "connecting",
        physicalDevice: "is_connect" in physicalDevice ? physicalDevice : void 0,
        loading: true
      });
      addRuntimeLog("appPeripheral-手动connect触发", {
        connectionId: targetRow.id,
        target: physicalDevice,
        peripheralUsage,
        silent: options.silent
      });
      try {
        const nextUsage = peripheralUsage ?? (isLabelPrinter(targetRow.connection) ? rowRef.current.usage : void 0);
        const result = await (0, import_peripheralConnectionService.connectPeripheralConnection)({
          app: getAppInstance(),
          plugin: getPeripheralPlugin(),
          connection: targetRow.connection,
          target: physicalDevice,
          peripheralUsage: nextUsage
        });
        markedDisconnectedRef.current.delete(targetRow.id);
        applyBinding(targetRow, result.binding);
        patchRuntimeState({
          status: "connected",
          physicalDevice: result.physicalDevice,
          loading: false
        });
        if (!options.silent) {
          (0, import_materials.PisellToast)({
            content: getText("pisell2.saas.app-peripheral.connect-success"),
            duration: 2
          });
        }
        addRuntimeLog("appPeripheral-手动connect成功", {
          connectionId: targetRow.id,
          uuid: result.physicalDevice.uuid
        });
        return result;
      } catch (e) {
        patchRuntimeState({
          status: "disconnected",
          physicalDevice: "is_connect" in physicalDevice ? physicalDevice : void 0,
          loading: false
        });
        addRuntimeLog(
          "appPeripheral-手动connect失败",
          {
            connectionId: targetRow.id,
            target: physicalDevice,
            error: e
          },
          "error"
        );
        throw e;
      }
    }
  );
  const reconnectPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, options = {}) => {
      var _a;
      patchRuntimeState({
        status: "connecting",
        physicalDevice: getKnownPhysicalDevice(targetRow),
        loading: true
      });
      addRuntimeLog("appPeripheral-reconnect触发", {
        connectionId: targetRow.id,
        uuid: ((_a = getKnownPhysicalDevice(targetRow)) == null ? void 0 : _a.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(targetRow.connection),
        silent: options.silent
      });
      try {
        const result = await (0, import_peripheralConnectionService.reconnectPeripheralConnection)({
          app: getAppInstance(),
          plugin: getPeripheralPlugin(),
          connection: targetRow.connection,
          physicalDevice: getKnownPhysicalDevice(targetRow),
          peripheralUsage: targetRow.usage
        });
        markedDisconnectedRef.current.delete(targetRow.id);
        applyBinding(targetRow, result.binding);
        if (!options.silent) {
          (0, import_materials.PisellToast)({
            content: getText("pisell2.saas.app-peripheral.connect-success"),
            duration: 2
          });
        }
        addRuntimeLog("appPeripheral-reconnect成功", {
          connectionId: targetRow.id,
          uuid: result.physicalDevice.uuid
        });
        return result;
      } catch (e) {
        patchRuntimeState({
          status: "disconnected",
          physicalDevice: getKnownPhysicalDevice(targetRow),
          loading: false
        });
        if (!options.silent) {
          showConnectFailed(false);
        }
        addRuntimeLog(
          "appPeripheral-reconnect失败",
          {
            connectionId: targetRow.id,
            error: e
          },
          "error"
        );
        throw e;
      }
    }
  );
  const connectOrMarkDisconnected = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, target, options = {}) => {
      try {
        await connectPhysicalDevice(targetRow, target, void 0, options);
      } catch (e) {
        await markDisconnectedOnce(
          targetRow,
          "is_connect" in target ? target : void 0
        );
        showConnectFailed(options.silent);
        addRuntimeLog("appPeripheral-connect失败后完成断连收敛", {
          connectionId: targetRow.id,
          target,
          silent: options.silent
        });
      }
    }
  );
  const connectSelectedPhysicalDevice = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, physicalDevice) => {
      await connectOrMarkDisconnected(targetRow, physicalDevice);
    }
  );
  const inspectPeripheralStatus = (0, import_ahooks.useMemoizedFn)(
    async (targetRow) => {
      var _a, _b;
      const knownPhysicalDevice = getKnownPhysicalDevice(targetRow);
      const effectiveUuid = (knownPhysicalDevice == null ? void 0 : knownPhysicalDevice.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(targetRow.connection);
      const ip = (knownPhysicalDevice == null ? void 0 : knownPhysicalDevice.ip) || (0, import_peripheralRuntime.getPeripheralIp)(targetRow.connection);
      addRuntimeLog("appPeripheral-初始化探测开始", {
        connectionId: targetRow.id,
        effectiveUuid,
        ip,
        connectionMethod: (_a = targetRow.connection.config) == null ? void 0 : _a.connection_method
      });
      if (!effectiveUuid && ip && ((_b = targetRow.connection.config) == null ? void 0 : _b.connection_method) === "manual") {
        addRuntimeLog("appPeripheral-初始化使用config手动IP自动连接", {
          connectionId: targetRow.id,
          ip
        });
        await connectOrMarkDisconnected(targetRow, { ip }, { silent: true });
        return;
      }
      const devices = effectiveUuid ? await findPhysicalDevices(targetRow.connection, effectiveUuid) : await findPhysicalDevices(targetRow.connection);
      const matchedDevices = effectiveUuid ? devices.filter((device) => device.uuid === effectiveUuid) : ip ? devices.filter((device) => device.ip === ip) : devices;
      const candidates = matchedDevices.length ? matchedDevices : devices;
      if (!candidates.length) {
        addRuntimeLog("appPeripheral-初始化未发现候选设备", {
          connectionId: targetRow.id,
          effectiveUuid,
          ip
        });
        if (effectiveUuid && knownPhysicalDevice && !knownPhysicalDevice.is_connect) {
          try {
            await reconnectPhysicalDevice(targetRow, { silent: true });
            return;
          } catch (e) {
            await markDisconnectedOnce(targetRow, knownPhysicalDevice);
            return;
          }
        }
        await markDisconnectedOnce(targetRow, knownPhysicalDevice);
        return;
      }
      if (candidates.length > 1) {
        addRuntimeLog("appPeripheral-初始化发现多个候选设备", {
          connectionId: targetRow.id,
          candidateCount: candidates.length,
          uuids: candidates.map((device) => device.uuid)
        });
        patchRuntimeState({
          status: "select",
          candidates,
          loading: false
        });
        return;
      }
      const physicalDevice = candidates[0];
      if (!effectiveUuid && !physicalDevice.is_connect) {
        addRuntimeLog("appPeripheral-初始化发现单个未连接设备并自动连接", {
          connectionId: targetRow.id,
          uuid: physicalDevice.uuid
        });
        await connectOrMarkDisconnected(targetRow, physicalDevice, {
          silent: true
        });
        return;
      }
      if (effectiveUuid && !physicalDevice.is_connect) {
        try {
          await reconnectPhysicalDevice(targetRow, { silent: true });
          return;
        } catch (e) {
          await markDisconnectedOnce(targetRow, physicalDevice);
          return;
        }
      }
      const result = await (0, import_peripheralConnectionService.savePeripheralConnectionStatus)({
        app: getAppInstance(),
        connection: targetRow.connection,
        physicalDevice,
        peripheralUsage: targetRow.usage
      });
      applyBinding(targetRow, result.binding);
      addRuntimeLog("appPeripheral-初始化状态探测完成", {
        connectionId: targetRow.id,
        uuid: physicalDevice.uuid,
        isConnect: physicalDevice.is_connect
      });
      patchRuntimeState({
        status: physicalDevice.is_connect ? "connected" : "disconnected",
        physicalDevice,
        loading: false
      });
    }
  );
  const handleConnectPeripheral = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, auto = false) => {
      var _a;
      if (inspectingRef.current.has(targetRow.id)) return;
      if (auto && bootstrappedRef.current.has(targetRow.id)) return;
      if (auto) {
        bootstrappedRef.current.add(targetRow.id);
      }
      inspectingRef.current.add(targetRow.id);
      addRuntimeLog("appPeripheral-连接入口触发", {
        connectionId: targetRow.id,
        auto
      });
      patchRuntimeState({
        status: "connecting",
        loading: true
      });
      try {
        if (auto) {
          await inspectPeripheralStatus(targetRow);
          return;
        }
        const knownPhysicalDevice = getKnownPhysicalDevice(targetRow);
        const effectiveUuid = (knownPhysicalDevice == null ? void 0 : knownPhysicalDevice.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(targetRow.connection);
        const ip = (knownPhysicalDevice == null ? void 0 : knownPhysicalDevice.ip) || (0, import_peripheralRuntime.getPeripheralIp)(targetRow.connection);
        const options = {
          silent: auto
        };
        if (effectiveUuid) {
          const devices2 = await findPhysicalDevices(
            targetRow.connection,
            effectiveUuid
          );
          const physicalDevice = devices2.find((device) => device.uuid === effectiveUuid) || knownPhysicalDevice;
          const target = physicalDevice || { uuid: effectiveUuid, ip };
          await connectOrMarkDisconnected(targetRow, target, options);
          return;
        }
        if (ip && ((_a = targetRow.connection.config) == null ? void 0 : _a.connection_method) === "manual") {
          await connectOrMarkDisconnected(targetRow, { ip }, options);
          return;
        }
        const devices = await findPhysicalDevices(targetRow.connection);
        const matchedDevices = ip ? devices.filter((device) => device.ip === ip) : devices;
        const candidates = matchedDevices.length ? matchedDevices : devices;
        if (!candidates.length) {
          await markDisconnectedOnce(targetRow);
          showConnectFailed(auto);
          return;
        }
        if (candidates.length === 1) {
          await connectOrMarkDisconnected(
            targetRow,
            candidates[0],
            options
          );
          return;
        }
        patchRuntimeState({
          status: "select",
          candidates,
          loading: false
        });
      } catch (e) {
        patchRuntimeState({
          status: "disconnected",
          loading: false
        });
        showConnectFailed(auto);
        addRuntimeLog(
          "appPeripheral-连接入口异常",
          {
            connectionId: targetRow.id,
            auto,
            error: e
          },
          "error"
        );
      } finally {
        inspectingRef.current.delete(targetRow.id);
      }
    }
  );
  const handleUpdatePeripheralUsage = (0, import_ahooks.useMemoizedFn)(
    async (targetRow, usage) => {
      const physicalDevice = getKnownPhysicalDevice(targetRow);
      addRuntimeLog("appPeripheral-更新打印机角色触发", {
        connectionId: targetRow.id,
        usage,
        uuid: physicalDevice == null ? void 0 : physicalDevice.uuid
      });
      patchRuntimeState({
        status: (physicalDevice == null ? void 0 : physicalDevice.is_connect) ? "connected" : "disconnected",
        physicalDevice,
        loading: true
      });
      try {
        const result = await (0, import_peripheralConnectionService.updatePeripheralUsage)({
          app: getAppInstance(),
          connection: targetRow.connection,
          physicalDevice,
          peripheralUsage: usage
        });
        applyBinding(targetRow, result.binding);
        (0, import_materials.PisellToast)({
          content: getText("pisell2.saas.app-peripheral.save-success"),
          duration: 2
        });
      } catch (e) {
        (0, import_materials.PisellToast)({
          content: getText("pisell2.saas.app-peripheral.connect-failed"),
          duration: 2
        });
        patchRuntimeState({
          status: (physicalDevice == null ? void 0 : physicalDevice.is_connect) ? "connected" : "disconnected",
          physicalDevice,
          loading: false
        });
        addRuntimeLog(
          "appPeripheral-更新打印机角色失败",
          {
            connectionId: targetRow.id,
            usage,
            error: e
          },
          "error"
        );
      }
    }
  );
  const handleRemovePeripheral = (0, import_ahooks.useMemoizedFn)(
    async (targetRow) => {
      var _a;
      addRuntimeLog("appPeripheral-忽略连接插件清理触发", {
        connectionId: targetRow.id,
        uuid: ((_a = getKnownPhysicalDevice(targetRow)) == null ? void 0 : _a.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(targetRow.connection)
      });
      await (0, import_peripheralConnectionService.removePeripheralConnection)({
        app: getAppInstance(),
        plugin: getPeripheralPlugin(),
        connection: targetRow.connection,
        physicalDevice: getKnownPhysicalDevice(targetRow)
      });
    }
  );
  (0, import_react.useEffect)(() => {
    rowRef.current = row;
  }, [row]);
  (0, import_react.useEffect)(() => {
    setRuntimeState((prev) => {
      var _a, _b, _c;
      if (!prev || prev.loading || prev.status === "select") return prev;
      if (!row.physical) return void 0;
      const nextStatus = row.physical.is_connect ? "connected" : "disconnected";
      if (prev.status === nextStatus && ((_a = prev.physicalDevice) == null ? void 0 : _a.uuid) === row.physical.uuid && ((_b = prev.physicalDevice) == null ? void 0 : _b.is_connect) === row.physical.is_connect && ((_c = prev.physicalDevice) == null ? void 0 : _c.status_code) === row.physical.status_code) {
        return prev;
      }
      return {
        status: nextStatus,
        physicalDevice: row.physical,
        loading: false
      };
    });
  }, [row.physical]);
  (0, import_react.useEffect)(() => {
    handleConnectPeripheral(row, true);
  }, [row.id, handleConnectPeripheral]);
  const isRuntimeSubmitting = Boolean(runtimeState == null ? void 0 : runtimeState.loading);
  return {
    runtimeState,
    physicalSelect,
    isRuntimeSubmitting,
    setPhysicalSelect,
    handleConnectPeripheral,
    handleRemovePeripheral,
    handleUpdatePeripheralUsage,
    connectSelectedPhysicalDevice
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  usePeripheralRuntime
});
