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 React, { memo, useState, useMemo, useCallback } from 'react';
import { Spin } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { PisellInput, PisellEmpty, PisellModal } from '@pisell/materials';
import { locales } from '@pisell/utils';
import "./index.less";

/**
 * SelectDevice 组件 Props
 */

/** 默认设备图标 */
var DeviceIcon = function DeviceIcon() {
  return /*#__PURE__*/React.createElement("svg", {
    width: "24",
    height: "24",
    viewBox: "0 0 24 24",
    fill: "none",
    xmlns: "http://www.w3.org/2000/svg"
  }, /*#__PURE__*/React.createElement("rect", {
    x: "4",
    y: "3",
    width: "16",
    height: "18",
    rx: "2",
    stroke: "currentColor",
    strokeWidth: "2"
  }), /*#__PURE__*/React.createElement("line", {
    x1: "4",
    y1: "7",
    x2: "20",
    y2: "7",
    stroke: "currentColor",
    strokeWidth: "2"
  }), /*#__PURE__*/React.createElement("line", {
    x1: "4",
    y1: "17",
    x2: "20",
    y2: "17",
    stroke: "currentColor",
    strokeWidth: "2"
  }), /*#__PURE__*/React.createElement("circle", {
    cx: "12",
    cy: "19.5",
    r: "0.5",
    fill: "currentColor"
  }));
};

/**
 * 模糊搜索匹配
 * @param device 设备数据
 * @param keyword 搜索关键词
 */
var matchDevice = function matchDevice(device, keyword) {
  if (!keyword.trim()) return true;
  var lowerKeyword = keyword.toLowerCase();

  // 搜索设备名称和描述
  var searchFields = [device === null || device === void 0 ? void 0 : device.name, device === null || device === void 0 ? void 0 : device.description, device === null || device === void 0 ? void 0 : device.number].filter(Boolean);
  return searchFields.some(function (field) {
    return field === null || field === void 0 ? void 0 : field.toLowerCase().includes(lowerKeyword);
  });
};

/**
 * 获取确认弹窗文本
 * @param device 设备数据
 */
var getConfirmText = function getConfirmText(device) {
  var _device$client;
  var deviceName = (device === null || device === void 0 ? void 0 : device.name) || '';
  var clientName = (device === null || device === void 0 || (_device$client = device.client) === null || _device$client === void 0 ? void 0 : _device$client.name) || '';
  var template = locales.getText('webpos-login-device-takeover-confirm');
  return template(deviceName, clientName);
};

/**
 * SelectDevice 设备选择组件
 * @description 展示设备列表，支持搜索过滤和选择，已被使用的设备需确认后选择
 */
var SelectDevice = /*#__PURE__*/memo(function (props) {
  var _props$deviceList = props.deviceList,
    deviceList = _props$deviceList === void 0 ? [] : _props$deviceList,
    _props$locale = props.locale,
    locale = _props$locale === void 0 ? 'en' : _props$locale,
    _props$loading = props.loading,
    loading = _props$loading === void 0 ? false : _props$loading,
    lastUsedDeviceId = props.lastUsedDeviceId,
    onSelect = props.onSelect,
    confirmOkText = props.confirmOkText,
    confirmCancelText = props.confirmCancelText;

  /** 搜索关键词 */
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    searchKeyword = _useState2[0],
    setSearchKeyword = _useState2[1];

  /** 当前选中的设备ID（用于显示点击loading） */
  var _useState3 = useState(null),
    _useState4 = _slicedToArray(_useState3, 2),
    selectingId = _useState4[0],
    setSelectingId = _useState4[1];

  /** 确认弹窗状态 */
  var _useState5 = useState(false),
    _useState6 = _slicedToArray(_useState5, 2),
    confirmVisible = _useState6[0],
    setConfirmVisible = _useState6[1];

  /** 待确认的设备 */
  var _useState7 = useState(null),
    _useState8 = _slicedToArray(_useState7, 2),
    pendingDevice = _useState8[0],
    setPendingDevice = _useState8[1];

  /**
   * 过滤后的设备列表
   */
  var filteredDeviceList = useMemo(function () {
    if (!searchKeyword.trim()) return deviceList;
    return deviceList.filter(function (device) {
      return matchDevice(device, searchKeyword);
    });
  }, [deviceList, searchKeyword]);

  /**
   * 处理搜索输入
   */
  var handleSearchChange = useCallback(function (e) {
    setSearchKeyword(e.target.value);
  }, []);

  /**
   * 处理设备选择
   */
  var handleSelectDevice = useCallback(function (device) {
    if (selectingId) return; // 正在选择中，防止重复点击

    // 如果设备已被使用（client 不为空），需要弹窗确认
    if (device.client) {
      setPendingDevice(device);
      setConfirmVisible(true);
      return;
    }

    // 直接选择
    setSelectingId(device.id);
    onSelect === null || onSelect === void 0 || onSelect(device);
  }, [selectingId, onSelect]);

  /**
   * 确认接管设备
   */
  var handleConfirmSelect = useCallback(function () {
    if (!pendingDevice) return;
    setConfirmVisible(false);
    setSelectingId(pendingDevice.id);
    onSelect === null || onSelect === void 0 || onSelect(pendingDevice);
    setPendingDevice(null);
  }, [pendingDevice, onSelect]);

  /**
   * 取消确认
   */
  var handleCancelConfirm = useCallback(function () {
    setConfirmVisible(false);
    setPendingDevice(null);
  }, []);

  /**
   * 获取按钮文本
   */
  var okText = confirmOkText || locales.getText('webpos-login-device-takeover-confirm-ok');
  var cancelText = confirmCancelText || locales.getText('webpos-login-device-takeover-confirm-cancel');

  /**
   * 渲染设备列表项
   */
  var renderDeviceItem = function renderDeviceItem(device) {
    var isLastUsed = lastUsedDeviceId === device.id;
    var isSelecting = selectingId === device.id;
    return /*#__PURE__*/React.createElement("div", {
      key: device.id,
      className: "select-device__item ".concat(isSelecting ? 'select-device__item--selecting' : ''),
      onClick: function onClick() {
        return handleSelectDevice(device);
      }
    }, /*#__PURE__*/React.createElement("div", {
      className: "select-device__item-icon"
    }, /*#__PURE__*/React.createElement(DeviceIcon, null)), /*#__PURE__*/React.createElement("div", {
      className: "select-device__item-content"
    }, /*#__PURE__*/React.createElement("span", {
      className: "select-device__item-name"
    }, device.name), device.description && /*#__PURE__*/React.createElement("span", {
      className: "select-device__item-desc"
    }, device.description)), /*#__PURE__*/React.createElement("div", {
      className: "select-device__item-extra"
    }, isSelecting ? /*#__PURE__*/React.createElement(Spin, {
      size: "small"
    }) : isLastUsed ? /*#__PURE__*/React.createElement("span", {
      className: "select-device__item-tag"
    }, locales.getText('webpos-login-last-used')) : null));
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "select-device"
  }, /*#__PURE__*/React.createElement("div", {
    className: "select-device__search"
  }, /*#__PURE__*/React.createElement(PisellInput, {
    placeholder: locales.getText('webpos-login-search'),
    prefix: /*#__PURE__*/React.createElement(SearchOutlined, {
      style: {
        color: '#999'
      }
    }),
    value: searchKeyword,
    onChange: handleSearchChange,
    allowClear: true,
    size: "large"
  })), /*#__PURE__*/React.createElement("div", {
    className: "select-device__list"
  }, loading ? /*#__PURE__*/React.createElement("div", {
    className: "select-device__loading"
  }, /*#__PURE__*/React.createElement(Spin, {
    size: "large"
  })) : filteredDeviceList.length === 0 ? /*#__PURE__*/React.createElement("div", {
    className: "select-device__empty"
  }, /*#__PURE__*/React.createElement(PisellEmpty, {
    description: locales.getText('webpos-login-select-device-empty')
  })) : filteredDeviceList.map(renderDeviceItem)), /*#__PURE__*/React.createElement(PisellModal.Information, {
    title: "",
    describe: pendingDevice ? getConfirmText(pendingDevice) : '',
    open: confirmVisible,
    okText: okText,
    cancelText: cancelText,
    okVisible: true,
    cancelVisible: true,
    closable: true,
    footerDivider: true,
    destroyOnClose: true,
    onOk: handleConfirmSelect,
    onCancel: handleCancelConfirm
  }));
});
SelectDevice.displayName = 'SelectDevice';
export default SelectDevice;