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 { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useRequest } from 'ahooks';
import { createDevice, deleteDevice, getDevices, prepareDeviceShortNumber, updateDevice } from "../api";
import { createDeviceRows, createProfileNameMap, DEFAULT_PAGE_SIZE, getStoredIotDevice } from "../model";
var EMPTY_DEVICES = [];
/** 管理当前型号下的设备列表、搜索、分页、定时刷新和初始接管提示。 */
export var useAppDeviceList = function useAppDeviceList(_ref) {
  var kind = _ref.kind,
    typeCode = _ref.typeCode,
    modelCode = _ref.modelCode,
    selectedWorkAreaId = _ref.selectedWorkAreaId,
    modelDetail = _ref.modelDetail,
    deviceTypeName = _ref.deviceTypeName,
    modelName = _ref.modelName,
    utils = _ref.utils,
    autoTakeoverLastUsed = _ref.autoTakeoverLastUsed,
    isModelSelecting = _ref.isModelSelecting,
    translation = _ref.translation,
    setInitCheckTakeoverDevice = _ref.setInitCheckTakeoverDevice;
  // 设备列表的本地展示状态：搜索关键字和客户端分页。
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    search = _useState2[0],
    setSearch = _useState2[1];
  var _useState3 = useState(1),
    _useState4 = _slicedToArray(_useState3, 2),
    page = _useState4[0],
    setPage = _useState4[1];
  var _useState5 = useState(DEFAULT_PAGE_SIZE),
    _useState6 = _slicedToArray(_useState5, 2),
    pageSize = _useState6[0],
    setPageSize = _useState6[1];

  // 当前终端和上次使用设备来自 App storage，用于标记 Current/Last Used。
  var _useState7 = 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));
    }),
    _useState8 = _slicedToArray(_useState7, 2),
    storedIotDevice = _useState8[0],
    setStoredIotDevice = _useState8[1];

  // 自动接管提示只允许弹出一次，避免列表刷新后重复打扰用户。
  var initTakeoverPromptedRef = useRef(false);

  // 设备 CRUD 请求对象由页面入口组合使用，避免主组件直接感知 API 细节。
  var deviceRequest = useRequest(getDevices, {
    manual: true
  });
  var createDeviceRequest = useRequest(createDevice, {
    manual: true
  });
  var updateDeviceRequest = useRequest(function (params) {
    return updateDevice(params.id, params.payload);
  }, {
    manual: true
  });
  var removeDeviceRequest = useRequest(deleteDevice, {
    manual: true
  });
  var prepareShortNumberRequest = useRequest(prepareDeviceShortNumber, {
    manual: true
  });
  var devices = (deviceRequest.data || EMPTY_DEVICES).filter(function (device) {
    return device.model_code === modelCode;
  });

  // 先从型号详情读取 profile 名称，再用设备返回的 profile 补齐缺失项。
  var profileNameMap = useMemo(function () {
    return createProfileNameMap(modelDetail, devices, translation);
  }, [devices, modelDetail, translation]);

  // 将接口设备模型转换成列表展示模型，并应用客户端搜索。
  var tableData = useMemo(function () {
    return createDeviceRows({
      devices: devices,
      search: search,
      storedIotDevice: storedIotDevice,
      deviceTypeName: deviceTypeName,
      modelName: modelName,
      profileNameMap: profileNameMap,
      translation: translation
    });
  }, [deviceTypeName, devices, modelName, profileNameMap, search, storedIotDevice, translation]);

  /** 统一生成设备列表请求参数，手动刷新、轮询和 CRUD 后刷新都复用它。 */
  var getDeviceListParams = useCallback(function () {
    return {
      workarea_id: selectedWorkAreaId,
      type_kind: kind,
      type_code: typeCode,
      model_code: modelCode,
      with: ['type', 'model', 'profile', 'workarea']
    };
  }, [kind, modelCode, selectedWorkAreaId, typeCode]);

  /** 重新加载当前工作区域和型号下的设备列表。 */
  var reloadDevices = useCallback(function () {
    if (!modelCode) return;
    deviceRequest.run(getDeviceListParams());
  }, [getDeviceListParams, modelCode]);

  /** 切换工作区域或型号时重置列表视图状态。 */
  var resetDeviceView = function resetDeviceView() {
    setSearch('');
    setPage(1);
  };

  // App 实例可在引擎初始化后才可用，因此在 utils 变化时同步一次设备缓存。
  useEffect(function () {
    if (utils !== null && utils !== void 0 && utils.getApp) {
      setStoredIotDevice(getStoredIotDevice(utils.getApp()));
    }
  }, [utils]);

  // 查询条件变化后立即刷新设备列表。
  useEffect(function () {
    reloadDevices();
  }, [reloadDevices]);

  // 设备在线和绑定状态会变化，进入设备列表后按固定间隔刷新。
  useEffect(function () {
    if (!modelCode) return;
    var timer = window.setInterval(function () {
      reloadDevices();
    }, 60 * 1000);
    return function () {
      window.clearInterval(timer);
    };
  }, [modelCode, reloadDevices]);

  // 初始化场景下，如果上次使用设备已被其他终端占用，则只提示一次接管确认。
  useEffect(function () {
    if (!autoTakeoverLastUsed || initTakeoverPromptedRef.current || isModelSelecting || deviceRequest.loading) {
      return;
    }
    var lastUsedLinkedDevice = tableData.find(function (item) {
      return item.isLastUsed && item.link === 'linked';
    });
    if (!lastUsedLinkedDevice) return;
    initTakeoverPromptedRef.current = true;
    setInitCheckTakeoverDevice(lastUsedLinkedDevice);
  }, [autoTakeoverLastUsed, deviceRequest.loading, isModelSelecting, setInitCheckTakeoverDevice, tableData]);
  return {
    search: search,
    page: page,
    pageSize: pageSize,
    devices: devices,
    tableData: tableData,
    deviceRequest: deviceRequest,
    createDeviceRequest: createDeviceRequest,
    updateDeviceRequest: updateDeviceRequest,
    removeDeviceRequest: removeDeviceRequest,
    prepareShortNumberRequest: prepareShortNumberRequest,
    setSearch: setSearch,
    setPage: setPage,
    setPageSize: setPageSize,
    setStoredIotDevice: setStoredIotDevice,
    resetDeviceView: resetDeviceView,
    reloadDevices: reloadDevices,
    prepareShortNumber: prepareShortNumberRequest.runAsync
  };
};