function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

// @ts-nocheck
import React, { Component } from "react";
import AutoComplete from "antd/es/auto-complete";
import Input from "antd/es/input";
import Alert from "antd/es/alert";
import Button from "antd/es/button";
import { CloseCircleOutlined, ExclamationCircleOutlined, LoadingOutlined } from '@fishx/icons';
import PagePoint from '../page-point';
var Option = AutoComplete.Option;
var Group = Input.Group;
var regKey = PagePoint.pagePointConfig.regKey;
/**
 * 搜索框。根据用户在input中输入的内容，调用外部的接口获取AutoComplete数据。
 * 并且把用户最终的选择通过callback传递到外部组件中。
 */

var SearchInput = /*#__PURE__*/function (_Component) {
  _inherits(SearchInput, _Component);

  var _super = _createSuper(SearchInput);

  function SearchInput(props) {
    var _this;

    _classCallCheck(this, SearchInput);

    _this = _super.call(this, props);
    _this.searchLabel = void 0;
    _this.dataProvider = void 0;
    _this.input = void 0;
    _this.timer = void 0;

    _this.getInputText = function () {
      var label = _this.state.label;
      return label;
    };

    _this.handleInputBlur = function () {
      var onBlur = _this.props.onBlur;

      if (typeof onBlur === "function") {
        onBlur();
      }
    };

    _this.handleInputFocus = function () {
      var label = _this.state.label;
      var onFocus = _this.props.onFocus;

      if (typeof onFocus === "function") {
        onFocus();
      }

      _this.handleLabelChange(label);
    };

    _this.handleClickClearIcon = function () {
      _this.handleLabelChange("");

      _this.doRemoveImage();

      _this.input.focus();
    };

    _this.toggleTipText = function () {
      var tipText = _this.props.tipText;

      if (tipText && tipText.length > 0) {
        _this.setState(function (state) {
          return {
            showTips: !state.showTips
          };
        });
      } // if (typeof e !== "undefined") {
      //   e.stopPropagation();
      // }

    };

    _this.handleLabelChange = function (v) {
      var value = v;

      if (typeof value === "undefined") {
        value = _this.searchLabel;
      }

      var searchPromise = _this.props.searchPromise;
      var showTips = _this.state.showTips;
      _this.searchLabel = value;

      if (typeof searchPromise === "function") {
        var fetchQuery = function fetchQuery() {
          var _assertThisInitialize = _assertThisInitialized(_this),
              searchLabel = _assertThisInitialize.searchLabel;

          if (value === searchLabel) {
            searchPromise(value).then(function (res) {
              var label = _this.searchLabel;

              if (res.search === label) {
                var dataSource = res.dataSource;

                _this.setState({
                  dataSource: dataSource,
                  loading: false
                });

                if (showTips === true) {
                  _this.toggleTipText();
                }
              }
            });
          }
        };

        if (typeof _this.timer !== "undefined") {
          try {
            clearTimeout(_this.timer);
          } catch (e) {// Something wrong here.
          }
        }

        if (value && value.length > 0) {
          _this.timer = setTimeout(fetchQuery, 500);
        } else {
          fetchQuery();
        }

        _this.setState({
          label: value,
          loading: true
        });
      }
    };

    _this.doRemoveImage = function () {
      var onRemoveImage = _this.props.onRemoveImage;

      if (typeof onRemoveImage === "function") {
        onRemoveImage();
      }
    };

    _this.handleSelect = function (value) {
      var onSelect = _this.props.onSelect;

      if (typeof onSelect === "function") {
        var getKey = String(_this.state.dataSource.map(function (item) {
          return item.label;
        }).indexOf(value));

        var object = _this.dataProvider.get(getKey);

        onSelect(object);
      }

      _this.setState({
        label: value
      });
    };

    _this.handleConfirm = function () {
      var onSelect = _this.props.onSelect;

      if (typeof onSelect === "function") {
        var label = _this.state.label;
        onSelect(label);
      }
    };

    _this.defaultOptionRenderer = function (renderer) {
      return function (item) {
        var component;

        if (renderer) {
          component = renderer(item);
        } else {
          component = /*#__PURE__*/React.createElement(Option, {
            key: item.id,
            value: item.label
          }, item.label);
        }

        _this.dataProvider.set(component.key, item);

        return component;
      };
    };

    _this.renderTipContent = function () {
      var showTips = _this.state.showTips;
      var tipText = _this.props.tipText;

      if (showTips && tipText && tipText.length > 0) {
        return /*#__PURE__*/React.createElement(Alert, {
          "data-spm": "Clstips",
          style: {
            textAlign: "left",
            position: "absolute",
            zIndex: 2,
            backgroundColor: "#fff"
          },
          className: "extra-msg",
          afterClose: _this.toggleTipText,
          message: tipText,
          closable: true,
          type: "info",
          showIcon: true
        });
      }
    };

    _this.dataProvider = new Map();
    _this.searchLabel = props.defaultValue;
    _this.state = {
      image: null,
      dataSource: [],
      label: props.defaultValue || "",
      loading: false,
      showTips: false
    };
    return _this;
  }

  _createClass(SearchInput, [{
    key: "render",
    value: function render() {
      var _this2 = this,
          _inputProps;

      var _this$props = this.props,
          _this$props$prefix = _this$props.prefix,
          prefix = _this$props$prefix === void 0 ? [] : _this$props$prefix,
          placeholder = _this$props.placeholder,
          optionRenderer = _this$props.optionRenderer,
          tipText = _this$props.tipText,
          enterButton = _this$props.enterButton,
          _this$props$disabled = _this$props.disabled,
          disabled = _this$props$disabled === void 0 ? false : _this$props$disabled,
          size = _this$props.size,
          _this$props$suffix = _this$props.suffix,
          suffix = _this$props$suffix === void 0 ? [] : _this$props$suffix,
          buttonClassName = _this$props.buttonClassName,
          autocompleteClassName = _this$props.autocompleteClassName,
          dataRegId = _this$props[regKey];
      var _this$state = this.state,
          dataSource = _this$state.dataSource,
          label = _this$state.label,
          loading = _this$state.loading;

      var regKeyProp = _defineProperty({}, regKey, dataRegId);

      var image = this.state.image;

      if (image) {
        prefix.push(image);
      }

      var props = {
        value: label,
        onSelect: this.handleSelect,
        onSearch: this.handleLabelChange,
        onFocus: this.handleInputFocus,
        onBlur: this.handleInputBlur,
        className: autocompleteClassName,
        style: {
          flex: 1
        },
        size: size,
        ref: function ref(input) {
          _this2.input = input;
        },
        dataSource: []
      };
      this.dataProvider.clear();

      if (typeof optionRenderer === "function") {
        props.dataSource = dataSource.map(this.defaultOptionRenderer(optionRenderer));
      } else {
        props.dataSource = dataSource.map(this.defaultOptionRenderer(null));
      }

      var inputProps = (_inputProps = {
        placeholder: image ? "" : placeholder,
        value: disabled ? "" : label
      }, _defineProperty(_inputProps, regKey, dataRegId), _defineProperty(_inputProps, "size", size), _defineProperty(_inputProps, "suffix", suffix), _defineProperty(_inputProps, "disabled", disabled), _defineProperty(_inputProps, "onKeyDown", function onKeyDown(e) {
        var st = _this2.state;
        var lb = st.label;
        var img = st.image;

        if (img && lb.length < 1 && e.key === "Backspace") {
          _this2.doRemoveImage();
        }
      }), _inputProps);

      if (label && label.length > 0 || image) {
        SearchInput.addSuffix(inputProps.suffix, /*#__PURE__*/React.createElement(CloseCircleOutlined, {
          "data-spm": "Clear",
          key: "extra-close",
          className: "extra-icon show",
          onClick: this.handleClickClearIcon
        }));
      }

      if (loading || tipText) {
        SearchInput.addSuffix(inputProps.suffix, loading ? /*#__PURE__*/React.createElement(LoadingOutlined, {
          key: "extra-info",
          className: "extra-icon",
          onClick: this.toggleTipText
        }) : /*#__PURE__*/React.createElement(ExclamationCircleOutlined, {
          key: "extra-info",
          className: "extra-icon",
          onClick: this.toggleTipText
        }));
      }

      return /*#__PURE__*/React.createElement("div", {
        "data-spm": "Xiala"
      }, /*#__PURE__*/React.createElement(Group, {
        compact: true,
        size: "large"
      }, prefix, /*#__PURE__*/React.createElement(AutoComplete, props, /*#__PURE__*/React.createElement(Input, inputProps)), /*#__PURE__*/React.createElement(Button, _extends({
        "data-spm": "Search",
        type: "primary",
        size: size,
        className: buttonClassName,
        onClick: this.handleConfirm
      }, regKeyProp), enterButton)), this.renderTipContent());
    }
  }], [{
    key: "addSuffix",
    value: function addSuffix(suffix, element) {
      if (!suffix.find(function (e) {
        return e.key === element.key;
      })) {
        suffix.push(element);
      }
    }
  }, {
    key: "getDerivedStateFromProps",
    value: function getDerivedStateFromProps(props, state) {
      return _objectSpread(_objectSpread({}, state), {}, {
        image: props.injectImage
      });
    }
  }]);

  return SearchInput;
}(Component);

export default SearchInput;