import { useRef } from 'react';
import { useBookingTicket } from "./bookingTicket";
import { formatScanGlobal } from "../../utils";
import { useToast } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { useActiveExecute } from "./useActiveExecute";
import useEngineContext from "../../../../hooks/useEngineContext";
var useScanGlobal = function useScanGlobal() {
  var _context$appHelper;
  var bookingTicket = useBookingTicket();
  var scanRef = useRef(null);
  var Toast = useToast();
  var _useActiveExecute = useActiveExecute(),
    executeIfActive = _useActiveExecute.executeIfActive;
  var context = useEngineContext();
  var _ref = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    action = _ref.action;
  var handleScanGlobal = function handleScanGlobal(callback) {
    var _bookingTicket$initPe;
    bookingTicket === null || bookingTicket === void 0 || (_bookingTicket$initPe = bookingTicket.initPeripheralsListener) === null || _bookingTicket$initPe === void 0 || _bookingTicket$initPe.call(bookingTicket);
    scanRef.current = bookingTicket === null || bookingTicket === void 0 ? void 0 : bookingTicket.scanGlobalListener(executeIfActive(function (data) {
      console.log('scanGlobalListener>>>>>>>', data);
      if (data.status === 'failed') {
        Toast.fail(locales.getText('pisell2.text.scan-global-failed'));
        return;
      }
      var result = formatScanGlobal(data);
      if ((result === null || result === void 0 ? void 0 : result.searchType) === 'order') {
        // 这里应该可以统一化给他打开，不需要外部再处理了
        action({
          type: 'pisell1.handleOpenCachedBigSale',
          data: {
            order_id: result.data.order_id,
            business_code: 'ticket'
          }
        });
      }
      callback(result);
    }));
  };
  return {
    openScan: handleScanGlobal,
    closeScan: function closeScan() {
      var _scanRef$current, _scanRef$current$remo;
      (_scanRef$current = scanRef.current) === null || _scanRef$current === void 0 || (_scanRef$current$remo = _scanRef$current.remove) === null || _scanRef$current$remo === void 0 || _scanRef$current$remo.call(_scanRef$current);
    }
  };
};
export default useScanGlobal;