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; }
import { useEffect, useMemo, useState } from 'react';
import { getDeviceConnectionDetail, getDeviceBrands, getDeviceDetail, getDevices, getDeviceTypes, getWorkAreas } from "../../../api";
import { EMPTY_I18N } from "../../../model";
import { flattenDeviceModels, normalizeText } from "../../../model";
import { getModelConnectionTypes, isProfileRequired } from "../../../shared";
var needsNetworkConfig = function needsNetworkConfig(connectionType) {
  return connectionType === 'ethernet' || connectionType === 'wifi';
};

/** 管理连接弹窗的 existing/new/edit 三种模式状态和最终连接 payload 组装。 */
export var useConnectDeviceModal = function useConnectDeviceModal(_ref) {
  var open = _ref.open,
    mode = _ref.mode,
    _ref$connectionType = _ref.connectionType,
    connectionType = _ref$connectionType === void 0 ? 'dumb' : _ref$connectionType,
    targetStructure = _ref.targetStructure,
    currentDevice = _ref.currentDevice,
    editConnection = _ref.editConnection,
    connectedDeviceIds = _ref.connectedDeviceIds,
    currentWorkAreaId = _ref.currentWorkAreaId,
    getText = _ref.getText,
    translation = _ref.translation,
    onSubmit = _ref.onSubmit,
    onUpdate = _ref.onUpdate;
  var _useState = useState('pick'),
    _useState2 = _slicedToArray(_useState, 2),
    step = _useState2[0],
    setStep = _useState2[1];
  var _useState3 = useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    workAreas = _useState4[0],
    setWorkAreas = _useState4[1];
  var _useState5 = useState(),
    _useState6 = _slicedToArray(_useState5, 2),
    selectedWorkAreaId = _useState6[0],
    setSelectedWorkAreaId = _useState6[1];
  var _useState7 = useState([]),
    _useState8 = _slicedToArray(_useState7, 2),
    devices = _useState8[0],
    setDevices = _useState8[1];
  var _useState9 = useState([]),
    _useState10 = _slicedToArray(_useState9, 2),
    models = _useState10[0],
    setModels = _useState10[1];
  var _useState11 = useState([]),
    _useState12 = _slicedToArray(_useState11, 2),
    brands = _useState12[0],
    setBrands = _useState12[1];
  var _useState13 = useState(),
    _useState14 = _slicedToArray(_useState13, 2),
    selectedDevice = _useState14[0],
    setSelectedDevice = _useState14[1];
  var _useState15 = useState(),
    _useState16 = _slicedToArray(_useState15, 2),
    selectedModel = _useState16[0],
    setSelectedModel = _useState16[1];
  var _useState17 = useState(''),
    _useState18 = _slicedToArray(_useState17, 2),
    keyword = _useState18[0],
    setKeyword = _useState18[1];
  var _useState19 = useState(),
    _useState20 = _slicedToArray(_useState19, 2),
    editFormValues = _useState20[0],
    setEditFormValues = _useState20[1];
  var _useState21 = useState(false),
    _useState22 = _slicedToArray(_useState21, 2),
    loading = _useState22[0],
    setLoading = _useState22[1];
  var _useState23 = useState(false),
    _useState24 = _slicedToArray(_useState23, 2),
    detailLoading = _useState24[0],
    setDetailLoading = _useState24[1];
  var _useState25 = useState(),
    _useState26 = _slicedToArray(_useState25, 2),
    pickingDeviceId = _useState26[0],
    setPickingDeviceId = _useState26[1];
  var currentIsSmart = currentDevice.type_kind === 'smart';
  var targetKind = currentIsSmart ? 'dumb' : 'smart';
  var peripheral = currentIsSmart && mode === 'new' ? undefined : currentIsSmart ? selectedDevice : currentDevice;
  var smartDevice = currentIsSmart ? currentDevice : selectedDevice;
  var fallbackProfileModel = peripheral !== null && peripheral !== void 0 && peripheral.model_code ? models.find(function (model) {
    return model.code === peripheral.model_code;
  }) : undefined;
  var profileSource = mode === 'new' ? selectedModel : (peripheral === null || peripheral === void 0 ? void 0 : peripheral.model) || fallbackProfileModel;
  var profileOptions = ((profileSource === null || profileSource === void 0 ? void 0 : profileSource.active_profiles) || []).map(function (profile) {
    return {
      label: translation(profile.name) || String(profile.id),
      value: profile.id
    };
  });
  var profileRequired = isProfileRequired(profileSource);
  var connectionTypes = profileSource ? getModelConnectionTypes(profileSource) : [];
  var getWorkAreaDeviceCount = function getWorkAreaDeviceCount(area) {
    return targetKind === 'smart' ? area.smart_devices_count || 0 : area.dumb_devices_count || 0;
  };
  var getDeviceCountText = function getDeviceCountText(count) {
    var 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));
  };
  useEffect(function () {
    if (!open) return;
    setStep(mode === 'edit' ? 'config' : 'pick');
    setSelectedDevice(undefined);
    setSelectedModel(undefined);
    setKeyword('');
    setEditFormValues(undefined);
    setPickingDeviceId(undefined);
    setLoading(true);
    setDetailLoading(mode === 'edit');
    Promise.all([getWorkAreas(), mode === 'new' ? getDeviceBrands() : Promise.resolve([]), getDeviceTypes({
      kind: 'dumb',
      with: ['activeModels', 'activeModels.activeProfiles', 'activeModels.brand']
    }), mode === 'edit' && editConnection !== null && editConnection !== void 0 && editConnection.id ? getDeviceConnectionDetail(editConnection.id) : Promise.resolve(null)]).then(function (_ref2) {
      var _areas$;
      var _ref3 = _slicedToArray(_ref2, 4),
        areas = _ref3[0],
        brandList = _ref3[1],
        types = _ref3[2],
        detail = _ref3[3];
      setWorkAreas(areas);
      setBrands(brandList);
      setModels(flattenDeviceModels(types));
      var defaultWorkAreaId = currentWorkAreaId || ((_areas$ = areas[0]) === null || _areas$ === void 0 ? void 0 : _areas$.id);
      setSelectedWorkAreaId(defaultWorkAreaId);
      if (detail) {
        var _detail$config, _detail$config2, _detail$config3;
        setSelectedDevice(currentIsSmart ? detail.target_device || undefined : detail.source_device || undefined);
        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(function (profile) {
            return profile.id;
          })
        });
      }
    }).finally(function () {
      setLoading(false);
      setDetailLoading(false);
    });
  }, [currentIsSmart, currentWorkAreaId, editConnection === null || editConnection === void 0 ? void 0 : editConnection.id, mode, open]);
  useEffect(function () {
    if (!open || !selectedWorkAreaId) return;
    setLoading(true);
    if (mode === 'new') {
      setLoading(false);
      return;
    }
    getDevices({
      workarea_id: selectedWorkAreaId,
      type_kind: targetKind,
      with: ['type', 'model', 'model.activeProfiles', 'workarea']
    }).then(function (list) {
      return setDevices(list);
    }).finally(function () {
      return setLoading(false);
    });
  }, [mode, open, selectedWorkAreaId, targetKind]);
  var filteredDevices = useMemo(function () {
    var value = normalizeText(keyword);
    return devices.filter(function (device) {
      return value ? normalizeText(translation(device.name)).includes(value) : true;
    });
  }, [devices, keyword, translation]);
  var resetConnectionConfig = function resetConnectionConfig() {
    setEditFormValues(undefined);
  };

  /** 选择已有设备后拉取详情，确保配置页能拿到型号和 profiles。 */
  var handlePickDevice = function handlePickDevice(device) {
    if (connectedDeviceIds.includes(device.id)) return;
    if (pickingDeviceId) return;
    resetConnectionConfig();
    setPickingDeviceId(device.id);
    getDeviceDetail(device.id).then(function (detail) {
      return setSelectedDevice(detail || device);
    }).catch(function () {
      return setSelectedDevice(device);
    }).finally(function () {
      setPickingDeviceId(undefined);
      setStep('config');
    });
  };

  /** 新增外设模式下选择型号，并为名称填入仅 original 的默认值。 */
  var handlePickModel = function handlePickModel(model) {
    resetConnectionConfig();
    setSelectedModel(model);
    setStep('config');
  };

  /** 从配置页返回选择页时清理连接配置和已选目标。 */
  var handleBackToPick = function handleBackToPick() {
    resetConnectionConfig();
    setSelectedDevice(undefined);
    setSelectedModel(undefined);
    setStep('pick');
  };

  /** 根据当前模式组装 create/update connection payload 并交给父组件提交。 */
  var handleSubmit = function handleSubmit(values) {
    if (!smartDevice || !values.connection_type) return;
    var 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();
      }
    }
    var profileIds = values.profile_ids || [];
    if (mode === 'edit') {
      if (!editConnection || !onUpdate) return;
      onUpdate(editConnection.id, {
        config: config,
        profile_ids: profileIds
      });
      return;
    }
    var payload = mode === 'new' ? {
      type: connectionType,
      source_device_id: smartDevice.id,
      target_device_action: 'new',
      target_device: _objectSpread({
        workarea_id: values.workarea_id || currentWorkAreaId || 0,
        model_code: (selectedModel === null || selectedModel === void 0 ? void 0 : selectedModel.code) || '',
        name: values.name || _objectSpread({}, EMPTY_I18N)
      }, targetStructure ? {
        structure: targetStructure
      } : {}),
      config: 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: config,
      profile_ids: profileIds
    };
    onSubmit === null || onSubmit === void 0 || onSubmit(payload);
  };
  return {
    step: step,
    workAreas: workAreas,
    brands: brands,
    models: models,
    selectedWorkAreaId: selectedWorkAreaId,
    selectedModel: selectedModel,
    keyword: keyword,
    editFormValues: editFormValues,
    loading: loading,
    detailLoading: detailLoading,
    pickingDeviceId: pickingDeviceId,
    currentIsSmart: currentIsSmart,
    targetKind: targetKind,
    peripheral: peripheral,
    smartDevice: smartDevice,
    profileOptions: profileOptions,
    profileRequired: profileRequired,
    connectionTypes: connectionTypes,
    filteredDevices: filteredDevices,
    getWorkAreaDeviceCount: getWorkAreaDeviceCount,
    getDeviceCountText: getDeviceCountText,
    setSelectedWorkAreaId: setSelectedWorkAreaId,
    setKeyword: setKeyword,
    handlePickDevice: handlePickDevice,
    handlePickModel: handlePickModel,
    handleBackToPick: handleBackToPick,
    handleSubmit: handleSubmit
  };
};