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 _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, useMemo, useRef, useState, useImperativeHandle } from "react";
import classNames from 'classnames';
import { ScrollView, Text } from "@alifd/meet-react-component-one";
import Button from '../button';
import View from '../view';
import { ItemContext } from '../form';
import SelectDrawer from '../select-drawer';
import SafeArea from '../safe-area';
import SelectBody from './section/select-body';
import SelectSearch from './section/select-search';
import SelectedListDrawer from './section/selected-list-drawer';
import { useLocale } from '../locale';
import defaultLang from '../locale/lang/zh-cn';
import { findInArray, getDataSource, isFunction, isString, isValidArray } from '../utils';
import { useValue } from '../utils/hooks';
import SelectContext from './context';
import { defaultLocalFilter, getValidEvtValues, innerRenderSelection, isEqualItems } from './util';

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,
      _props$type = props.type,
      type = _props$type === void 0 ? 'normal' : _props$type,
      defaultValue = props.defaultValue,
      className = props.className,
      _props$mode = props.mode,
      mode = _props$mode === void 0 ? 'single' : _props$mode,
      hasSearch = props.hasSearch,
      children = props.children,
      _dataSource = props.dataSource,
      _props$disabled = props.disabled,
      disabled = _props$disabled === void 0 ? false : _props$disabled,
      hasClear = props.hasClear,
      onSearch = props.onSearch,
      _props$displayType = props.displayType,
      displayType = _props$displayType === void 0 ? 'normal' : _props$displayType,
      _props$filterLocal = props.filterLocal,
      filterLocal = _props$filterLocal === void 0 ? true : _props$filterLocal,
      _props$filter = props.filter,
      filter = _props$filter === void 0 ? defaultLocalFilter : _props$filter,
      renderSelection = props.renderSelection,
      useDetailValue = props.useDetailValue,
      _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,
      _locale = props.locale,
      sizeProp = props.size,
      _props$notFoundConten = props.notFoundContent,
      notFoundContent = _props$notFoundConten === void 0 ? '' : _props$notFoundConten,
      others = __rest(props, ["prefix", "placeholder", "value", "type", "defaultValue", "className", "mode", "hasSearch", "children", "dataSource", "disabled", "hasClear", "onSearch", "displayType", "filterLocal", "filter", "renderSelection", "useDetailValue", "onChange", "onClear", "onCancel", "locale", "size", "notFoundContent"]);

  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 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 compare = function compare(a, b) {
    return isEqualItems(a, b, true);
  };

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

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

  var _useState5 = useState(false),
      _useState6 = _slicedToArray(_useState5, 2),
      confirmVisible = _useState6[0],
      setConfirmVisible = _useState6[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) {
    setInnerValue(value);

    if (searchRef && searchRef.current) {
      searchRef.current.setValue('');
    }

    if (baseSelectRef && baseSelectRef.current) {
      baseSelectRef.current.hide();
    }

    if (isFunction(onCancel)) {
      onCancel(reason);
    }
  }, [value]);

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

    var changed = !isEqualItems(value, innerValue);

    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 && searchRef.current) {
      searchRef.current.setValue('');
    }

    if (baseSelectRef && baseSelectRef.current) {
      baseSelectRef.current.hide();
    }
  };

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

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

      if (searchRef && 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 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) {
        return setInnerValue(v);
      },
      searchValue: searchVal,
      setSearchValue: setSearchVal
    });
  }, [props, realHasSearch, dataSource, type, mode, size, prefix, value, innerValue, displayType, selectLocale, searchVal]);
  useImperativeHandle(ref, function () {
    return Object.assign(baseSelectRef.current);
  });
  return /*#__PURE__*/React.createElement(Fragment, null, /*#__PURE__*/React.createElement(SelectDrawer, _extends({}, others, {
    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,
    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(ScrollView, {
    className: "".concat(clsPrefix, "-option-list")
  }, /*#__PURE__*/React.createElement(SelectBody, null)), realHasSearch && /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-drawer-footer")
  }, !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)), /*#__PURE__*/React.createElement(View, {
    className: "".concat(clsPrefix, "-drawer-btn-wrapper")
  }, /*#__PURE__*/React.createElement(Button, {
    size: "large",
    className: "".concat(clsPrefix, "-footer-button"),
    type: "primary",
    model: "outline",
    onClick: function onClick() {
      return handleCancel('cancel-button');
    }
  }, selectDrawerLocal.cancel), /*#__PURE__*/React.createElement(Button, {
    size: "large",
    className: "".concat(clsPrefix, "-footer-button"),
    type: "primary",
    model: "solid",
    onClick: handleOk
  }, selectDrawerLocal.ok)), /*#__PURE__*/React.createElement(SafeArea, null))))), !isSingle && /*#__PURE__*/React.createElement(SelectedListDrawer, {
    prefix: contextValue.prefix,
    innerValue: contextValue.innerValue,
    locale: contextValue.locale,
    visible: confirmVisible,
    onOk: handleConfirmDone
  }));
};

BaseSelect.displayName = 'SelectDrawer';
export default /*#__PURE__*/forwardRef(BaseSelect);