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/usePeripheralSetupFlow.ts
var usePeripheralSetupFlow_exports = {};
__export(usePeripheralSetupFlow_exports, {
  usePeripheralSetupFlow: () => usePeripheralSetupFlow
});
module.exports = __toCommonJS(usePeripheralSetupFlow_exports);
var import_react = require("react");
var import_ahooks = require("ahooks");
var import_peripheralDiscoveryService = require("../services/peripheralDiscoveryService");
var import_peripheralConnectionService = require("../services/peripheralConnectionService");
var import_peripheralRuntime = require("../utils/peripheralRuntime");
var findConnectedDeviceForRow = (row, devices) => {
  var _a, _b;
  const uuid = ((_a = row.physical) == null ? void 0 : _a.uuid) || (0, import_peripheralRuntime.getPeripheralUuid)(row.connection);
  if (uuid) {
    return devices.find((device) => device.uuid === uuid);
  }
  const ip = (_b = row.physical) == null ? void 0 : _b.ip;
  return ip ? devices.find((device) => device.ip === ip) : void 0;
};
var usePeripheralSetupFlow = ({
  rows,
  getAppInstance,
  getPeripheralPlugin,
  addPageLog,
  applySyncedBinding
}) => {
  const [setupFlowMap, setSetupFlowMap] = (0, import_react.useState)({});
  const [autoOpenPhysicalSelectRowId, setAutoOpenPhysicalSelectRowId] = (0, import_react.useState)();
  const rowsRef = (0, import_react.useRef)([]);
  const setupFlowMapRef = (0, import_react.useRef)({});
  const activeSearchKeySetRef = (0, import_react.useRef)(/* @__PURE__ */ new Set());
  const connectedCalibrationStartedRef = (0, import_react.useRef)(false);
  const pendingPhysicalSelectConnectionIdRef = (0, import_react.useRef)();
  (0, import_react.useEffect)(() => {
    rowsRef.current = rows;
  }, [rows]);
  (0, import_react.useEffect)(() => {
    setupFlowMapRef.current = setupFlowMap;
  }, [setupFlowMap]);
  const patchSetupFlow = (0, import_ahooks.useMemoizedFn)(
    (rowId, nextState) => {
      setSetupFlowMap((prev) => {
        const next = {
          ...prev,
          [rowId]: nextState
        };
        setupFlowMapRef.current = next;
        return next;
      });
    }
  );
  const clearSetupFlow = (0, import_ahooks.useMemoizedFn)((rowId) => {
    setSetupFlowMap((prev) => {
      if (!prev[rowId]) return prev;
      const next = { ...prev };
      delete next[rowId];
      setupFlowMapRef.current = next;
      return next;
    });
  });
  const runConnectedCalibration = (0, import_ahooks.useMemoizedFn)(async () => {
    if (connectedCalibrationStartedRef.current) return;
    connectedCalibrationStartedRef.current = true;
    const plugin = getPeripheralPlugin();
    addPageLog("appPeripheral-CONNECTED校准开始");
    try {
      const devices = await (0, import_peripheralDiscoveryService.findConnectedPeripheralDevices)(plugin);
      let matchedCount = 0;
      let disconnectedCount = 0;
      const boundRows = rowsRef.current.filter(
        (row) => (0, import_peripheralRuntime.getConnectionFactStatus)(row) !== "empty"
      );
      await Promise.all(
        boundRows.map(async (row) => {
          const matchedDevice = findConnectedDeviceForRow(row, devices);
          const physicalDevice = matchedDevice || ((0, import_peripheralRuntime.getConnectionFactStatus)(row) === "connected" && row.physical ? {
            ...row.physical,
            is_connect: false
          } : void 0);
          if (!physicalDevice) return;
          if (matchedDevice) {
            matchedCount += 1;
          } else {
            disconnectedCount += 1;
          }
          const result = await (0, import_peripheralConnectionService.savePeripheralConnectionStatus)({
            app: getAppInstance(),
            connection: row.connection,
            physicalDevice,
            peripheralUsage: row.usage
          });
          applySyncedBinding(row, result.physicalDevice, result.binding);
        })
      );
      addPageLog("appPeripheral-CONNECTED校准完成", {
        resultCount: devices.length,
        boundRowCount: boundRows.length,
        matchedCount,
        disconnectedCount
      });
    } catch (e) {
      addPageLog("appPeripheral-CONNECTED校准失败", { error: e }, "error");
    }
  });
  const upsertSearchingFlow = (0, import_ahooks.useMemoizedFn)(
    (row, params) => {
      const searchKey = (0, import_peripheralRuntime.createFindListSearchKey)(params);
      const prevFlow = setupFlowMapRef.current[row.id];
      if ((prevFlow == null ? void 0 : prevFlow.step) !== "searching" || prevFlow.searchKey !== searchKey) {
        patchSetupFlow(row.id, {
          step: "searching",
          candidates: (prevFlow == null ? void 0 : prevFlow.candidates) || [],
          searchKey
        });
      }
      if (pendingPhysicalSelectConnectionIdRef.current === row.id) {
        setAutoOpenPhysicalSelectRowId(row.id);
      }
      if (activeSearchKeySetRef.current.has(searchKey)) return;
      activeSearchKeySetRef.current.add(searchKey);
      addPageLog("appPeripheral-NOT_CONNECT搜索启动", {
        connectionId: row.id,
        params
      });
      (0, import_peripheralDiscoveryService.startNotConnectedPeripheralDiscovery)(getPeripheralPlugin(), params).catch(
        (error) => {
          activeSearchKeySetRef.current.delete(searchKey);
          patchSetupFlow(row.id, { step: "idle", error });
          addPageLog(
            "appPeripheral-NOT_CONNECT搜索启动失败",
            { connectionId: row.id, error },
            "error"
          );
        }
      );
    }
  );
  const syncSetupFlowForRows = (0, import_ahooks.useMemoizedFn)(
    (nextRows) => {
      const rowIdSet = new Set(nextRows.map((row) => row.id));
      Object.keys(setupFlowMapRef.current).forEach((rowId) => {
        if (!rowIdSet.has(Number(rowId))) {
          clearSetupFlow(Number(rowId));
        }
      });
      nextRows.forEach((row) => {
        var _a;
        const factStatus = (0, import_peripheralRuntime.getConnectionFactStatus)(row);
        const currentFlow = setupFlowMapRef.current[row.id];
        if ((currentFlow == null ? void 0 : currentFlow.step) === "connecting") return;
        if (factStatus === "empty") {
          const manualIp = (0, import_peripheralRuntime.getManualConnectionIp)(row.connection);
          if (manualIp) {
            patchSetupFlow(row.id, {
              step: "connecting",
              target: { ip: manualIp },
              autoStart: true
            });
            return;
          }
          const params = (0, import_peripheralRuntime.buildNotConnectedFindListParams)(row.connection);
          if (params) {
            upsertSearchingFlow(row, params);
          }
          return;
        }
        if (factStatus === "connected" && ((_a = row.peripheral) == null ? void 0 : _a.type_code) === "label_printer" && !row.usage) {
          patchSetupFlow(row.id, { step: "configuring" });
          return;
        }
        if ((currentFlow == null ? void 0 : currentFlow.step) === "searching" || (currentFlow == null ? void 0 : currentFlow.step) === "configuring") {
          clearSetupFlow(row.id);
        }
      });
    }
  );
  const handleFindListListener = (0, import_ahooks.useMemoizedFn)(
    (result) => {
      const devices = (0, import_peripheralRuntime.uniquePeripheralDevices)(
        Array.isArray(result == null ? void 0 : result.data) ? result.data : []
      );
      const nextRows = rowsRef.current;
      nextRows.forEach((row) => {
        const flow = setupFlowMapRef.current[row.id];
        if ((flow == null ? void 0 : flow.step) !== "searching") return;
        const candidates = devices.filter(
          (device) => (0, import_peripheralRuntime.matchesPeripheralDiscovery)(row.connection, device)
        );
        patchSetupFlow(row.id, {
          ...flow,
          candidates
        });
      });
      addPageLog("appPeripheral-findListListener收到未连接设备", {
        resultCount: devices.length
      });
    }
  );
  const requestAutoOpenPhysicalSelect = (0, import_ahooks.useMemoizedFn)((connectionId) => {
    pendingPhysicalSelectConnectionIdRef.current = connectionId;
    if (!connectionId) return;
    const flow = setupFlowMapRef.current[connectionId];
    if ((flow == null ? void 0 : flow.step) === "searching") {
      setAutoOpenPhysicalSelectRowId(connectionId);
    }
  });
  const clearAutoOpenPhysicalSelect = (0, import_ahooks.useMemoizedFn)((connectionId) => {
    if (connectionId && pendingPhysicalSelectConnectionIdRef.current !== connectionId) {
      return;
    }
    pendingPhysicalSelectConnectionIdRef.current = void 0;
    setAutoOpenPhysicalSelectRowId(void 0);
  });
  (0, import_react.useEffect)(() => {
    const plugin = getPeripheralPlugin();
    if (!(plugin == null ? void 0 : plugin.addListener)) return void 0;
    let listenerHandle;
    let disposed = false;
    Promise.resolve(
      plugin.addListener("findListListener", handleFindListListener)
    ).then((handle) => {
      var _a;
      if (disposed) {
        void ((_a = handle == null ? void 0 : handle.remove) == null ? void 0 : _a.call(handle));
        return;
      }
      listenerHandle = handle;
    });
    return () => {
      var _a, _b;
      disposed = true;
      void ((_a = listenerHandle == null ? void 0 : listenerHandle.remove) == null ? void 0 : _a.call(listenerHandle));
      void ((_b = plugin.stopFindList) == null ? void 0 : _b.call(plugin));
    };
  }, [getPeripheralPlugin, handleFindListListener]);
  (0, import_react.useEffect)(() => {
    if (!rows.length) return;
    syncSetupFlowForRows(rows);
    void runConnectedCalibration();
  }, [rows, runConnectedCalibration, syncSetupFlowForRows]);
  (0, import_react.useEffect)(() => {
    var _a, _b;
    const hasSearching = Object.values(setupFlowMap).some(
      (flow) => flow.step === "searching"
    );
    if (hasSearching || !activeSearchKeySetRef.current.size) return;
    activeSearchKeySetRef.current.clear();
    void ((_b = (_a = getPeripheralPlugin()) == null ? void 0 : _a.stopFindList) == null ? void 0 : _b.call(_a));
  }, [getPeripheralPlugin, setupFlowMap]);
  return {
    setupFlowMap,
    patchSetupFlow,
    requestAutoOpenPhysicalSelect,
    clearAutoOpenPhysicalSelect,
    autoOpenPhysicalSelectRowId
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  usePeripheralSetupFlow
});
