function _extends() { _extends = Object.assign ? Object.assign.bind() : 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 _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(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

import { __rest } from "tslib";
import React, { createElement, forwardRef, Fragment, useCallback, useContext, useEffect, useMemo, useRef, useState, useImperativeHandle } from "react";
import classNames from 'classnames';
import { Text } from "@alifd/meet-react-component-one";
import View from '../view';
import { ItemContext } from '../form';
import BottomButton from '../bottom-button';
import SelectDrawer from '../select-drawer';
import { useLocale } from '../locale';
import defaultLang from '../locale/lang/zh-cn';
import { useValue } from '../utils/hooks';
import { findInArray, getDataSource, isFunction, isString, isValidArray } from '../utils';
import SelectBody from './section/select-body';
import SelectSearch from './section/select-search';
import SelectedListDrawer from './section/selected-list-drawer';
import SelectContext from './context';
import { defaultLocalFilter, getValidEvtValues, innerRenderSelection, isEqualItems } from './util';
var AUTO_CLOSE_WAITING_TIME = 300;

var compare = function compare(a, b) {
  return isEqualItems(a, b, true);
};

var BaseSelect = function BaseSelect(props, ref) {
  var _props$prefix = props.prefix,
      prefix = _props$prefix === void 0 ? 'mt-' : _props$prefix,
      placeholder = props.placeholder,
      _value = props.value,
      type = props.type,
      defaultValue = props.defaultValue,
      className = props.className,
      mode = props.mode,
      hasSearch = props.hasSearch,
      children = props.children,
      _dataSource = props.dataSource,
      displayType = props.displayType,
      disabled = props.disabled,
      autoConfirm = props.autoConfirm,
      hasClear = props.hasClear,
      filterLocal = props.filterLocal,
      transferSearchToOption = props.transferSearchToOption,
      _props$filter = props.filter,
      filter = _props$filter === void 0 ? defaultLocalFilter : _props$filter,
      renderSelection = props.renderSelection,
      useDetailValue = props.useDetailValue,
      _locale = props.locale,
      sizeProp = props.size,
      notFoundContent = props.notFoundContent,
      onVisibleChange = props.onVisibleChange,
      _props$onChange = props.onChange,
      onChange = _props$onChange === void 0 ? function () {} : _props$onChange,
      _props$onClear = props.onClear,
      onClear = _props$onClear === void 0 ? function () {} : _props$onClear,
      _props$onCancel = props.onCancel,
      onCancel = _props$onCancel === void 0 ? function () {} : _props$onCancel,
      _props$onOk = props.onOk,
      onOk = _props$onOk === void 0 ? function () {} : _props$onOk,
      onSearch = props.onSearch,
      others = __rest(props, ["prefix", "placeholder", "value", "type", "defaultValue", "className", "mode", "hasSearch", "children", "dataSource", "displayType", "disabled", "autoConfirm", "hasClear", "filterLocal", "transferSearchToOption", "filter", "renderSelection", "useDetailValue", "locale", "size", "notFoundContent", "onVisibleChange", "onChange", "onClear", "onCancel", "onOk", "onSearch"]);

  var _useContext = useContext(ItemContext),
      isInsideForm = _useContext.isInsideForm,
      contextSize = _useContext.size;

  var size = sizeProp || (isInsideForm ? contextSize : 'medium');

  var _useState = useState(''),
      _useState2 = _slicedToArray(_useState, 2),
      searchVal = _useState2[0],
      setSearchVal = _useState2[1];

  var _useState3 = useState(false),
      _useState4 = _slicedToArray(_useState3, 2),
      drawerVisible = _useState4[0],
      setDrawerVisible = _useState4[1];

  var selectLocale = useLocale('Select', props, defaultLang.Select);
  var selectDrawerLocal = useLocale('SelectDrawer', {}, defaultLang.SelectDrawer);
  var clsPrefix = "".concat(prefix, "select");
  var baseSelectRef = useRef(null);
  var dataSource = useMemo(function () {
    return getDataSource(props.dataSource, props.children);
  }, [props.dataSource, props.children]);

  var fitValue = function fitValue(v) {
    if (v === '' || v === null) {
      return [];
    }

    var x = Array.isArray(v) ? v : [v];

    if (useDetailValue) {
      return x;
    } else if (isValidArray(x)) {
      return x.map(function (item) {
        var tmp = findInArray(dataSource, function (d) {
          return d.value === item;
        });
        return tmp || {
          label: item,
          value: item
        };
      });
    } else {
      return [];
    }
  };

  var _useValue = useValue(props, [], {
    fitValue: fitValue,
    compare: compare
  }),
      _useValue2 = _slicedToArray(_useValue, 3),
      value = _useValue2[0],
      setValue = _useValue2[1],
      isControlled = _useValue2[2];

  var _useState5 = useState(value),
      _useState6 = _slicedToArray(_useState5, 2),
      innerValue = _useState6[0],
      setInnerValue = _useState6[1];

  var _useState7 = useState(false),
      _useState8 = _slicedToArray(_useState7, 2),
      confirmVisible = _useState8[0],
      setConfirmVisible = _useState8[1];

  var isSingle = mode === 'single';
  var searchRef = useRef(null);
  var realHasSearch = props.hasSearch || props.showSearch;
  useMemo(function () {
    if (isControlled && !compare(value, innerValue)) {
      setInnerValue(value);
    }
  }, [value]);
  var handleCancel = useCallback(function (reason) {
    if (searchRef && searchRef.current) {
      searchRef.current.setValue('');
    }

    if (isFunction(onCancel)) {
      onCancel(reason);
    }

    setTimeout(function () {
      setInnerValue(value);
    }, 300);
  }, [value]);

  var handleOk = function handleOk() {
    if (!isControlled) {
      setValue(innerValue);
    }

    var changed = !isEqualItems(value, innerValue);

    if (isFunction(onOk)) {
      onOk();
    }

    if (changed && isFunction(onChange)) {
      var _getValidEvtValues = getValidEvtValues({
        selectedItems: innerValue,
        isSingle: isSingle,
        useDetailValue: useDetailValue
      }),
          val = _getValidEvtValues.value,
          items = _getValidEvtValues.items;

      onChange(val, 'change', items);
    }

    if (searchRef === null || searchRef === void 0 ? void 0 : searchRef.current) {
      searchRef.current.setValue('');
    }
  };

  var handleTotalClick = function handleTotalClick() {
    setConfirmVisible(true);
  };

  var handleClear = function handleClear() {
    if (!isControlled) {
      setValue([]);
      setInnerValue([]);

      if (searchRef === null || searchRef === void 0 ? void 0 : searchRef.current) {
        searchRef.current.setValue('');
      }
    }

    if (isFunction(onClear)) {
      onClear();
    }

    if (isFunction(onChange)) {
      var _getValidEvtValues2 = getValidEvtValues({
        selectedItems: [],
        useDetailValue: useDetailValue,
        isSingle: isSingle
      }),
          val = _getValidEvtValues2.value,
          items = _getValidEvtValues2.items;

      onChange(val, 'clear', items);
    }
  };

  var handleConfirmDone = function handleConfirmDone(items) {
    setInnerValue(items);
    setConfirmVisible(false);
  };

  var handleConfirmCancel = function handleConfirmCancel() {
    setConfirmVisible(false);
  };

  var handleBottomOk = function handleBottomOk() {
    var _a;

    if ((_a = baseSelectRef === null || baseSelectRef === void 0 ? void 0 : baseSelectRef.current) === null || _a === void 0 ? void 0 : _a.ok) {
      baseSelectRef.current.ok();
    }
  };

  var handleBottomCancel = function handleBottomCancel() {
    var _a;

    if ((_a = baseSelectRef === null || baseSelectRef === void 0 ? void 0 : baseSelectRef.current) === null || _a === void 0 ? void 0 : _a.cancel) {
      baseSelectRef.current.cancel('cancel-button');
    }
  };

  var handleVisibleChange = function handleVisibleChange(visible) {
    setDrawerVisible(visible);

    if (isFunction(onVisibleChange)) {
      onVisibleChange(visible);
    }
  };

  var contextValue = useMemo(function () {
    return Object.assign(Object.assign({}, props), {
      hasSearch: realHasSearch,
      dataSource: dataSource,
      type: type,
      mode: mode,
      size: size,
      prefix: prefix,
      value: value,
      innerValue: innerValue,
      displayType: displayType,
      locale: selectLocale,
      onChange: function onChange(v) {
        setInnerValue(v);
      },
      searchValue: searchVal,
      setSearchValue: setSearchVal
    });
  }, [props, realHasSearch, dataSource, type, mode, size, prefix, value, innerValue, displayType, selectLocale, searchVal]);
  useEffect(function () {
    if (drawerVisible && isSingle && !realHasSearch && autoConfirm === true) {
      setTimeout(function () {
        var _a;

        if ((_a = baseSelectRef === null || baseSelectRef === void 0 ? void 0 : baseSelectRef.current) === null || _a === void 0 ? void 0 : _a.ok) {
          baseSelectRef.current.ok();
        }
      }, AUTO_CLOSE_WAITING_TIME);
    }
  }, [innerValue]);
  useImperativeHandle(ref, function () {
    return Object.assign(baseSelectRef.current);
  });
  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(SelectDrawer, _extends({}, others, {
    hideButton: isSingle && autoConfirm === true,
    size: size,
    ref: baseSelectRef,
    showToolbar: !realHasSearch,
    type: type,
    disabled: disabled,
    placeholder: placeholder,
    hasClear: hasClear,
    className: classNames(clsPrefix, className),
    content: renderSelection ? renderSelection(value) : innerRenderSelection(value, contextValue),
    onClear: handleClear,
    onCancel: handleCancel,
    onOk: handleOk,
    onVisibleChange: handleVisibleChange,
    drawerClassName: classNames(_defineProperty({}, "".concat(clsPrefix, "--searchable"), realHasSearch))
  }), /*#__PURE__*/React.createElement(SelectContext.Provider, {
    value: contextValue
  }, /*#__PURE__*/React.createElement(Fragment, null, realHasSearch && /*#__PURE__*/React.createElement(SelectSearch, {
    ref: searchRef
  }), dataSource.length === 0 && !realHasSearch ? /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-drawer-content ").concat(clsPrefix, "drawer-drawer--empty")
  }, isString(notFoundContent) ? /*#__PURE__*/React.createElement(Text, {
    className: "".concat(clsPrefix, "drawer-drawer-empty-text")
  }, notFoundContent) : /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "drawer-drawer-empty-text")
  }, notFoundContent)) : /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-option-list")
  }, /*#__PURE__*/React.createElement(SelectBody, {
    emptySearchText: selectLocale.emptySearchText,
    searchToOptionBtnText: selectLocale.searchToOptionBtnText
  })), realHasSearch && /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-drawer-footer")
  }, /*#__PURE__*/React.createElement(BottomButton, {
    okText: selectDrawerLocal.ok,
    cancelText: selectDrawerLocal.cancel,
    onOk: handleBottomOk,
    onCancel: handleBottomCancel
  }, !isSingle && /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-footer-counter"),
    onClick: handleTotalClick
  }, /*#__PURE__*/React.createElement(Text, null, selectLocale.totalPrefixText), /*#__PURE__*/React.createElement(Text, {
    className: "".concat(clsPrefix, "-total-num")
  }, innerValue.length), /*#__PURE__*/React.createElement(Text, null, selectLocale.totalSuffixText))))))), !isSingle && /*#__PURE__*/React.createElement(SelectedListDrawer, {
    prefix: contextValue.prefix,
    innerValue: contextValue.innerValue,
    locale: contextValue.locale,
    visible: confirmVisible,
    onOk: handleConfirmDone,
    onCancel: handleConfirmCancel
  }));
};

var RefBaseSelect = /*#__PURE__*/forwardRef(BaseSelect);
RefBaseSelect.displayName = 'BaseSelect';
RefBaseSelect.defaultProps = {
  mode: 'single',
  type: 'normal',
  displayType: 'normal',
  disabled: false,
  hideButton: false,
  transferSearchToOption: false,
  filterLocal: false,
  hasClear: false,
  autoConfirm: false,
  notFoundContent: '',
  stickyOnTop: false
};
export default RefBaseSelect;