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); }
var _excluded = ["options", "value", "onChange", "selectAllValue", "selectAllLabel", "placeholder", "searchPlaceholder", "dropdownWidth", "style", "isShowSearch"];
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 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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
import { SearchOutlined } from '@ant-design/icons';
import { Checkbox, ConfigProvider, Empty, Input, Select, Tag } from 'antd';
import React, { useContext, useEffect, useMemo, useState } from 'react';
import { useLogCenterLocale } from "./context";
import "./select-with-all.less";
function isOptionGroup(item) {
  return !!item.options;
}
var SelectWithAll = function SelectWithAll(props) {
  var _useContext, _rest$maxTagCount;
  var _props$options = props.options,
    options = _props$options === void 0 ? [] : _props$options,
    value = props.value,
    onChange = props.onChange,
    _props$selectAllValue = props.selectAllValue,
    selectAllValue = _props$selectAllValue === void 0 ? '*' : _props$selectAllValue,
    selectAllLabel = props.selectAllLabel,
    placeholder = props.placeholder,
    searchPlaceholder = props.searchPlaceholder,
    dropdownWidth = props.dropdownWidth,
    style = props.style,
    _props$isShowSearch = props.isShowSearch,
    isShowSearch = _props$isShowSearch === void 0 ? true : _props$isShowSearch,
    rest = _objectWithoutProperties(props, _excluded);
  var _useState = useState(value !== null && value !== void 0 ? value : []),
    _useState2 = _slicedToArray(_useState, 2),
    internalValue = _useState2[0],
    setInternalValue = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    searchText = _useState4[0],
    setSearchText = _useState4[1];
  var configLocale = (_useContext = useContext(ConfigProvider.ConfigContext)) === null || _useContext === void 0 ? void 0 : _useContext.locale;
  var locale = useLogCenterLocale();
  var _useMemo = useMemo(function () {
      var found = null;
      var sec = [];
      var allFlat = [];
      var _iterator = _createForOfIteratorHelper(options),
        _step;
      try {
        for (_iterator.s(); !(_step = _iterator.n()).done;) {
          var item = _step.value;
          if (isOptionGroup(item)) {
            sec.push({
              type: 'group',
              label: item.label,
              options: item.options
            });
            allFlat.push.apply(allFlat, _toConsumableArray(item.options));
          } else if (item && item.value !== undefined) {
            if (item.value === selectAllValue) {
              found = item;
            } else {
              sec.push({
                type: 'flat',
                option: item
              });
              allFlat.push(item);
            }
          }
        }
      } catch (err) {
        _iterator.e(err);
      } finally {
        _iterator.f();
      }
      return {
        allOption: found,
        allSelectableOptions: allFlat,
        sections: sec
      };
    }, [options, selectAllValue]),
    allOption = _useMemo.allOption,
    allSelectableOptions = _useMemo.allSelectableOptions,
    sections = _useMemo.sections;
  var optionsFingerprint = useMemo(function () {
    var parts = [];
    var _iterator2 = _createForOfIteratorHelper(options),
      _step2;
    try {
      for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
        var item = _step2.value;
        if (isOptionGroup(item)) {
          parts.push("g:".concat(String(item.label)));
          var _iterator3 = _createForOfIteratorHelper(item.options),
            _step3;
          try {
            for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
              var o = _step3.value;
              parts.push("o:".concat(String(o.value), ":").concat(String(o.label)));
            }
          } catch (err) {
            _iterator3.e(err);
          } finally {
            _iterator3.f();
          }
        } else if (item && item.value !== undefined) {
          var _o = item;
          parts.push("o:".concat(String(_o.value), ":").concat(String(_o.label)));
        }
      }
    } catch (err) {
      _iterator2.e(err);
    } finally {
      _iterator2.f();
    }
    return parts.join('|');
  }, [options]);
  var allSelectableValues = useMemo(function () {
    return allSelectableOptions.map(function (o) {
      return o.value;
    });
  }, [allSelectableOptions]);
  var isAllSelected = useMemo(function () {
    if (internalValue.includes(selectAllValue)) return true;
    if (allSelectableValues.length === 0) return false;
    return internalValue.length === allSelectableValues.length && allSelectableValues.every(function (v) {
      return internalValue.includes(v);
    });
  }, [internalValue, selectAllValue, allSelectableValues]);
  var isItemSelected = function isItemSelected(v) {
    return isAllSelected || internalValue.includes(v);
  };
  var allCheckIndeterminate = useMemo(function () {
    var n = internalValue.filter(function (v) {
      return v !== selectAllValue;
    }).length;
    return n > 0 && n < allSelectableValues.length;
  }, [internalValue, selectAllValue, allSelectableValues]);
  var allCheckChecked = isAllSelected;
  var filteredSections = useMemo(function () {
    if (!searchText.trim()) return sections;
    var lower = searchText.toLowerCase().trim();
    var filterOpts = function filterOpts(opts) {
      return opts.filter(function (o) {
        return String(o.label).toLowerCase().includes(lower) || String(o.value).toLowerCase().includes(lower);
      });
    };
    return sections.map(function (s) {
      if (s.type === 'group') {
        var filtered = filterOpts(s.options);
        if (filtered.length === 0) return null;
        return _objectSpread(_objectSpread({}, s), {}, {
          options: filtered
        });
      }
      var o = s.option;
      if (String(o.label).toLowerCase().includes(lower) || String(o.value).toLowerCase().includes(lower)) {
        return s;
      }
      return null;
    }).filter(Boolean);
  }, [sections, searchText]);
  useEffect(function () {
    if (value) setInternalValue(value);
  }, [value]);
  useEffect(function () {
    setSearchText('');
  }, [optionsFingerprint]);
  var updateValue = function updateValue(next) {
    setInternalValue(next);
    onChange === null || onChange === void 0 || onChange(next);
  };
  var handleSelectAllChange = function handleSelectAllChange(checked) {
    if (checked && allOption) {
      updateValue([selectAllValue]);
    } else {
      updateValue([]);
    }
  };
  var handleItemChange = function handleItemChange(optValue, checked) {
    var next;
    if (internalValue.includes(selectAllValue)) {
      next = checked ? [selectAllValue] : allSelectableValues.filter(function (v) {
        return v !== optValue;
      });
    } else if (checked) {
      next = [].concat(_toConsumableArray(internalValue), [optValue]);
      if (allOption && next.length === allSelectableValues.length) {
        next = [selectAllValue];
      }
    } else {
      next = internalValue.filter(function (v) {
        return v !== optValue;
      });
    }
    updateValue(next);
  };
  var tagRender = function tagRender(tagProps) {
    var label = tagProps.label,
      v = tagProps.value,
      _onClose = tagProps.onClose;
    if (isAllSelected && allOption) {
      if (v === selectAllValue) {
        var _ref, _ref2, _configLocale$common;
        var text = (_ref = (_ref2 = selectAllLabel !== null && selectAllLabel !== void 0 ? selectAllLabel : allOption.label) !== null && _ref2 !== void 0 ? _ref2 : configLocale === null || configLocale === void 0 || (_configLocale$common = configLocale.common) === null || _configLocale$common === void 0 ? void 0 : _configLocale$common.all) !== null && _ref !== void 0 ? _ref : locale.common.all;
        return /*#__PURE__*/React.createElement(Tag, {
          closable: true,
          onClose: function onClose(e) {
            e.preventDefault();
            _onClose();
          }
        }, text);
      }
      return /*#__PURE__*/React.createElement("span", {
        style: {
          display: 'none'
        }
      });
    }
    return /*#__PURE__*/React.createElement(Tag, {
      closable: true,
      onClose: function onClose(e) {
        e.preventDefault();
        _onClose();
      }
    }, label);
  };
  var popupRender = function popupRender() {
    return /*#__PURE__*/React.createElement("div", {
      style: {
        minWidth: dropdownWidth !== null && dropdownWidth !== void 0 ? dropdownWidth : '100%'
      }
    }, isShowSearch && /*#__PURE__*/React.createElement(Input, {
      placeholder: searchPlaceholder || locale.log['请输入关键字'],
      prefix: /*#__PURE__*/React.createElement(SearchOutlined, null),
      value: searchText,
      onChange: function onChange(e) {
        return setSearchText(e.target.value);
      },
      allowClear: true,
      className: "search-input"
    }), /*#__PURE__*/React.createElement("div", {
      className: "items"
    }, !searchText && allOption && /*#__PURE__*/React.createElement(Checkbox, {
      checked: allCheckChecked,
      indeterminate: allCheckIndeterminate,
      onChange: function onChange(e) {
        e.stopPropagation();
        handleSelectAllChange(e.target.checked);
      },
      onClick: function onClick(e) {
        e.stopPropagation();
        handleSelectAllChange(!allCheckChecked);
      },
      className: "checkbox-all"
    }, allOption.label), filteredSections.map(function (s, idx) {
      if (s.type === 'group') {
        return /*#__PURE__*/React.createElement("div", {
          key: "group-".concat(idx)
        }, /*#__PURE__*/React.createElement("h5", null, s.label), s.options.map(function (o) {
          return /*#__PURE__*/React.createElement(Checkbox, {
            key: "group-".concat(idx, "-").concat(o.value),
            checked: isItemSelected(o.value),
            disabled: o.disabled,
            onChange: function onChange(e) {
              e.stopPropagation();
              if (!o.disabled) handleItemChange(o.value, e.target.checked);
            },
            onClick: function onClick(e) {
              e.stopPropagation();
              if (!o.disabled) handleItemChange(o.value, !isItemSelected(o.value));
            }
          }, o.label, o.dataSource === 'es' && /*#__PURE__*/React.createElement(Tag, null, locale.history));
        }));
      }
      var o = s.option;
      return /*#__PURE__*/React.createElement(Checkbox, {
        key: "flat-".concat(idx, "-").concat(o.value),
        checked: isItemSelected(o.value),
        disabled: o.disabled,
        onChange: function onChange(e) {
          e.stopPropagation();
          if (!o.disabled) handleItemChange(o.value, e.target.checked);
        },
        onClick: function onClick(e) {
          e.stopPropagation();
          if (!o.disabled) handleItemChange(o.value, !isItemSelected(o.value));
        }
      }, o.label, o.dataSource === 'es' && /*#__PURE__*/React.createElement(Tag, null, locale.history));
    }), filteredSections.length === 0 && /*#__PURE__*/React.createElement(Empty, {
      image: Empty.PRESENTED_IMAGE_SIMPLE,
      description: searchText ? locale.common.noData : locale.common.empty
    })));
  };
  var selectOptions = useMemo(function () {
    var list = [];
    if (allOption) list.push(allOption);
    list.push.apply(list, _toConsumableArray(allSelectableOptions));
    return list;
  }, [allOption, allSelectableOptions]);
  return /*#__PURE__*/React.createElement(Select, _extends({
    mode: "multiple",
    value: internalValue,
    onChange: updateValue,
    placeholder: placeholder || locale.log['请选择'],
    tagRender: tagRender,
    dropdownRender: popupRender,
    maxTagCount: isAllSelected && allOption ? 1 : (_rest$maxTagCount = rest.maxTagCount) !== null && _rest$maxTagCount !== void 0 ? _rest$maxTagCount : 'responsive',
    allowClear: true
  }, rest, {
    showSearch: false,
    popupMatchSelectWidth: false,
    className: "select-with-all-selection",
    popupClassName: "select-with-all-dropdown",
    options: selectOptions.map(function (o) {
      return {
        label: o.label,
        value: o.value,
        disabled: o.disabled
      };
    })
  }));
};
export default SelectWithAll;