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 { CloseOutlined, SearchOutlined } from '@ant-design/icons';
import { Button, Input } from 'antd';
import React, { cloneElement, forwardRef, isValidElement, useImperativeHandle, useRef, useState } from 'react';
import useEngineContext from "../../../hooks/useEngineContext";
import { getText } from "../../../locales";
import Iconfont from "../../iconfont";
import PisellQRScanner from "../../pisellQRScanner";
/**
 * LookupTrigger 组件
 * 触发器层：支持多种触发器类型
 */
var LookupTriggerComponent = /*#__PURE__*/forwardRef(function (props, ref) {
  var _context$appHelper;
  var _props$type = props.type,
    type = _props$type === void 0 ? 'input' : _props$type,
    trigger = props.trigger,
    triggerText = props.triggerText,
    triggerIcon = props.triggerIcon,
    _props$buttonText = props.buttonText,
    buttonText = _props$buttonText === void 0 ? getText('pisell-lookup-button-text') : _props$buttonText,
    _props$disabled = props.disabled,
    disabled = _props$disabled === void 0 ? false : _props$disabled,
    _props$placeholder = props.placeholder,
    placeholder = _props$placeholder === void 0 ? getText('pisell-lookup-placeholder') : _props$placeholder,
    _props$size = props.size,
    size = _props$size === void 0 ? 'middle' : _props$size,
    _props$showPrefixIcon = props.showPrefixIcon,
    showPrefixIcon = _props$showPrefixIcon === void 0 ? false : _props$showPrefixIcon,
    prefixIcon = props.prefixIcon,
    addonBefore = props.addonBefore,
    _props$showClear = props.showClear,
    showClear = _props$showClear === void 0 ? true : _props$showClear,
    _props$showConfirmBut = props.showConfirmButton,
    showConfirmButton = _props$showConfirmBut === void 0 ? true : _props$showConfirmBut,
    _props$confirmButtonT = props.confirmButtonText,
    confirmButtonText = _props$confirmButtonT === void 0 ? getText('pisell-lookup-confirm-button-text') : _props$confirmButtonT,
    _props$showScan = props.showScan,
    showScan = _props$showScan === void 0 ? true : _props$showScan,
    value = props.value,
    loading = props.loading,
    inputRender = props.inputRender,
    _onChange = props.onChange,
    onClick = props.onClick,
    onFocus = props.onFocus,
    _onConfirm = props.onConfirm,
    _onScan = props.onScan,
    onClear = props.onClear,
    onBlur = props.onBlur,
    _props$autoFocus = props.autoFocus,
    autoFocus = _props$autoFocus === void 0 ? false : _props$autoFocus,
    className = props.className,
    style = props.style;
  var context = useEngineContext();
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    getApp = _ref.getApp;
  /**
   * Input 输入框的 ref
   */
  var inputRef = useRef(null);

  /**
   * 暴露给外部的方法
   */
  useImperativeHandle(ref, function () {
    return {
      focus: function focus() {
        var _inputRef$current;
        (_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 || _inputRef$current.focus();
      },
      select: function select() {
        var _inputRef$current2;
        (_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 || _inputRef$current2.select();
      }
    };
  }, []);

  /**
   * 扫码弹窗可见性状态
   */
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    scanVisible = _useState2[0],
    setScanVisible = _useState2[1];

  /**
   * 处理输入变化
   */
  var handleChange = function handleChange(e) {
    _onChange === null || _onChange === void 0 || _onChange(e.target.value);
  };

  /**
   * 处理清除
   */
  var handleClear = function handleClear() {
    _onChange === null || _onChange === void 0 || _onChange('');
    onClear === null || onClear === void 0 || onClear();
  };

  /**
   * @title: 获取扫码插件示例
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   */
  var getAppScanBarcodePlugin = function getAppScanBarcodePlugin() {
    if (getApp) {
      var app = getApp();
      var scanBarcode = app === null || app === void 0 ? void 0 : app.getPlugin('webScan');
      if (scanBarcode) {
        return scanBarcode;
      }
    }
    return null;
  };

  /**
   * @title: 在APP环境下使用插件进行扫码
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   */
  var appScan = function appScan() {
    var app = getApp();
    try {
      var scanBarcode = getAppScanBarcodePlugin();
      scanBarcode.scan({
        type: "capacitor",
        params: {
          hint: 17
        }
      }).then(function (res) {
        _onScan === null || _onScan === void 0 || _onScan(res);
      });
      // scanBarcode({ hint: 17 })
      //   .then((res: { ScanResult: string }) => onScan?.(res?.ScanResult))
      //   .catch((err: any) => {
      //     app.logger.addLog({
      //       type: 'info',
      //       title: '扫码失败',
      //       metadata: { err },
      //     });
      //   });
    } catch (err) {
      app.logger.addLog({
        type: 'error',
        title: '扫码代码执行异常',
        metadata: {
          err: err
        }
      });
    }
  };

  /**
   * 处理扫码按钮点击
   */
  var handleScanClick = function handleScanClick() {
    // 如果有扫码插件,使用插件进行扫码
    if (getAppScanBarcodePlugin()) {
      appScan();
      return;
    }
    setScanVisible(true);
  };

  /**
   * 处理扫码成功
   */
  var handleScanSuccess = function handleScanSuccess(code) {
    // 关闭扫码弹窗
    setScanVisible(false);
    // 触发扫码回调
    _onScan === null || _onScan === void 0 || _onScan(code);
  };

  /**
   * 处理扫码关闭
   */
  var handleScanClose = function handleScanClose() {
    setScanVisible(false);
  };

  /**
   * 处理确认
   */
  var handleConfirm = function handleConfirm() {
    _onConfirm === null || _onConfirm === void 0 || _onConfirm();
  };

  /**
   * 处理按 Enter 键：传入当前输入值，避免受控模式下 state 未更新导致历史未保存
   */
  var handleKeyPress = function handleKeyPress(e) {
    if (e.key === 'Enter') {
      var _ref2, _e$currentTarget$valu, _e$currentTarget;
      var currentValue = (_ref2 = (_e$currentTarget$valu = (_e$currentTarget = e.currentTarget) === null || _e$currentTarget === void 0 ? void 0 : _e$currentTarget.value) !== null && _e$currentTarget$valu !== void 0 ? _e$currentTarget$valu : value) !== null && _ref2 !== void 0 ? _ref2 : '';
      _onConfirm === null || _onConfirm === void 0 || _onConfirm(currentValue);
    }
  };

  /**
   * 渲染输入框触发器
   */
  var renderInputTrigger = function renderInputTrigger() {
    // 输入栏插槽：把内部接好的受控状态 / 回调透传给自定义输入控件，替换内置 antd Input。
    // button/icon/text 触发器不会走到这里，因此插槽只影响 input 形态。
    if (inputRender) {
      return inputRender({
        value: value !== null && value !== void 0 ? value : '',
        placeholder: placeholder,
        disabled: disabled,
        size: size,
        loading: loading,
        onChange: function onChange(v) {
          return _onChange === null || _onChange === void 0 ? void 0 : _onChange(v);
        },
        onConfirm: function onConfirm(v) {
          var _ref3;
          return _onConfirm === null || _onConfirm === void 0 ? void 0 : _onConfirm((_ref3 = v !== null && v !== void 0 ? v : value) !== null && _ref3 !== void 0 ? _ref3 : '');
        },
        onClear: handleClear,
        onScan: function onScan(code) {
          return _onScan === null || _onScan === void 0 ? void 0 : _onScan(code);
        },
        onFocus: onFocus,
        onBlur: onBlur
      });
    }

    // 构建前缀图标
    var prefix = showPrefixIcon ? prefixIcon || /*#__PURE__*/React.createElement(SearchOutlined, null) : undefined;

    // 构建后缀图标
    var suffix = /*#__PURE__*/React.createElement("div", {
      className: "pisell-lookup-input-suffix"
    }, showClear && value && /*#__PURE__*/React.createElement("span", {
      className: "pisell-lookup-input-clear",
      onClick: handleClear
    }, /*#__PURE__*/React.createElement(CloseOutlined, null), /*#__PURE__*/React.createElement("span", {
      className: "pisell-lookup-input-clear-text"
    }, getText('pisell-lookup-clear'))), showScan && /*#__PURE__*/React.createElement(Iconfont, {
      className: "pisell-lookup-input-scan",
      type: "pisell2-scan",
      onClick: handleScanClick,
      style: {
        fontSize: size === 'small' ? 18 : size === 'large' ? 26 : 24
      }
    }), showConfirmButton && /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      size: size,
      onClick: handleConfirm,
      className: "pisell-lookup-input-confirm"
    }, confirmButtonText));
    var inputEl = /*#__PURE__*/React.createElement(Input, {
      ref: inputRef,
      value: value,
      onChange: handleChange,
      onFocus: onFocus,
      onBlur: onBlur,
      onPressEnter: handleKeyPress,
      placeholder: placeholder,
      size: size,
      disabled: disabled,
      prefix: prefix,
      suffix: suffix,
      addonBefore: addonBefore,
      autoFocus: autoFocus,
      className: "pisell-lookup-trigger-input ".concat(className || '').trim(),
      style: style
    });

    // 无 Lookup 按钮时用带 class 的包裹层，确保 DOM 上一定有 pisell-lookup-trigger-input-no-confirm；同时保留 pisell-lookup-trigger-input 以便 modal 下 .pisell-lookup-search-area-with-close .pisell-lookup-trigger-input { flex: 1 } 能命中
    if (!showConfirmButton) {
      return /*#__PURE__*/React.createElement("div", {
        className: "pisell-lookup-trigger-input pisell-lookup-trigger-input-no-confirm"
      }, inputEl);
    }
    return inputEl;
  };

  /**
   * 渲染按钮触发器
   */
  var renderButtonTrigger = function renderButtonTrigger() {
    return /*#__PURE__*/React.createElement(Button, {
      type: "primary",
      icon: /*#__PURE__*/React.createElement(SearchOutlined, null),
      onClick: onClick,
      disabled: disabled,
      size: size,
      className: "pisell-lookup-trigger-button ".concat(className || ''),
      style: style
    }, buttonText);
  };

  /**
   * 渲染图标触发器
   */
  var renderIconTrigger = function renderIconTrigger() {
    var icon = triggerIcon || /*#__PURE__*/React.createElement(SearchOutlined, {
      style: {
        fontSize: 20
      }
    });
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-lookup-trigger-icon ".concat(className || ''),
      onClick: disabled ? undefined : onClick,
      style: _objectSpread({
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1
      }, style)
    }, icon);
  };

  /**
   * 渲染文本触发器
   */
  var renderTextTrigger = function renderTextTrigger() {
    var text = triggerText || '搜索';
    return /*#__PURE__*/React.createElement("span", {
      className: "pisell-lookup-trigger-text ".concat(className || ''),
      onClick: disabled ? undefined : onClick,
      style: _objectSpread({
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1
      }, style)
    }, text);
  };

  /**
   * 渲染自定义触发器
   */
  var renderCustomTrigger = function renderCustomTrigger() {
    if (!trigger) return null;

    // 如果是有效的 React 元素，注入点击事件
    if ( /*#__PURE__*/isValidElement(trigger)) {
      return /*#__PURE__*/cloneElement(trigger, {
        onClick: disabled ? undefined : onClick,
        style: _objectSpread({
          cursor: disabled ? 'not-allowed' : 'pointer',
          opacity: disabled ? 0.5 : 1
        }, trigger.props.style || {})
      });
    }

    // 否则直接包裹
    return /*#__PURE__*/React.createElement("div", {
      className: "pisell-lookup-trigger-custom ".concat(className || ''),
      onClick: disabled ? undefined : onClick,
      style: _objectSpread({
        cursor: disabled ? 'not-allowed' : 'pointer',
        opacity: disabled ? 0.5 : 1
      }, style)
    }, trigger);
  };

  /**
   * 渲染触发器
   */
  var renderTrigger = function renderTrigger() {
    // 如果有自定义触发器，优先使用
    if (trigger) {
      return renderCustomTrigger();
    }

    // 根据类型渲染不同的触发器
    switch (type) {
      case 'input':
        return renderInputTrigger();
      case 'button':
        return renderButtonTrigger();
      case 'icon':
        return renderIconTrigger();
      case 'text':
        return renderTextTrigger();
      default:
        return renderInputTrigger();
    }
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, renderTrigger(), showScan && /*#__PURE__*/React.createElement(PisellQRScanner, {
    visible: scanVisible,
    onClose: handleScanClose,
    onScan: handleScanSuccess
  }));
});
LookupTriggerComponent.displayName = 'LookupTrigger';
export var LookupTrigger = LookupTriggerComponent;