require("../../../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_types = require("../../../model/types.js");
const require_constants = require("../../../model/constants.js");
const require_adapters = require("../../../model/adapters.js");
const require_utils = require("../../../shared/utils.js");
const require_workAreas = require("../../../api/workAreas.js");
const require_devices = require("../../../api/devices.js");
const require_deviceModels = require("../../../api/deviceModels.js");
const require_deviceConnections = require("../../../api/deviceConnections.js");
let react = require("react");
//#region src/plus/saasDevice/devicePlanning/modules/deviceConnections/hooks/useConnectDeviceModal.ts
const needsNetworkConfig = (connectionType) => connectionType === "ethernet" || connectionType === "wifi";
/** 管理连接弹窗的 existing/new/edit 三种模式状态和最终连接 payload 组装。 */
const useConnectDeviceModal = ({ open, mode, connectionType = "dumb", targetStructure, currentDevice, editConnection, connectedDeviceIds, currentWorkAreaId, getText, translation, onSubmit, onUpdate }) => {
	const [step, setStep] = (0, react.useState)("pick");
	const [workAreas, setWorkAreas] = (0, react.useState)([]);
	const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, react.useState)();
	const [devices, setDevices] = (0, react.useState)([]);
	const [models, setModels] = (0, react.useState)([]);
	const [brands, setBrands] = (0, react.useState)([]);
	const [selectedDevice, setSelectedDevice] = (0, react.useState)();
	const [selectedModel, setSelectedModel] = (0, react.useState)();
	const [keyword, setKeyword] = (0, react.useState)("");
	const [editFormValues, setEditFormValues] = (0, react.useState)();
	const [loading, setLoading] = (0, react.useState)(false);
	const [detailLoading, setDetailLoading] = (0, react.useState)(false);
	const [pickingDeviceId, setPickingDeviceId] = (0, 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 || peripheral === void 0 ? void 0 : peripheral.model_code) ? models.find((model) => model.code === peripheral.model_code) : void 0;
	const profileSource = mode === "new" ? selectedModel : (peripheral === null || peripheral === void 0 ? void 0 : peripheral.model) || fallbackProfileModel;
	const profileOptions = ((profileSource === null || profileSource === void 0 ? void 0 : profileSource.active_profiles) || []).map((profile) => ({
		label: translation(profile.name) || String(profile.id),
		value: profile.id
	}));
	const profileRequired = require_utils.isProfileRequired(profileSource);
	const connectionTypes = profileSource ? require_utils.getModelConnectionTypes(profileSource) : [];
	const getWorkAreaDeviceCount = (area) => targetKind === "smart" ? area.smart_devices_count || 0 : area.dumb_devices_count || 0;
	const getDeviceCountText = (count) => {
		return getText(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").replace("{N}", String(count));
	};
	(0, react.useEffect)(() => {
		if (!open) return;
		setStep(mode === "edit" ? "config" : "pick");
		setSelectedDevice(void 0);
		setSelectedModel(void 0);
		setKeyword("");
		setEditFormValues(void 0);
		setPickingDeviceId(void 0);
		setLoading(true);
		setDetailLoading(mode === "edit");
		Promise.all([
			require_workAreas.getWorkAreas(),
			mode === "new" ? require_deviceModels.getDeviceBrands() : Promise.resolve([]),
			require_deviceModels.getDeviceTypes({
				kind: "dumb",
				with: [
					"activeModels",
					"activeModels.activeProfiles",
					"activeModels.brand"
				]
			}),
			mode === "edit" && (editConnection === null || editConnection === void 0 ? void 0 : editConnection.id) ? require_deviceConnections.getDeviceConnectionDetail(editConnection.id) : Promise.resolve(null)
		]).then(([areas, brandList, types, detail]) => {
			var _areas$;
			setWorkAreas(areas);
			setBrands(brandList);
			setModels(require_adapters.flattenDeviceModels(types));
			setSelectedWorkAreaId(currentWorkAreaId || ((_areas$ = areas[0]) === null || _areas$ === void 0 ? void 0 : _areas$.id));
			if (detail) {
				var _detail$config, _detail$config2, _detail$config3;
				setSelectedDevice(currentIsSmart ? detail.target_device || void 0 : detail.source_device || void 0);
				setEditFormValues({
					connection_type: (_detail$config = detail.config) === null || _detail$config === void 0 ? void 0 : _detail$config.connection_type,
					connection_method: ((_detail$config2 = detail.config) === null || _detail$config2 === void 0 ? void 0 : _detail$config2.connection_method) === "manual" ? "manual" : "auto",
					connection_ip: String(((_detail$config3 = detail.config) === null || _detail$config3 === void 0 ? void 0 : _detail$config3.connection_ip) || ""),
					profile_ids: detail.profile_ids || (detail.profiles || []).map((profile) => profile.id)
				});
			}
		}).finally(() => {
			setLoading(false);
			setDetailLoading(false);
		});
	}, [
		currentIsSmart,
		currentWorkAreaId,
		editConnection === null || editConnection === void 0 ? void 0 : editConnection.id,
		mode,
		open
	]);
	(0, react.useEffect)(() => {
		if (!open || !selectedWorkAreaId) return;
		setLoading(true);
		if (mode === "new") {
			setLoading(false);
			return;
		}
		require_devices.getDevices({
			workarea_id: selectedWorkAreaId,
			type_kind: targetKind,
			with: [
				"type",
				"model",
				"model.activeProfiles",
				"workarea"
			]
		}).then((list) => setDevices(list)).finally(() => setLoading(false));
	}, [
		mode,
		open,
		selectedWorkAreaId,
		targetKind
	]);
	const filteredDevices = (0, react.useMemo)(() => {
		const value = require_constants.normalizeText(keyword);
		return devices.filter((device) => value ? require_constants.normalizeText(translation(device.name)).includes(value) : true);
	}, [
		devices,
		keyword,
		translation
	]);
	const resetConnectionConfig = () => {
		setEditFormValues(void 0);
	};
	/** 选择已有设备后拉取详情，确保配置页能拿到型号和 profiles。 */
	const handlePickDevice = (device) => {
		if (connectedDeviceIds.includes(device.id)) return;
		if (pickingDeviceId) return;
		resetConnectionConfig();
		setPickingDeviceId(device.id);
		require_devices.getDeviceDetail(device.id).then((detail) => setSelectedDevice(detail || device)).catch(() => setSelectedDevice(device)).finally(() => {
			setPickingDeviceId(void 0);
			setStep("config");
		});
	};
	/** 新增外设模式下选择型号，并为名称填入仅 original 的默认值。 */
	const handlePickModel = (model) => {
		resetConnectionConfig();
		setSelectedModel(model);
		setStep("config");
	};
	/** 从配置页返回选择页时清理连接配置和已选目标。 */
	const handleBackToPick = () => {
		resetConnectionConfig();
		setSelectedDevice(void 0);
		setSelectedModel(void 0);
		setStep("pick");
	};
	/** 根据当前模式组装 create/update connection payload 并交给父组件提交。 */
	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 || [];
		if (mode === "edit") {
			if (!editConnection || !onUpdate) return;
			onUpdate(editConnection.id, {
				config,
				profile_ids: profileIds
			});
			return;
		}
		const payload = mode === "new" ? {
			type: connectionType,
			source_device_id: smartDevice.id,
			target_device_action: "new",
			target_device: require_objectSpread2._objectSpread2({
				workarea_id: values.workarea_id || currentWorkAreaId || 0,
				model_code: (selectedModel === null || selectedModel === void 0 ? void 0 : selectedModel.code) || "",
				name: values.name || require_objectSpread2._objectSpread2({}, require_types.EMPTY_I18N)
			}, targetStructure ? { structure: targetStructure } : {}),
			config,
			profile_ids: profileIds
		} : {
			type: connectionType,
			source_device_id: smartDevice.id,
			target_device_id: peripheral === null || peripheral === void 0 ? void 0 : peripheral.id,
			target_device_action: "existing",
			config,
			profile_ids: profileIds
		};
		onSubmit === null || onSubmit === void 0 || onSubmit(payload);
	};
	return {
		step,
		workAreas,
		brands,
		models,
		selectedWorkAreaId,
		selectedModel,
		keyword,
		editFormValues,
		loading,
		detailLoading,
		pickingDeviceId,
		currentIsSmart,
		targetKind,
		peripheral,
		smartDevice,
		profileOptions,
		profileRequired,
		connectionTypes,
		filteredDevices,
		getWorkAreaDeviceCount,
		getDeviceCountText,
		setSelectedWorkAreaId,
		setKeyword,
		handlePickDevice,
		handlePickModel,
		handleBackToPick,
		handleSubmit
	};
};
//#endregion
exports.useConnectDeviceModal = useConnectDeviceModal;
