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 = ["children"];
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 _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 _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 _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 _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; }
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 _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, _toPropertyKey(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 _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 _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 ? Object.setPrototypeOf.bind() : 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.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
import React from 'react';
import { MoreOutlined } from '@ant-design/icons';
import { Button, Empty, Tag, Popover, Space, TreeSelect } from 'antd';
import isEqual from 'lodash-es/isEqual';
import difference from 'lodash-es/difference';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Ztree from "../vtx-ztree";
import "./style/index.less";
import { jsx as _jsx } from "react/jsx-runtime";
import { jsxs as _jsxs } from "react/jsx-runtime";
import { Fragment as _Fragment } from "react/jsx-runtime";
var VtxZtreeSelect = /*#__PURE__*/function (_React$Component) {
  _inherits(VtxZtreeSelect, _React$Component);
  var _super = _createSuper(VtxZtreeSelect);
  function VtxZtreeSelect(props) {
    var _this;
    _classCallCheck(this, VtxZtreeSelect);
    _this = _super.call(this, props);
    _this.tree = null;
    _this.treeRefreshFlag = 1;
    _this.treeRef = undefined;
    _this.clearFlag = false;
    _this.blurFlag = false;
    _this.state = {
      popoverVisible: false,
      popWidth: 0,
      searchValue: undefined,
      inputRef: null
    };
    _this.keyNodesMapping = {};
    _this.getKeyNodesMapping();
    _this.TextEnum = _objectSpread({
      alreadyChooseText: '已选择',
      clearChoosedOptionsText: '清空已选项',
      emptyDescriptionText: '暂无数据'
    }, props.customEnumText || {});
    return _this;
  }

  // UNSAFE_componentWillReceiveProps(nextProps) {
  //     if (!isEqual(this.props.data, nextProps.data)) {
  //         this.getKeyNodesMapping(nextProps.data);
  //     }
  //     if (!isEqual(this.props.expandedKeys, nextProps.expandedKeys)) {
  //         this.treeRefreshFlag++;
  //     }
  // }

  // 替换componentWillReceiveProps
  _createClass(VtxZtreeSelect, [{
    key: "componentDidUpdate",
    value: function componentDidUpdate(prevProps) {
      if (!isEqual(this.props.data, prevProps.data)) {
        this.getKeyNodesMapping(this.props.data);
      }
      if (!isEqual(this.props.expandedKeys, prevProps.expandedKeys)) {
        this.treeRefreshFlag++;
      }
    }
  }, {
    key: "getKeyNodesMapping",
    value: function getKeyNodesMapping(nodes) {
      var t = this;
      t.keyNodesMapping = {};
      (function genNodes(nodes) {
        nodes.map(function (item) {
          var children = item.children,
            rest = _objectWithoutProperties(item, _excluded);
          t.keyNodesMapping[item.key] = rest;
          if (Array.isArray(children) && children.length > 0) {
            genNodes(children);
          }
        });
      })(nodes || this.props.data || []);
    }
  }, {
    key: "clear",
    value: function clear() {
      if (this.tree) {
        if (this.props.treeCheckable) {
          this.tree.checkNodes(this.tree.getCheckedNodes().map(function (item) {
            return item.key;
          }), false);
        } else {
          this.tree.cancelSelectedNodes(this.props.value);
        }
      }
      this.props.onChange && this.props.onChange({
        nodes: [],
        keys: [],
        leafKeys: [],
        names: []
      });
      if (this.tree) {
        var _this$tree;
        this.setState({
          searchValue: ''
        });
        (_this$tree = this.tree) === null || _this$tree === void 0 || _this$tree.fuzzySearch('');
      }
    }
  }, {
    key: "clearKey",
    value: function clearKey(key) {
      var _this2 = this;
      var keyIndex = this.props.value.indexOf(key);
      if (keyIndex != -1) {
        var keyList = _toConsumableArray(this.props.value);
        keyList.splice(keyIndex, 1);
        var nodes = keyList.map(function (key) {
          return _this2.keyNodesMapping[key];
        });
        if (this.tree) {
          if (this.props.treeCheckable) {
            this.tree.checkNodes([key], false);
          } else {
            this.tree.cancelSelectedNodes([key]);
          }
        }
        this.props.onChange && this.props.onChange({
          nodes: nodes,
          keys: keyList,
          leafKeys: nodes.filter(function (item) {
            return item.isLeaf;
          }).map(function (item) {
            return item.key;
          }),
          names: nodes.map(function (item) {
            return item.name;
          })
        });
      }
    }
  }, {
    key: "clearSearch",
    value: function clearSearch() {
      this.tree && this.tree.clearSearch();
    }
  }, {
    key: "render",
    value: function render() {
      var _data$;
      var t = this;
      // 必填参数
      var _t$props = t.props,
        data = _t$props.data,
        value = _t$props.value;
      // 可配参数
      var _t$props2 = t.props,
        _t$props2$prefixCls = _t$props2.prefixCls,
        prefixCls = _t$props2$prefixCls === void 0 ? 'vtx-ztree-select' : _t$props2$prefixCls,
        _t$props2$treeCheckab = _t$props2.treeCheckable,
        treeCheckable = _t$props2$treeCheckab === void 0 ? false : _t$props2$treeCheckab,
        _t$props2$treeDefault = _t$props2.treeDefaultExpandAll,
        treeDefaultExpandAll = _t$props2$treeDefault === void 0 ? false : _t$props2$treeDefault,
        _t$props2$multiple = _t$props2.multiple,
        multiple = _t$props2$multiple === void 0 ? false : _t$props2$multiple,
        _t$props2$showSearch = _t$props2.showSearch,
        showSearch = _t$props2$showSearch === void 0 ? true : _t$props2$showSearch,
        searchPlaceholder = _t$props2.searchPlaceholder,
        _t$props2$dropdownSty = _t$props2.dropdownStyle,
        dropdownStyle = _t$props2$dropdownSty === void 0 ? {} : _t$props2$dropdownSty,
        _t$props2$style = _t$props2.style,
        style = _t$props2$style === void 0 ? {} : _t$props2$style,
        _t$props2$disabled = _t$props2.disabled,
        disabled = _t$props2$disabled === void 0 ? false : _t$props2$disabled,
        _t$props2$refreshFlag = _t$props2.refreshFlag,
        refreshFlag = _t$props2$refreshFlag === void 0 ? null : _t$props2$refreshFlag,
        expandedKeys = _t$props2.expandedKeys,
        customCfg = _t$props2.customCfg,
        checkStrictly = _t$props2.checkStrictly,
        _t$props2$maxTagCount = _t$props2.maxTagCount,
        maxTagCount = _t$props2$maxTagCount === void 0 ? 1 : _t$props2$maxTagCount,
        _t$props2$maxTagTextL = _t$props2.maxTagTextLength,
        maxTagTextLength = _t$props2$maxTagTextL === void 0 ? 5 : _t$props2$maxTagTextL,
        _t$props2$maxTagPlace = _t$props2.maxTagPlaceholder,
        maxTagPlaceholder = _t$props2$maxTagPlace === void 0 ? '...' : _t$props2$maxTagPlace,
        _t$props2$allowClear = _t$props2.allowClear,
        allowClear = _t$props2$allowClear === void 0 ? true : _t$props2$allowClear;
      // eslint-disable-next-line camelcase
      var value_arr = function (val) {
        if (Array.isArray(val)) {
          return val;
        } else if (val) {
          return [val];
        } else {
          return [];
        }
      }(value);
      var selectedNodes = value_arr.filter(function (k) {
        return k in t.keyNodesMapping;
      }).map(function (item) {
        return {
          id: item,
          name: t.keyNodesMapping[item].name
        };
      });
      // ztree配置
      var treeProps = _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({
        data: data,
        // 树的数据
        // showSearch: showSearch,
        showSearch: false,
        searchPlaceholder: searchPlaceholder,
        multiple: multiple,
        checkable: treeCheckable
      }, treeCheckable ? 'checkedKeys' : 'selectedKeys', value_arr), "defaultExpandAll", treeDefaultExpandAll), "expandedKeys", expandedKeys ? expandedKeys : treeDefaultExpandAll ? undefined : (data === null || data === void 0 || (_data$ = data[0]) === null || _data$ === void 0 ? void 0 : _data$.key) || '-1'), "refreshFlag", refreshFlag || t.treeRefreshFlag), "customCfg", customCfg), "checkStrictly", checkStrictly), "ref", function ref(instance) {
        if (instance) t.tree = instance;
      }), "onClick", function onClick(_ref) {
        var selectedNodes = _ref.selectedNodes,
          selectedKeys = _ref.selectedKeys,
          selectedNames = _ref.selectedNames;
        if (!treeCheckable) {
          t.props.onChange && t.props.onChange({
            nodes: selectedNodes,
            keys: selectedKeys,
            leafKeys: selectedNodes.filter(function (item) {
              return item.isLeaf;
            }).map(function (item) {
              return item.key;
            }),
            names: selectedNames
          });
          if (!multiple) {
            var _t$tree;
            t.setState({
              popoverVisible: false,
              searchValue: ''
            });
            (_t$tree = t.tree) === null || _t$tree === void 0 || _t$tree.fuzzySearch('');
            t.treeRef.blur();
          }
        }
      }), "onCheck", function onCheck(_ref2) {
        var checkedNodes = _ref2.checkedNodes,
          checkedKeys = _ref2.checkedKeys,
          checkedNames = _ref2.checkedNames;
        if (treeCheckable) {
          t.props.onChange && t.props.onChange({
            nodes: checkedNodes,
            keys: checkedKeys,
            leafKeys: checkedNodes.filter(function (item) {
              return item.isLeaf;
            }).map(function (item) {
              return item.key;
            }),
            names: checkedNames
          });
        }
      }), "beforeCheck", function beforeCheck(treeNode) {
        return t.props.beforeCheck ? t.props.beforeCheck(treeNode) : true;
      });
      // 多选组件
      var MultiSelect = /*#__PURE__*/_jsx("div", {
        className: classnames("".concat(prefixCls, "-multiple-box")),
        style: style,
        ref: function ref(_ref4) {
          if (!t.state.popWidth && _ref4 !== null && _ref4 !== void 0 && _ref4.clientWidth) {
            t.setState({
              popWidth: _ref4 === null || _ref4 === void 0 ? void 0 : _ref4.clientWidth
            });
          }
        },
        children: /*#__PURE__*/_jsxs(Space.Compact, {
          style: {
            width: '100%'
          },
          children: [/*#__PURE__*/_jsx(TreeSelect, {
            value: selectedNodes.map(function (item) {
              return {
                value: item.id,
                label: item.name
              };
            }),
            multiple: true,
            style: style,
            disabled: disabled,
            placeholder: t.props.placeholder,
            showSearch: showSearch ? {
              onSearch: function onSearch(e) {
                var _t$tree2;
                (_t$tree2 = t.tree) === null || _t$tree2 === void 0 || _t$tree2.fuzzySearch(e ? e.trim() : '');
              }
            } : false,
            ref: function ref(_ref3) {
              t.treeRef = _ref3;
            },
            onFocus: function onFocus(e) {
              if (!t.clearFlag) {
                t.setState({
                  popoverVisible: true
                });
              }
              t.clearFlag = false;
            },
            onBlur: function onBlur() {
              if (!t.blurFlag) {
                t.setState({
                  popoverVisible: false
                });
              } else {
                t.blurFlag = false;
                t.treeRef.focus();
              }
            },
            onClear: function onClear() {
              // 防止onFocus打开
              t.clearFlag = true;
              // 主动失去Focus
              setTimeout(function () {
                t.treeRef.blur();
              }, [50]);
            },
            onChange: function onChange(e) {
              console.log(e, t.tree);
              if (e.length == 0) {
                t.clear();
              } else {
                var res = difference(selectedNodes.map(function (item) {
                  return item.id;
                }), e);
                console.log('res', res);
                res === null || res === void 0 || res.map(function (v) {
                  t.clearKey(v);
                });
              }
              // if (e && t.tree) {
              //     t.setState({ searchValue: e.target.value });
              //     t.tree?.fuzzySearch(e.target.value.trim());
              // } else {
              //    
              // }
            },
            open: t.state.popoverVisible,
            treeData: [],
            allowClear: allowClear,
            popupRender: function popupRender() {
              return /*#__PURE__*/_jsx("div", {
                className: "".concat(prefixCls, "-popover"),
                style: dropdownStyle,
                onMouseDown: function onMouseDown(e) {
                  t.blurFlag = true;
                },
                children: /*#__PURE__*/_jsx(Ztree, _objectSpread({}, treeProps))
              });
            },
            maxTagCount: maxTagCount,
            maxTagTextLength: maxTagTextLength,
            maxTagPlaceholder: maxTagPlaceholder
          }), /*#__PURE__*/_jsx(Popover, {
            content: /*#__PURE__*/_jsxs(_Fragment, {
              children: [/*#__PURE__*/_jsxs("div", {
                className: classnames('vtx-tree-count-head'),
                children: [/*#__PURE__*/_jsxs("span", {
                  children: [this.TextEnum.alreadyChooseText, "\uFF1A", selectedNodes.length]
                }), /*#__PURE__*/_jsx("span", {
                  className: classnames(selectedNodes.length > 0 && !disabled ? 'clear-count' : 'disabled-count'),
                  onClick: function onClick(e) {
                    if (!disabled) {
                      e.stopPropagation();
                      t.clear();
                    }
                  },
                  children: this.TextEnum.clearChoosedOptionsText
                })]
              }), selectedNodes.length > 0 ? selectedNodes.map(function (item) {
                return /*#__PURE__*/_jsx(Tag, {
                  closable: !disabled,
                  onClose: function onClose(e) {
                    e.stopPropagation();
                    t.clearKey(item.id);
                  },
                  style: {
                    marginBottom: '5px'
                  },
                  children: item.name && item.name.length > 20 ? "".concat(item.name.slice(0, 20), "...") : item.name
                }, "tab-".concat(item.id));
              }) : /*#__PURE__*/_jsx(Empty, {
                image: Empty.PRESENTED_IMAGE_SIMPLE,
                description: this.TextEnum.emptyDescriptionText
              })]
            }),
            placement: "bottomRight",
            trigger: "click",
            styles: {
              container: {
                width: t.state.popWidth
              }
            },
            children: /*#__PURE__*/_jsx(Button, {
              className: "vtx-tree-count",
              icon: /*#__PURE__*/_jsx(MoreOutlined, {}),
              size: "default",
              onClick: function onClick(e) {
                e.stopPropagation();
              }
            })
          })]
        })
      });

      // 单选组件
      var SingleSelect = /*#__PURE__*/_jsx(TreeSelect, _defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({
        value: (selectedNodes === null || selectedNodes === void 0 ? void 0 : selectedNodes.length) > 0 ? selectedNodes.map(function (item) {
          return item.name;
        }).join(', ') : undefined,
        style: style,
        disabled: disabled,
        placeholder: t.props.placeholder,
        showSearch: showSearch ? {
          onSearch: function onSearch(e) {
            var _t$tree3;
            (_t$tree3 = t.tree) === null || _t$tree3 === void 0 || _t$tree3.fuzzySearch(e ? e.trim() : '');
          }
        } : false,
        ref: function ref(_ref5) {
          t.treeRef = _ref5;
        },
        onFocus: function onFocus(e) {
          if (!t.clearFlag) {
            t.setState({
              focusSingle: true,
              popoverVisible: true
            });
          }
          t.clearFlag = false;
        }
      }, "style", {
        width: '100%'
      }), "onBlur", function onBlur() {
        if (!t.blurFlag) {
          t.setState({
            popoverVisible: false
          });
        } else {
          t.blurFlag = false;
          t.treeRef.focus();
        }
      }), "onClear", function onClear() {
        // 防止onFocus打开
        t.clearFlag = true;
        // 主动失去Focus
        setTimeout(function () {
          t.treeRef.blur();
        }, [50]);
      }), "onChange", function onChange(e) {
        if (!e) {
          t.clear();
        }
      }), "open", t.state.popoverVisible), "treeData", []), "allowClear", allowClear), "popupRender", function popupRender() {
        return /*#__PURE__*/_jsx("div", {
          className: "".concat(prefixCls, "-popover"),
          style: dropdownStyle,
          onMouseDown: function onMouseDown(e) {
            t.blurFlag = true;
          },
          children: /*#__PURE__*/_jsx(Ztree, _objectSpread({}, treeProps))
        });
      }));
      return /*#__PURE__*/_jsx("div", {
        className: "".concat(prefixCls, " css-var-root"),
        children: multiple || treeCheckable ? MultiSelect : SingleSelect
      });
    }
  }]);
  return VtxZtreeSelect;
}(React.Component);
VtxZtreeSelect.propTypes = {
  data: PropTypes.array,
  expandedKeys: PropTypes.arrayOf(PropTypes.string),
  treeCheckable: PropTypes.bool,
  value: PropTypes.oneOfType([PropTypes.string, PropTypes.arrayOf(PropTypes.string)]),
  onChange: PropTypes.func,
  popoverProps: PropTypes.object,
  allowClear: PropTypes.bool,
  customEnumText: PropTypes.object
};
export { VtxZtreeSelect };
export default VtxZtreeSelect;