function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { Dropdown, Empty, Spin } from 'antd';
import { Button, Icon, PisellToast } from '@pisell/materials';
import { ArrowLeftOutlined, LinkOutlined, PlusOutlined } from '@ant-design/icons';
import { useMemoizedFn, useMount, useRequest } from 'ahooks';
import classNames from 'classnames';
import { locales } from '@pisell/utils';
import useEngineContext from "../../../hooks/useEngineContext";
import useLocale from "../../../hooks/useLocale";
import { withResponsive } from "../../../responsive";
import { request } from "../../../utils";
import { createDeviceConnection, deleteDevice, deleteDeviceConnection, getDeviceConnections, getDeviceDetail, getDeviceTypes, getWorkAreas, updateDevice } from "./serve";
import { useTranslation } from "./hooks";
import { usePeripheralLogger } from "./hooks/usePeripheralLogger";
import { savePeripheralConnectionStatus, syncLocalPeripheralBindings } from "./services/peripheralConnectionService";
import localeTexts from "./locales";
import { createDeviceRow, flattenDeviceModels } from "./utils";
import { createLocalPeripheralBinding, getPeripheralUuid, mergeConnectionRows } from "./utils/peripheralRuntime";
import ConnectExistingDeviceModal from "./components/ConnectExistingDeviceModal";
import EditDeviceModal from "./components/EditDeviceModal";
import PeripheralConnectionCardContainer from "./components/PeripheralConnectionCardContainer";
import "./index.less";
var PERIPHERAL_STATUS_CHANGE_CHANNEL = 'peripheral.statusChange';
var localBindingHydrationCache = new Map();
var getStoredIotDevice = function getStoredIotDevice(app) {
  try {
    var _app$storage;
    var iotDevice = JSON.parse((app === null || app === void 0 || (_app$storage = app.storage) === null || _app$storage === void 0 ? void 0 : _app$storage.getStorage('iotDevice')) || '{}');
    return {
      id: (iotDevice === null || iotDevice === void 0 ? void 0 : iotDevice.id) !== undefined && (iotDevice === null || iotDevice === void 0 ? void 0 : iotDevice.id) !== null ? Number(iotDevice.id) : undefined
    };
  } catch (e) {
    return {};
  }
};
var getConnectionListParams = function getConnectionListParams(sourceDeviceId) {
  return {
    source_device_id: sourceDeviceId,
    with: ['targetDevice.type', 'targetDevice.model.brand', 'targetDevice.workarea', 'profiles']
  };
};

/** 将 SQLite 本地记录按 connection_id 建索引，用于初始化 row 的 usage/physical。 */
var createLocalBindingMap = function createLocalBindingMap(bindings) {
  return bindings.reduce(function (result, binding) {
    result[Number(binding.connection_id)] = binding;
    return result;
  }, {});
};
var hydrateLocalBindingMapOnce = /*#__PURE__*/function () {
  var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(sourceDeviceId, loadBindings) {
    var cached, promise;
    return _regeneratorRuntime().wrap(function _callee$(_context) {
      while (1) switch (_context.prev = _context.next) {
        case 0:
          cached = localBindingHydrationCache.get(sourceDeviceId);
          if (!(cached !== null && cached !== void 0 && cached.hydrated)) {
            _context.next = 3;
            break;
          }
          return _context.abrupt("return", cached.bindingMap);
        case 3:
          if (!(cached !== null && cached !== void 0 && cached.promise)) {
            _context.next = 5;
            break;
          }
          return _context.abrupt("return", cached.promise);
        case 5:
          promise = loadBindings().then(function (bindingMap) {
            localBindingHydrationCache.set(sourceDeviceId, {
              hydrated: true,
              bindingMap: bindingMap
            });
            return bindingMap;
          }).catch(function (error) {
            localBindingHydrationCache.delete(sourceDeviceId);
            throw error;
          });
          localBindingHydrationCache.set(sourceDeviceId, {
            hydrated: false,
            bindingMap: (cached === null || cached === void 0 ? void 0 : cached.bindingMap) || {},
            promise: promise
          });
          return _context.abrupt("return", promise);
        case 8:
        case "end":
          return _context.stop();
      }
    }, _callee);
  }));
  return function hydrateLocalBindingMapOnce(_x, _x2) {
    return _ref.apply(this, arguments);
  };
}();
var updateLocalBindingMapCache = function updateLocalBindingMapCache(sourceDeviceId, bindingMap) {
  localBindingHydrationCache.set(sourceDeviceId, {
    hydrated: true,
    bindingMap: bindingMap
  });
};
var unsubscribePubsub = function unsubscribePubsub(pubsub, subscription, handler) {
  var _pubsub$unsubscribe;
  if (typeof subscription === 'function') {
    subscription();
    return;
  }
  if (typeof (subscription === null || subscription === void 0 ? void 0 : subscription.unsubscribe) === 'function') {
    subscription.unsubscribe();
    return;
  }
  pubsub === null || pubsub === void 0 || (_pubsub$unsubscribe = pubsub.unsubscribe) === null || _pubsub$unsubscribe === void 0 || _pubsub$unsubscribe.call(pubsub, PERIPHERAL_STATUS_CHANGE_CHANNEL, handler);
};
var findStatusChangeRow = function findStatusChangeRow(rows, payload, physicalDevice) {
  var _payload$binding, _payload$binding2, _payload$binding3;
  var connectionId = (_payload$binding = payload.binding) === null || _payload$binding === void 0 ? void 0 : _payload$binding.connection_id;
  if (connectionId) {
    return rows.find(function (row) {
      return row.id === Number(connectionId);
    });
  }
  var uuid = (physicalDevice === null || physicalDevice === void 0 ? void 0 : physicalDevice.uuid) || ((_payload$binding2 = payload.binding) === null || _payload$binding2 === void 0 ? void 0 : _payload$binding2.physical_uuid) || ((_payload$binding3 = payload.binding) === null || _payload$binding3 === void 0 || (_payload$binding3 = _payload$binding3.physical_device) === null || _payload$binding3 === void 0 ? void 0 : _payload$binding3.uuid);
  if (!uuid) return undefined;
  return rows.find(function (row) {
    var _row$physical;
    return ((_row$physical = row.physical) === null || _row$physical === void 0 ? void 0 : _row$physical.uuid) === uuid || getPeripheralUuid(row.connection) === uuid;
  });
};
var SaasAppPeripheral = function SaasAppPeripheral(_ref2) {
  var _context$appHelper;
  var className = _ref2.className,
    style = _ref2.style,
    _ref2$showBack = _ref2.showBack,
    showBack = _ref2$showBack === void 0 ? false : _ref2$showBack,
    onBack = _ref2.onBack,
    onManageProfiles = _ref2.onManageProfiles,
    onTest = _ref2.onTest,
    variant = _ref2.variant;
  var context = useEngineContext();
  var locale = useLocale();
  var currentVariant = variant || 'desktop';
  locales.init(localeTexts, locale || 'en');
  var getText = locales.getText;
  var translation = useTranslation();
  var _usePeripheralLogger = usePeripheralLogger(),
    addPageLog = _usePeripheralLogger.addLog;
  var utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
  var _useState = useState(function () {
      var _utils$getApp;
      return getStoredIotDevice(utils === null || utils === void 0 || (_utils$getApp = utils.getApp) === null || _utils$getApp === void 0 ? void 0 : _utils$getApp.call(utils));
    }),
    _useState2 = _slicedToArray(_useState, 2),
    storedIotDevice = _useState2[0],
    setStoredIotDevice = _useState2[1];
  var _useState3 = useState(),
    _useState4 = _slicedToArray(_useState3, 2),
    connectModal = _useState4[0],
    setConnectModal = _useState4[1];
  var _useState5 = useState(),
    _useState6 = _slicedToArray(_useState5, 2),
    editingDevice = _useState6[0],
    setEditingDevice = _useState6[1];
  var _useState7 = useState(false),
    _useState8 = _slicedToArray(_useState7, 2),
    initializing = _useState8[0],
    setInitializing = _useState8[1];
  var _useState9 = useState('component'),
    _useState10 = _slicedToArray(_useState9, 2),
    activeConnectionType = _useState10[0],
    setActiveConnectionType = _useState10[1];
  /** 页面唯一渲染列表：云端 connection/peripheral + 本地 physical/usage。 */
  var _useState11 = useState([]),
    _useState12 = _slicedToArray(_useState11, 2),
    rows = _useState12[0],
    setRows = _useState12[1];
  var localBindingMapRef = useRef({});
  var rowsRef = useRef([]);
  var hadTabsRef = useRef(false);
  useEffect(function () {
    if (utils !== null && utils !== void 0 && utils.request) {
      request.setRequest(utils.request);
    }
  }, [utils === null || utils === void 0 ? void 0 : utils.request]);
  useEffect(function () {
    var _utils$getApp2;
    var nextDevice = getStoredIotDevice(utils === null || utils === void 0 || (_utils$getApp2 = utils.getApp) === null || _utils$getApp2 === void 0 ? void 0 : _utils$getApp2.call(utils));
    setStoredIotDevice(function (prev) {
      return prev.id === nextDevice.id ? prev : nextDevice;
    });
  }, [utils === null || utils === void 0 ? void 0 : utils.getApp]);
  var getAppInstance = useMemoizedFn(function () {
    var _utils$getApp3;
    return utils === null || utils === void 0 || (_utils$getApp3 = utils.getApp) === null || _utils$getApp3 === void 0 ? void 0 : _utils$getApp3.call(utils);
  });
  useEffect(function () {
    rowsRef.current = rows;
  }, [rows]);
  var currentDeviceRequest = useRequest(getDeviceDetail, {
    manual: true
  });
  var connectionRequest = useRequest(getDeviceConnections, {
    manual: true
  });
  var workAreaRequest = useRequest(getWorkAreas, {
    manual: true
  });
  var typeRequest = useRequest(function () {
    return getDeviceTypes({
      kind: 'dumb',
      with: ['activeModels', 'activeModels.activeProfiles', 'activeModels.brand']
    });
  }, {
    manual: true
  });
  var createConnectionRequest = useRequest(createDeviceConnection, {
    manual: true
  });
  var updateDeviceRequest = useRequest(function (params) {
    return updateDevice(params.id, params.payload);
  }, {
    manual: true
  });
  var deleteConnectionRequest = useRequest(deleteDeviceConnection, {
    manual: true
  });
  var deleteDeviceRequest = useRequest(deleteDevice, {
    manual: true
  });
  var currentDevice = currentDeviceRequest.data || undefined;
  var isIntegratedDevice = (currentDevice === null || currentDevice === void 0 ? void 0 : currentDevice.structure) === 'composite';
  var workAreas = useMemo(function () {
    return workAreaRequest.data || [];
  }, [workAreaRequest.data]);
  var models = useMemo(function () {
    return flattenDeviceModels(typeRequest.data || []);
  }, [typeRequest.data]);
  var loading = initializing || currentDeviceRequest.loading || connectionRequest.loading || workAreaRequest.loading || typeRequest.loading;
  var componentRows = useMemo(function () {
    return rows.filter(function (row) {
      return row.connection.type === 'component';
    });
  }, [rows]);
  var peripheralRows = useMemo(function () {
    return rows.filter(function (row) {
      return row.connection.type === 'dumb';
    });
  }, [rows]);
  var hasComponentRows = componentRows.length > 0;
  var hasPeripheralRows = peripheralRows.length > 0;
  var shouldShowTabs = isIntegratedDevice || hasComponentRows && hasPeripheralRows;
  var visibleConnectionType = shouldShowTabs ? activeConnectionType : hasComponentRows ? 'component' : 'dumb';
  var visibleRows = visibleConnectionType === 'component' ? componentRows : peripheralRows;
  var connectedDeviceIds = useMemo(function () {
    return rows.filter(function (row) {
      return row.connection.type === ((connectModal === null || connectModal === void 0 ? void 0 : connectModal.connectionType) || 'dumb');
    }).map(function (row) {
      return row.peripheralId;
    });
  }, [connectModal === null || connectModal === void 0 ? void 0 : connectModal.connectionType, rows]);
  useEffect(function () {
    if (shouldShowTabs && !hadTabsRef.current) {
      setActiveConnectionType('component');
    }
    hadTabsRef.current = shouldShowTabs;
  }, [shouldShowTabs]);
  useEffect(function () {
    if (isIntegratedDevice) return;
    if (activeConnectionType === 'component' && !hasComponentRows && hasPeripheralRows) {
      setActiveConnectionType('dumb');
      return;
    }
    if (activeConnectionType === 'dumb' && hasComponentRows && !hasPeripheralRows) {
      setActiveConnectionType('component');
    }
  }, [activeConnectionType, hasComponentRows, hasPeripheralRows, isIntegratedDevice]);
  var hydrateLocalBindings = useMemoizedFn( /*#__PURE__*/function () {
    var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(nextConnections) {
      var sourceDeviceId;
      return _regeneratorRuntime().wrap(function _callee3$(_context3) {
        while (1) switch (_context3.prev = _context3.next) {
          case 0:
            sourceDeviceId = storedIotDevice.id;
            if (sourceDeviceId) {
              _context3.next = 3;
              break;
            }
            return _context3.abrupt("return", localBindingMapRef.current);
          case 3:
            _context3.next = 5;
            return hydrateLocalBindingMapOnce(sourceDeviceId, /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2() {
              var bindings;
              return _regeneratorRuntime().wrap(function _callee2$(_context2) {
                while (1) switch (_context2.prev = _context2.next) {
                  case 0:
                    _context2.next = 2;
                    return syncLocalPeripheralBindings({
                      app: getAppInstance(),
                      connections: nextConnections
                    });
                  case 2:
                    bindings = _context2.sent;
                    return _context2.abrupt("return", createLocalBindingMap(bindings));
                  case 4:
                  case "end":
                    return _context2.stop();
                }
              }, _callee2);
            })));
          case 5:
            localBindingMapRef.current = _context3.sent;
            return _context3.abrupt("return", localBindingMapRef.current);
          case 7:
          case "end":
            return _context3.stop();
        }
      }, _callee3);
    }));
    return function (_x3) {
      return _ref3.apply(this, arguments);
    };
  }());
  var patchLocalBindingMap = useMemoizedFn(function (row, physical, usage) {
    var binding = createLocalPeripheralBinding(row.connection, physical, usage);
    localBindingMapRef.current = _objectSpread(_objectSpread({}, localBindingMapRef.current), {}, _defineProperty({}, row.id, binding));
    updateLocalBindingMapCache(row.connection.source_device_id, localBindingMapRef.current);
  });
  var loadConnections = useMemoizedFn( /*#__PURE__*/_asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee4() {
    var options,
      nextConnections,
      localBindingMap,
      _args4 = arguments;
    return _regeneratorRuntime().wrap(function _callee4$(_context4) {
      while (1) switch (_context4.prev = _context4.next) {
        case 0:
          options = _args4.length > 0 && _args4[0] !== undefined ? _args4[0] : {};
          if (storedIotDevice.id) {
            _context4.next = 3;
            break;
          }
          return _context4.abrupt("return");
        case 3:
          // 接口刷新只更新 row 的云端部分，physical/usage 由 mergeConnectionRows 保留。
          addPageLog('appPeripheral-加载连接列表开始', {
            sourceDeviceId: storedIotDevice.id,
            hydrateLocal: options.hydrateLocal
          });
          _context4.next = 6;
          return connectionRequest.runAsync(getConnectionListParams(storedIotDevice.id));
        case 6:
          nextConnections = _context4.sent;
          if (!options.hydrateLocal) {
            _context4.next = 13;
            break;
          }
          _context4.next = 10;
          return hydrateLocalBindings(nextConnections || []);
        case 10:
          _context4.t0 = _context4.sent;
          _context4.next = 14;
          break;
        case 13:
          _context4.t0 = localBindingMapRef.current;
        case 14:
          localBindingMap = _context4.t0;
          setRows(function (prevRows) {
            return mergeConnectionRows(prevRows, nextConnections || [], localBindingMap);
          });
          addPageLog('appPeripheral-加载连接列表完成', {
            sourceDeviceId: storedIotDevice.id,
            connectionCount: (nextConnections || []).length,
            localBindingCount: Object.keys(localBindingMap).length
          });
          return _context4.abrupt("return", nextConnections);
        case 18:
        case "end":
          return _context4.stop();
      }
    }, _callee4);
  })));
  var reloadConnectionsImmediately = useMemoizedFn(function () {
    // 用户主动增删改后需要立即同步云端连接列表。
    loadConnections();
  });
  var patchRowPhysical = useMemoizedFn(function (rowId, physical) {
    // 插件运行时结果只回写当前 row 的 physical，不反写接口数据。
    setRows(function (prevRows) {
      return prevRows.map(function (row) {
        if (row.id !== rowId) return row;
        patchLocalBindingMap(row, physical, row.usage);
        return _objectSpread(_objectSpread({}, row), {}, {
          physical: physical
        });
      });
    });
  });
  var patchRowUsage = useMemoizedFn(function (rowId, usage) {
    // usage 是本地业务选择，独立于 connection/peripheral 接口字段。
    setRows(function (prevRows) {
      return prevRows.map(function (row) {
        if (row.id !== rowId) return row;
        patchLocalBindingMap(row, row.physical, usage);
        return _objectSpread(_objectSpread({}, row), {}, {
          usage: usage
        });
      });
    });
  });
  var applySyncedBinding = useMemoizedFn(function (row, physical, binding) {
    localBindingMapRef.current = _objectSpread(_objectSpread({}, localBindingMapRef.current), {}, _defineProperty({}, row.id, binding));
    updateLocalBindingMapCache(row.connection.source_device_id, localBindingMapRef.current);
    setRows(function (prevRows) {
      var nextRows = prevRows.map(function (prevRow) {
        return prevRow.id === row.id ? _objectSpread(_objectSpread({}, prevRow), {}, {
          physical: physical,
          usage: binding.peripheral_usage
        }) : prevRow;
      });
      rowsRef.current = nextRows;
      return nextRows;
    });
  });
  var handlePeripheralStatusChange = useMemoizedFn( /*#__PURE__*/function () {
    var _ref6 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee5(payload) {
      var _payload$event, _payload$binding4;
      var physicalDevice, row, _payload$binding$peri, _payload$binding5, result;
      return _regeneratorRuntime().wrap(function _callee5$(_context5) {
        while (1) switch (_context5.prev = _context5.next) {
          case 0:
            physicalDevice = (payload === null || payload === void 0 ? void 0 : payload.data) || (payload === null || payload === void 0 || (_payload$event = payload.event) === null || _payload$event === void 0 ? void 0 : _payload$event.data);
            if (physicalDevice !== null && physicalDevice !== void 0 && physicalDevice.uuid) {
              _context5.next = 3;
              break;
            }
            return _context5.abrupt("return");
          case 3:
            addPageLog('appPeripheral-收到外设状态变更', {
              uuid: physicalDevice.uuid,
              isConnect: physicalDevice.is_connect,
              bindingConnectionId: (_payload$binding4 = payload.binding) === null || _payload$binding4 === void 0 ? void 0 : _payload$binding4.connection_id
            });
            row = findStatusChangeRow(rowsRef.current, payload, physicalDevice);
            if (row) {
              _context5.next = 8;
              break;
            }
            addPageLog('appPeripheral-状态变更未匹配到页面row', {
              uuid: physicalDevice.uuid,
              rowCount: rowsRef.current.length
            });
            return _context5.abrupt("return");
          case 8:
            _context5.prev = 8;
            _context5.next = 11;
            return savePeripheralConnectionStatus({
              app: getAppInstance(),
              connection: row.connection,
              physicalDevice: physicalDevice,
              peripheralUsage: (_payload$binding$peri = (_payload$binding5 = payload.binding) === null || _payload$binding5 === void 0 ? void 0 : _payload$binding5.peripheral_usage) !== null && _payload$binding$peri !== void 0 ? _payload$binding$peri : row.usage
            });
          case 11:
            result = _context5.sent;
            applySyncedBinding(row, result.physicalDevice, result.binding);
            addPageLog('appPeripheral-状态变更已回写页面', {
              connectionId: row.id,
              uuid: result.physicalDevice.uuid,
              isConnect: result.physicalDevice.is_connect
            });
            _context5.next = 19;
            break;
          case 16:
            _context5.prev = 16;
            _context5.t0 = _context5["catch"](8);
            // 订阅同步失败时由 request 层处理提示，这里避免中断后续消息。
            addPageLog('appPeripheral-状态变更回写页面失败', {
              uuid: physicalDevice.uuid,
              error: _context5.t0
            }, 'error');
          case 19:
          case "end":
            return _context5.stop();
        }
      }, _callee5, null, [[8, 16]]);
    }));
    return function (_x4) {
      return _ref6.apply(this, arguments);
    };
  }());
  useEffect(function () {
    var _getAppInstance;
    var pubsub = ((_getAppInstance = getAppInstance()) === null || _getAppInstance === void 0 ? void 0 : _getAppInstance.pubsub) || (utils === null || utils === void 0 ? void 0 : utils.pubsub);
    if (!(pubsub !== null && pubsub !== void 0 && pubsub.subscribe)) return undefined;
    var handler = function handler(payload) {
      void handlePeripheralStatusChange(payload);
    };
    var subscription = pubsub.subscribe(PERIPHERAL_STATUS_CHANGE_CHANNEL, handler);
    return function () {
      unsubscribePubsub(pubsub, subscription, handler);
    };
  }, [handlePeripheralStatusChange, getAppInstance, utils === null || utils === void 0 ? void 0 : utils.getApp, utils === null || utils === void 0 ? void 0 : utils.pubsub]);
  useMount(function () {
    if (!storedIotDevice.id) return;
    if (utils !== null && utils !== void 0 && utils.request) {
      request.setRequest(utils.request);
    }
    var runInitialLoad = /*#__PURE__*/function () {
      var _ref7 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee6() {
        return _regeneratorRuntime().wrap(function _callee6$(_context6) {
          while (1) switch (_context6.prev = _context6.next) {
            case 0:
              setInitializing(true);
              addPageLog('appPeripheral-页面初始化开始', {
                sourceDeviceId: storedIotDevice.id
              });
              _context6.prev = 2;
              _context6.next = 5;
              return Promise.all([currentDeviceRequest.runAsync(storedIotDevice.id), workAreaRequest.runAsync(), typeRequest.runAsync(), loadConnections({
                hydrateLocal: true
              })]);
            case 5:
              addPageLog('appPeripheral-页面初始化完成', {
                sourceDeviceId: storedIotDevice.id
              });
            case 6:
              _context6.prev = 6;
              setInitializing(false);
              return _context6.finish(6);
            case 9:
            case "end":
              return _context6.stop();
          }
        }, _callee6, null, [[2,, 6, 9]]);
      }));
      return function runInitialLoad() {
        return _ref7.apply(this, arguments);
      };
    }();
    runInitialLoad();
  });
  var getPeripheral = function getPeripheral(connection) {
    return (connection === null || connection === void 0 ? void 0 : connection.target_device) || undefined;
  };
  var toPeripheralRow = function toPeripheralRow(device) {
    return createDeviceRow(device, translation);
  };
  var handleCreateConnection = /*#__PURE__*/function () {
    var _ref8 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee7(payload) {
      return _regeneratorRuntime().wrap(function _callee7$(_context7) {
        while (1) switch (_context7.prev = _context7.next) {
          case 0:
            addPageLog('appPeripheral-创建连接提交', {
              payload: payload
            });
            _context7.prev = 1;
            _context7.next = 4;
            return createConnectionRequest.runAsync(payload);
          case 4:
            PisellToast({
              content: getText('pisell2.saas.app-peripheral.connect-success'),
              duration: 2
            });
            setConnectModal(undefined);
            reloadConnectionsImmediately();
            addPageLog('appPeripheral-创建连接成功', {
              sourceDeviceId: payload.source_device_id,
              targetDeviceId: payload.target_device_id,
              targetDeviceAction: payload.target_device_action
            });
            _context7.next = 13;
            break;
          case 10:
            _context7.prev = 10;
            _context7.t0 = _context7["catch"](1);
            // 错误提示由 request 层统一处理。
            addPageLog('appPeripheral-创建连接失败', {
              payload: payload,
              error: _context7.t0
            }, 'error');
          case 13:
          case "end":
            return _context7.stop();
        }
      }, _callee7, null, [[1, 10]]);
    }));
    return function handleCreateConnection(_x5) {
      return _ref8.apply(this, arguments);
    };
  }();
  var handleRemoveConnection = /*#__PURE__*/function () {
    var _ref9 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee8(connection) {
      return _regeneratorRuntime().wrap(function _callee8$(_context8) {
        while (1) switch (_context8.prev = _context8.next) {
          case 0:
            addPageLog('appPeripheral-删除连接提交', {
              connectionId: connection.id,
              targetDeviceId: connection.target_device_id
            });
            _context8.prev = 1;
            _context8.next = 4;
            return deleteConnectionRequest.runAsync(connection.id);
          case 4:
            PisellToast({
              content: getText('pisell2.saas.app-peripheral.remove-success'),
              duration: 2
            });
            reloadConnectionsImmediately();
            addPageLog('appPeripheral-删除连接成功', {
              connectionId: connection.id,
              targetDeviceId: connection.target_device_id
            });
            _context8.next = 13;
            break;
          case 9:
            _context8.prev = 9;
            _context8.t0 = _context8["catch"](1);
            // 错误提示由 request 层统一处理。
            addPageLog('appPeripheral-删除连接失败', {
              connectionId: connection.id,
              error: _context8.t0
            }, 'error');
            throw _context8.t0;
          case 13:
          case "end":
            return _context8.stop();
        }
      }, _callee8, null, [[1, 9]]);
    }));
    return function handleRemoveConnection(_x6) {
      return _ref9.apply(this, arguments);
    };
  }();
  var handleDeleteComponentDevice = /*#__PURE__*/function () {
    var _ref10 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee9(connection) {
      return _regeneratorRuntime().wrap(function _callee9$(_context9) {
        while (1) switch (_context9.prev = _context9.next) {
          case 0:
            addPageLog('appPeripheral-删除组件设备提交', {
              connectionId: connection.id,
              targetDeviceId: connection.target_device_id
            });
            _context9.prev = 1;
            _context9.next = 4;
            return deleteDeviceRequest.runAsync(connection.target_device_id);
          case 4:
            PisellToast({
              content: getText('pisell2.saas.app-peripheral.delete-success'),
              duration: 2
            });
            reloadConnectionsImmediately();
            addPageLog('appPeripheral-删除组件设备成功', {
              connectionId: connection.id,
              targetDeviceId: connection.target_device_id
            });
            _context9.next = 13;
            break;
          case 9:
            _context9.prev = 9;
            _context9.t0 = _context9["catch"](1);
            // 错误提示由 request 层统一处理。
            addPageLog('appPeripheral-删除组件设备失败', {
              connectionId: connection.id,
              targetDeviceId: connection.target_device_id,
              error: _context9.t0
            }, 'error');
            throw _context9.t0;
          case 13:
          case "end":
            return _context9.stop();
        }
      }, _callee9, null, [[1, 9]]);
    }));
    return function handleDeleteComponentDevice(_x7) {
      return _ref10.apply(this, arguments);
    };
  }();
  var handleUpdateDevice = /*#__PURE__*/function () {
    var _ref11 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee10(id, payload) {
      return _regeneratorRuntime().wrap(function _callee10$(_context10) {
        while (1) switch (_context10.prev = _context10.next) {
          case 0:
            addPageLog('appPeripheral-编辑外设提交', {
              deviceId: id,
              payload: payload
            });
            _context10.prev = 1;
            _context10.next = 4;
            return updateDeviceRequest.runAsync({
              id: id,
              payload: payload
            });
          case 4:
            PisellToast({
              content: getText('pisell2.saas.app-peripheral.save-success'),
              duration: 2
            });
            setEditingDevice(undefined);
            reloadConnectionsImmediately();
            addPageLog('appPeripheral-编辑外设成功', {
              deviceId: id
            });
            _context10.next = 13;
            break;
          case 10:
            _context10.prev = 10;
            _context10.t0 = _context10["catch"](1);
            // 错误提示由 request 层统一处理。
            addPageLog('appPeripheral-编辑外设失败', {
              deviceId: id,
              error: _context10.t0
            }, 'error');
          case 13:
          case "end":
            return _context10.stop();
        }
      }, _callee10, null, [[1, 10]]);
    }));
    return function handleUpdateDevice(_x8, _x9) {
      return _ref11.apply(this, arguments);
    };
  }();
  var addMenuItems = [{
    key: 'existing',
    icon: /*#__PURE__*/React.createElement(LinkOutlined, null),
    label: getText('pisell2.saas.app-peripheral.add-existing'),
    onClick: function onClick() {
      addPageLog('appPeripheral-点击连接已有外设');
      setConnectModal({
        mode: 'existing',
        connectionType: 'dumb'
      });
    }
  }, {
    key: 'new',
    icon: /*#__PURE__*/React.createElement(PlusOutlined, null),
    label: getText('pisell2.saas.app-peripheral.add-new'),
    onClick: function onClick() {
      addPageLog('appPeripheral-点击新增外设');
      setConnectModal({
        mode: 'new',
        connectionType: 'dumb'
      });
    }
  }];
  var renderRows = function renderRows(nextRows, connectionType) {
    return /*#__PURE__*/React.createElement("div", {
      className: classNames('saas-app-peripheral__list', {
        'is-hidden': visibleConnectionType !== connectionType
      })
    }, nextRows.map(function (row) {
      return /*#__PURE__*/React.createElement(PeripheralConnectionCardContainer, {
        key: row.id,
        row: row,
        getText: getText,
        variant: currentVariant,
        translation: translation,
        getAppInstance: getAppInstance,
        onPhysicalChange: patchRowPhysical,
        onUsageChange: patchRowUsage,
        onTest: onTest,
        onEdit: function onEdit(item) {
          addPageLog('appPeripheral-点击编辑外设', {
            connectionId: item.id,
            targetDeviceId: item.target_device_id
          });
          var peripheral = getPeripheral(item);
          if (peripheral) {
            setEditingDevice(toPeripheralRow(peripheral));
          }
        },
        onRemove: handleRemoveConnection,
        onDeleteDevice: handleDeleteComponentDevice
      });
    }));
  };
  var handleAddComponent = function handleAddComponent() {
    addPageLog('appPeripheral-点击新增组件');
    setConnectModal({
      mode: 'new',
      connectionType: 'component',
      targetStructure: 'component'
    });
  };
  var renderAddButton = function renderAddButton() {
    if (visibleConnectionType === 'component') {
      return /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        icon: /*#__PURE__*/React.createElement(PlusOutlined, null),
        disabled: !currentDevice,
        onClick: handleAddComponent
      }, getText('pisell2.saas.app-peripheral.add'));
    }
    return /*#__PURE__*/React.createElement(Dropdown, {
      menu: {
        items: addMenuItems
      },
      trigger: ['click'],
      placement: "bottomRight",
      disabled: !currentDevice
    }, /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      icon: /*#__PURE__*/React.createElement(PlusOutlined, null),
      disabled: !currentDevice
    }, getText('pisell2.saas.app-peripheral.add')));
  };
  return /*#__PURE__*/React.createElement("div", {
    className: classNames('saas-app-peripheral', "saas-app-peripheral--".concat(currentVariant), className),
    style: style
  }, /*#__PURE__*/React.createElement("header", {
    className: "saas-app-peripheral__header"
  }, /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__header-main"
  }, showBack ? /*#__PURE__*/React.createElement(Button, {
    type: "text",
    icon: /*#__PURE__*/React.createElement(ArrowLeftOutlined, null),
    className: "saas-app-peripheral__back",
    onClick: onBack
  }) : null, /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__title"
  }, /*#__PURE__*/React.createElement(Icon, {
    type: "ApiOutlined"
  }), /*#__PURE__*/React.createElement("span", null, getText('pisell2.saas.app-peripheral.title'))), /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__subtitle"
  }, getText('pisell2.saas.app-peripheral.subtitle')))), !shouldShowTabs ? renderAddButton() : null), /*#__PURE__*/React.createElement(Spin, {
    spinning: loading,
    wrapperClassName: "saas-app-peripheral__spin"
  }, !storedIotDevice.id ? /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__empty"
  }, /*#__PURE__*/React.createElement(Empty, {
    image: Empty.PRESENTED_IMAGE_SIMPLE,
    description: getText('pisell2.saas.app-peripheral.no-current-device')
  })) : /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__content"
  }, /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__content-toolbar"
  }, shouldShowTabs ? /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__tabs"
  }, /*#__PURE__*/React.createElement("div", {
    className: classNames('saas-app-peripheral__tab', {
      'is-active': visibleConnectionType === 'component'
    }),
    onClick: function onClick() {
      return setActiveConnectionType('component');
    }
  }, getText('pisell2.saas.app-peripheral.tab-components')), /*#__PURE__*/React.createElement("div", {
    className: classNames('saas-app-peripheral__tab', {
      'is-active': visibleConnectionType === 'dumb'
    }),
    onClick: function onClick() {
      return setActiveConnectionType('dumb');
    }
  }, getText('pisell2.saas.app-peripheral.tab-peripherals'))) : /*#__PURE__*/React.createElement("div", null), shouldShowTabs ? /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__toolbar-actions"
  }, renderAddButton()) : null), renderRows(componentRows, 'component'), renderRows(peripheralRows, 'dumb'), !visibleRows.length ? /*#__PURE__*/React.createElement("div", {
    className: "saas-app-peripheral__empty"
  }, /*#__PURE__*/React.createElement(Empty, {
    image: Empty.PRESENTED_IMAGE_SIMPLE,
    description: getText(visibleConnectionType === 'component' ? 'pisell2.saas.app-peripheral.no-components' : 'pisell2.saas.app-peripheral.no-peripherals')
  })) : null)), connectModal && currentDevice ? /*#__PURE__*/React.createElement(ConnectExistingDeviceModal, {
    open: true,
    mode: connectModal.mode,
    connectionType: connectModal.connectionType,
    targetStructure: connectModal.targetStructure,
    currentDevice: currentDevice,
    connectedDeviceIds: connectedDeviceIds,
    currentWorkAreaId: currentDevice.workarea_id,
    variant: currentVariant,
    getText: getText,
    translation: translation,
    submitting: createConnectionRequest.loading,
    onClose: function onClose() {
      return setConnectModal(undefined);
    },
    onSubmit: handleCreateConnection
  }) : null, editingDevice ? /*#__PURE__*/React.createElement(EditDeviceModal, {
    open: true,
    record: editingDevice,
    variant: currentVariant,
    workAreas: workAreas,
    models: models,
    submitting: updateDeviceRequest.loading,
    getText: getText,
    translation: translation,
    onCancel: function onCancel() {
      return setEditingDevice(undefined);
    },
    onSubmit: handleUpdateDevice
  }) : null);
};
SaasAppPeripheral.displayName = 'SaasAppPeripheral';
export default withResponsive(SaasAppPeripheral);