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, useState, useCallback } from 'react';
import useEngineContext from "../../../hooks/useEngineContext";
export var useTerminal = function useTerminal() {
  var _context$appHelper, _interaction$utils, _interaction$utils$is;
  var context = useEngineContext();
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    interaction = _ref.interaction,
    isTerminal = _ref.isTerminal;
  return {
    isTerminal: isTerminal && isTerminal() || (interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$is = _interaction$utils.isAppEnv) === null || _interaction$utils$is === void 0 ? void 0 : _interaction$utils$is.call(_interaction$utils))
  };
};

/**
 * 获取扫码设备连接状态
 */
export var useScannerDevice = function useScannerDevice() {
  var _context$appHelper2;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    scannerStatus = _useState2[0],
    setScannerStatus = _useState2[1];
  var context = useEngineContext();
  var _ref2 = ((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.utils) || {},
    interaction = _ref2.interaction;
  useEffect(function () {
    var _interaction$utils2, _interaction$utils2$p, _interaction$utils3, _interaction$utils3$m;
    // 主动获取设备连接状态
    interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 || _interaction$utils2$p.call(_interaction$utils2, {
      module: 'global',
      key: 'get_peripherals_status',
      data: {}
    });

    // 设备当前连接状态返回
    interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$m = _interaction$utils3.mountFunction) === null || _interaction$utils3$m === void 0 || _interaction$utils3$m.call(_interaction$utils3, 'global', 'peripheralsStatus', function (strPeripherals) {
      try {
        var peripherals = JSON.parse(strPeripherals);
        setScannerStatus((peripherals === null || peripherals === void 0 ? void 0 : peripherals.scanner) == 'connected');
      } catch (err) {
        console.error(err);
      }
    });
  }, []);
  return {
    scannerStatus: scannerStatus
  };
};

/**
 * 摄像头激活和状态获取
 */
export var useCameraDevice = function useCameraDevice() {
  var _context$appHelper3, _interaction$utils5, _interaction$utils5$i;
  var context = useEngineContext();
  var _ref3 = ((_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.utils) || {},
    interaction = _ref3.interaction,
    isTerminal = _ref3.isTerminal;
  var activeCamera = useCallback(function () {
    var _interaction$utils4, _interaction$utils4$p;
    interaction === null || interaction === void 0 || (_interaction$utils4 = interaction.utils) === null || _interaction$utils4 === void 0 || (_interaction$utils4$p = _interaction$utils4.postMessageToApp) === null || _interaction$utils4$p === void 0 || _interaction$utils4$p.call(_interaction$utils4, {
      module: 'global',
      key: 'active_native_scanner',
      data: {
        source: 'eftposPay_huifu'
      }
    });
  }, []);
  return {
    activeCamera: activeCamera,
    cameraStatus: isTerminal && isTerminal() || (interaction === null || interaction === void 0 || (_interaction$utils5 = interaction.utils) === null || _interaction$utils5 === void 0 || (_interaction$utils5$i = _interaction$utils5.isAppEnv) === null || _interaction$utils5$i === void 0 ? void 0 : _interaction$utils5$i.call(_interaction$utils5))
  };
};

/**
 * 获取外部设备扫描结果
 */
export var useScanListener = function useScanListener() {
  var _context$appHelper4, _interaction$utils6, _interaction$utils6$i;
  var context = useEngineContext();
  var _ref4 = ((_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 ? void 0 : _context$appHelper4.utils) || {},
    interaction = _ref4.interaction,
    isTerminal = _ref4.isTerminal;
  var _useState3 = useState({
      type: 'scanner',
      value: ''
    }),
    _useState4 = _slicedToArray(_useState3, 2),
    scanResult = _useState4[0],
    setScanResult = _useState4[1];
  var isNativeEnv = isTerminal && isTerminal() || (interaction === null || interaction === void 0 || (_interaction$utils6 = interaction.utils) === null || _interaction$utils6 === void 0 || (_interaction$utils6$i = _interaction$utils6.isAppEnv) === null || _interaction$utils6$i === void 0 ? void 0 : _interaction$utils6$i.call(_interaction$utils6));
  useEffect(function () {
    var _interaction$utils7, _interaction$utils7$m;
    // 获取外部设备扫描结果
    interaction === null || interaction === void 0 || (_interaction$utils7 = interaction.utils) === null || _interaction$utils7 === void 0 || (_interaction$utils7$m = _interaction$utils7.mountFunction) === null || _interaction$utils7$m === void 0 || _interaction$utils7$m.call(_interaction$utils7, 'global', 'peripheralsResult', function (strVal) {
      try {
        var val = JSON.parse(strVal);
        setScanResult(val);
      } catch (err) {
        console.error(err);
        setScanResult({
          type: 'scanner',
          value: ''
        });
      }
    });

    // 支持在web环境下监听外部设备扫描结果，使用监听键盘事件
    var inputBuffer = '';
    var lastInputTime = 0;
    var inputTimer = null;
    var handleKeyDown = function handleKeyDown(e) {
      // 过滤特殊键
      if (e.key === 'Shift' || e.key === 'Control' || e.key === 'Alt' || e.key === 'Meta' || e.key === 'Tab' || e.key === 'CapsLock' || e.key === 'Escape' || e.key.startsWith('Arrow') || e.ctrlKey || e.metaKey) {
        return;
      }
      var currentTime = Date.now();
      var timeDiff = currentTime - lastInputTime;

      // Enter键表示扫码结束
      if (e.key === 'Enter') {
        var trimmedCode = inputBuffer.trim();
        if (trimmedCode.length >= 10) {
          setScanResult({
            type: 'scanner',
            value: trimmedCode
          });
        }
        inputBuffer = '';
        lastInputTime = 0;
        if (inputTimer) {
          clearTimeout(inputTimer);
          inputTimer = null;
        }
        return;
      }

      // 输入间隔 < 30ms 认为是扫码枪
      if (timeDiff < 30 && inputBuffer.length > 0) {
        inputBuffer += e.key;
      } else {
        inputBuffer = e.key;
      }
      lastInputTime = currentTime;

      // 清除之前的定时器
      if (inputTimer) {
        clearTimeout(inputTimer);
      }

      // 100ms 内没有新输入，认为扫码完成
      inputTimer = setTimeout(function () {
        var trimmedCode = inputBuffer.trim();
        if (trimmedCode.length >= 10) {
          setScanResult({
            type: 'scanner',
            value: trimmedCode
          });
        }
        inputBuffer = '';
      }, 100);
    };
    if (!isNativeEnv) {
      document.addEventListener('keydown', handleKeyDown);
    }
    return function () {
      if (!isNativeEnv) {
        document.removeEventListener('keydown', handleKeyDown);
      }
      if (inputTimer) {
        clearTimeout(inputTimer);
      }
    };
  }, []);
  return {
    scanResult: scanResult
  };
};