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/useConnectDeviceModal.ts
var useConnectDeviceModal_exports = {};
__export(useConnectDeviceModal_exports, {
  useConnectDeviceModal: () => useConnectDeviceModal
});
module.exports = __toCommonJS(useConnectDeviceModal_exports);
var import_react = require("react");
var import_serve = require("../serve");
var import_types = require("../types");
var import_constants = require("../constants");
var import_utils = require("../utils");
var import_usePeripheralLogger = require("./usePeripheralLogger");
var needsNetworkConfig = (connectionType) => connectionType === "ethernet" || connectionType === "wifi";
var useConnectDeviceModal = ({
  open,
  mode,
  connectionType = "dumb",
  targetStructure,
  currentDevice,
  connectedDeviceIds,
  currentWorkAreaId,
  getText,
  translation,
  onSubmit
}) => {
  const { addLog } = (0, import_usePeripheralLogger.usePeripheralLogger)();
  const [step, setStep] = (0, import_react.useState)("pick");
  const [workAreas, setWorkAreas] = (0, import_react.useState)([]);
  const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, import_react.useState)();
  const [devices, setDevices] = (0, import_react.useState)([]);
  const [models, setModels] = (0, import_react.useState)([]);
  const [brands, setBrands] = (0, import_react.useState)([]);
  const [selectedDevice, setSelectedDevice] = (0, import_react.useState)();
  const [selectedModel, setSelectedModel] = (0, import_react.useState)();
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [pickingDeviceId, setPickingDeviceId] = (0, import_react.useState)();
  const currentIsSmart = currentDevice.type_kind === "smart";
  const targetKind = currentIsSmart ? "dumb" : "smart";
  const peripheral = currentIsSmart && mode === "new" ? void 0 : currentIsSmart ? selectedDevice : currentDevice;
  const smartDevice = currentIsSmart ? currentDevice : selectedDevice;
  const fallbackProfileModel = (peripheral == null ? void 0 : peripheral.model_code) ? models.find((model) => model.code === peripheral.model_code) : void 0;
  const selectedPeripheralModel = fallbackProfileModel || (peripheral == null ? void 0 : peripheral.model);
  const profileSource = mode === "new" ? selectedModel : selectedPeripheralModel;
  const connectionTypeSource = mode === "new" ? selectedModel : [fallbackProfileModel, peripheral == null ? void 0 : peripheral.model].find(
    (model) => (0, import_utils.getModelConnectionTypes)(model).length
  ) || selectedPeripheralModel;
  const profileOptions = ((profileSource == null ? void 0 : profileSource.active_profiles) || []).map((profile) => ({
    label: translation(profile.name) || String(profile.id),
    value: profile.id
  }));
  const profileRequired = (0, import_utils.isProfileRequired)(profileSource);
  const connectionTypes = (0, import_utils.getModelConnectionTypes)(connectionTypeSource);
  const getWorkAreaDeviceCount = (area) => targetKind === "smart" ? area.smart_devices_count || 0 : area.dumb_devices_count || 0;
  const getDeviceCountText = (count) => {
    const key = targetKind === "smart" ? count === 1 ? "pisell2.saas.device-planning.connect.smart-count-one" : "pisell2.saas.device-planning.connect.smart-count-many" : count === 1 ? "pisell2.saas.device-planning.connect.peripheral-count-one" : "pisell2.saas.device-planning.connect.peripheral-count-many";
    return getText(key).replace("{N}", String(count));
  };
  (0, import_react.useEffect)(() => {
    if (!open) return;
    addLog("appPeripheral-连接弹窗打开", {
      mode,
      currentDeviceId: currentDevice.id,
      currentWorkAreaId
    });
    setStep("pick");
    setSelectedDevice(void 0);
    setSelectedModel(void 0);
    setKeyword("");
    setPickingDeviceId(void 0);
    setLoading(true);
    Promise.all([
      (0, import_serve.getWorkAreas)(),
      mode === "new" ? (0, import_serve.getDeviceBrands)() : Promise.resolve([]),
      (0, import_serve.getDeviceTypes)({
        kind: "dumb",
        with: ["activeModels", "activeModels.activeProfiles", "activeModels.brand"]
      })
    ]).then(([areas, brandList, types]) => {
      var _a;
      setWorkAreas(areas);
      setBrands(brandList);
      setModels((0, import_utils.flattenDeviceModels)(types));
      const defaultWorkAreaId = currentWorkAreaId || ((_a = areas[0]) == null ? void 0 : _a.id);
      setSelectedWorkAreaId(defaultWorkAreaId);
      addLog("appPeripheral-连接弹窗基础数据加载完成", {
        mode,
        workAreaCount: areas.length,
        brandCount: brandList.length,
        modelCount: (0, import_utils.flattenDeviceModels)(types).length,
        defaultWorkAreaId
      });
    }).catch((error) => {
      addLog("appPeripheral-连接弹窗基础数据加载失败", { mode, error }, "error");
    }).finally(() => {
      setLoading(false);
    });
  }, [currentWorkAreaId, mode, open]);
  (0, import_react.useEffect)(() => {
    if (!open || !selectedWorkAreaId) return;
    setLoading(true);
    if (mode === "new") {
      setLoading(false);
      return;
    }
    (0, import_serve.getDevices)({
      workarea_id: selectedWorkAreaId,
      type_kind: targetKind,
      with: ["type", "model", "model.activeProfiles", "workarea"]
    }).then((list) => {
      setDevices(list);
      addLog("appPeripheral-连接弹窗设备列表加载完成", {
        selectedWorkAreaId,
        targetKind,
        count: list.length
      });
    }).catch((error) => {
      addLog(
        "appPeripheral-连接弹窗设备列表加载失败",
        { selectedWorkAreaId, targetKind, error },
        "error"
      );
    }).finally(() => setLoading(false));
  }, [mode, open, selectedWorkAreaId, targetKind]);
  const filteredDevices = (0, import_react.useMemo)(() => {
    const value = (0, import_constants.normalizeText)(keyword);
    return devices.filter(
      (device) => value ? (0, import_constants.normalizeText)(translation(device.name)).includes(value) : true
    );
  }, [devices, keyword, translation]);
  const handlePickDevice = (device) => {
    if (connectedDeviceIds.includes(device.id)) return;
    if (pickingDeviceId) return;
    addLog("appPeripheral-连接弹窗选择已有设备", {
      deviceId: device.id,
      modelCode: device.model_code,
      typeCode: device.type_code
    });
    setPickingDeviceId(device.id);
    (0, import_serve.getDeviceDetail)(device.id).then((detail) => {
      setSelectedDevice(detail || device);
      addLog("appPeripheral-连接弹窗设备详情加载完成", {
        deviceId: device.id,
        hasDetail: Boolean(detail)
      });
    }).catch((error) => {
      setSelectedDevice(device);
      addLog("appPeripheral-连接弹窗设备详情加载失败", { deviceId: device.id, error }, "error");
    }).finally(() => {
      setPickingDeviceId(void 0);
      setStep("config");
    });
  };
  const handlePickModel = (model) => {
    addLog("appPeripheral-连接弹窗选择新增型号", {
      modelCode: model.code,
      typeCode: model.type_code,
      connectionTypes: (0, import_utils.getModelConnectionTypes)(model)
    });
    setSelectedModel(model);
    setStep("config");
  };
  const handleBackToPick = () => {
    addLog("appPeripheral-连接弹窗返回选择步骤", { mode });
    setSelectedDevice(void 0);
    setSelectedModel(void 0);
    setStep("pick");
  };
  const handleSubmit = (values) => {
    if (!smartDevice || !values.connection_type) return;
    const config = {
      connection_type: values.connection_type
    };
    if (needsNetworkConfig(values.connection_type)) {
      config.connection_method = values.connection_method || "auto";
      if (values.connection_method === "manual") {
        config.connection_ip = String(values.connection_ip || "").trim();
      }
    }
    const profileIds = values.profile_ids || [];
    const payload = mode === "new" ? {
      type: connectionType,
      source_device_id: smartDevice.id,
      target_device_action: "new",
      target_device: {
        workarea_id: values.workarea_id || currentWorkAreaId || 0,
        model_code: (selectedModel == null ? void 0 : selectedModel.code) || "",
        name: values.name || { ...import_types.EMPTY_I18N },
        ...targetStructure ? { structure: targetStructure } : {}
      },
      config,
      profile_ids: profileIds
    } : {
      type: connectionType,
      source_device_id: smartDevice.id,
      target_device_id: peripheral == null ? void 0 : peripheral.id,
      target_device_action: "existing",
      config,
      profile_ids: profileIds
    };
    addLog("appPeripheral-连接弹窗提交配置", {
      mode,
      connectionType: values.connection_type,
      connectionMethod: values.connection_method,
      targetDeviceId: payload.target_device_id,
      targetDeviceAction: payload.target_device_action,
      profileIds
    });
    onSubmit == null ? void 0 : onSubmit(payload);
  };
  return {
    step,
    workAreas,
    brands,
    models,
    selectedWorkAreaId,
    selectedModel,
    keyword,
    loading,
    pickingDeviceId,
    currentIsSmart,
    targetKind,
    peripheral,
    smartDevice,
    profileOptions,
    profileRequired,
    connectionTypes,
    filteredDevices,
    getWorkAreaDeviceCount,
    getDeviceCountText,
    setSelectedWorkAreaId,
    setKeyword,
    handlePickDevice,
    handlePickModel,
    handleBackToPick,
    handleSubmit
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useConnectDeviceModal
});
