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 { getDeviceBrands, getDeviceDetail, getDevices, getDeviceTypes, getWorkAreas } from "../serve";
import { EMPTY_I18N } from "../types";
import { normalizeText } from "../constants";
import { flattenDeviceModels, getModelConnectionTypes, isProfileRequired } from "../utils";
import { usePeripheralLogger } from "./usePeripheralLogger";
var needsNetworkConfig = function needsNetworkConfig(connectionType) {
  return connectionType === 'ethernet' || connectionType === 'wifi';
};
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,
    connectedDeviceIds = _ref.connectedDeviceIds,
    currentWorkAreaId = _ref.currentWorkAreaId,
    getText = _ref.getText,
    translation = _ref.translation,
    onSubmit = _ref.onSubmit;
  var _usePeripheralLogger = usePeripheralLogger(),
    addLog = _usePeripheralLogger.addLog;
  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(false),
    _useState20 = _slicedToArray(_useState19, 2),
    loading = _useState20[0],
    setLoading = _useState20[1];
  var _useState21 = useState(),
    _useState22 = _slicedToArray(_useState21, 2),
    pickingDeviceId = _useState22[0],
    setPickingDeviceId = _useState22[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 selectedPeripheralModel = fallbackProfileModel || (peripheral === null || peripheral === void 0 ? void 0 : peripheral.model);
  var profileSource = mode === 'new' ? selectedModel : selectedPeripheralModel;
  var connectionTypeSource = mode === 'new' ? selectedModel : [fallbackProfileModel, peripheral === null || peripheral === void 0 ? void 0 : peripheral.model].find(function (model) {
    return getModelConnectionTypes(model).length;
  }) || selectedPeripheralModel;
  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 = getModelConnectionTypes(connectionTypeSource);
  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;
    addLog('appPeripheral-连接弹窗打开', {
      mode: mode,
      currentDeviceId: currentDevice.id,
      currentWorkAreaId: currentWorkAreaId
    });
    setStep('pick');
    setSelectedDevice(undefined);
    setSelectedModel(undefined);
    setKeyword('');
    setPickingDeviceId(undefined);
    setLoading(true);
    Promise.all([getWorkAreas(), mode === 'new' ? getDeviceBrands() : Promise.resolve([]), getDeviceTypes({
      kind: 'dumb',
      with: ['activeModels', 'activeModels.activeProfiles', 'activeModels.brand']
    })]).then(function (_ref2) {
      var _areas$;
      var _ref3 = _slicedToArray(_ref2, 3),
        areas = _ref3[0],
        brandList = _ref3[1],
        types = _ref3[2];
      setWorkAreas(areas);
      setBrands(brandList);
      setModels(flattenDeviceModels(types));
      var defaultWorkAreaId = currentWorkAreaId || ((_areas$ = areas[0]) === null || _areas$ === void 0 ? void 0 : _areas$.id);
      setSelectedWorkAreaId(defaultWorkAreaId);
      addLog('appPeripheral-连接弹窗基础数据加载完成', {
        mode: mode,
        workAreaCount: areas.length,
        brandCount: brandList.length,
        modelCount: flattenDeviceModels(types).length,
        defaultWorkAreaId: defaultWorkAreaId
      });
    }).catch(function (error) {
      addLog('appPeripheral-连接弹窗基础数据加载失败', {
        mode: mode,
        error: error
      }, 'error');
    }).finally(function () {
      setLoading(false);
    });
  }, [currentWorkAreaId, 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) {
      setDevices(list);
      addLog('appPeripheral-连接弹窗设备列表加载完成', {
        selectedWorkAreaId: selectedWorkAreaId,
        targetKind: targetKind,
        count: list.length
      });
    }).catch(function (error) {
      addLog('appPeripheral-连接弹窗设备列表加载失败', {
        selectedWorkAreaId: selectedWorkAreaId,
        targetKind: targetKind,
        error: error
      }, 'error');
    }).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 handlePickDevice = function 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);
    getDeviceDetail(device.id).then(function (detail) {
      setSelectedDevice(detail || device);
      addLog('appPeripheral-连接弹窗设备详情加载完成', {
        deviceId: device.id,
        hasDetail: Boolean(detail)
      });
    }).catch(function (error) {
      setSelectedDevice(device);
      addLog('appPeripheral-连接弹窗设备详情加载失败', {
        deviceId: device.id,
        error: error
      }, 'error');
    }).finally(function () {
      setPickingDeviceId(undefined);
      setStep('config');
    });
  };
  var handlePickModel = function handlePickModel(model) {
    addLog('appPeripheral-连接弹窗选择新增型号', {
      modelCode: model.code,
      typeCode: model.type_code,
      connectionTypes: getModelConnectionTypes(model)
    });
    setSelectedModel(model);
    setStep('config');
  };
  var handleBackToPick = function handleBackToPick() {
    addLog('appPeripheral-连接弹窗返回选择步骤', {
      mode: mode
    });
    setSelectedDevice(undefined);
    setSelectedModel(undefined);
    setStep('pick');
  };
  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 || [];
    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),
        description: values.description
      }, 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
    };
    addLog('appPeripheral-连接弹窗提交配置', {
      mode: mode,
      connectionType: values.connection_type,
      connectionMethod: values.connection_method,
      targetDeviceId: payload.target_device_id,
      targetDeviceAction: payload.target_device_action,
      profileIds: profileIds
    });
    onSubmit === null || onSubmit === void 0 || onSubmit(payload);
  };
  return {
    step: step,
    workAreas: workAreas,
    brands: brands,
    models: models,
    selectedWorkAreaId: selectedWorkAreaId,
    selectedModel: selectedModel,
    keyword: keyword,
    loading: loading,
    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
  };
};