import _objectSpread from "@babel/runtime/helpers/esm/objectSpread2";
import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import Tree from '../tree';
import Select from '../select';
import { traverse } from '../tree/utils/traverseUtils';

function valuetoArray(val) {
  if (typeof val === 'undefined' || val === null) return [];
  return Array.isArray(val) ? val : [val];
}

var TreeSelectRenderFunction = function TreeSelectRenderFunction(props, ref) {
  var _props$treeData = props.treeData,
      treeData = _props$treeData === void 0 ? [] : _props$treeData,
      outerValue = props.value,
      outerOpen = props.open,
      outerSearchValue = props.treeSearchValue,
      multiple = props.multiple,
      treeCheckable = props.treeCheckable,
      onChange = props.onChange,
      showTreeIcon = props.showTreeIcon,
      _props$fieldNames = props.fieldNames,
      fieldNames = _props$fieldNames === void 0 ? {
    title: 'title',
    value: 'value',
    children: 'children'
  } : _props$fieldNames,
      virtual = props.virtual,
      listHeight = props.listHeight,
      outerOnTreeExpand = props.onTreeExpand,
      loadData = props.loadData,
      dropdownRender = props.dropdownRender,
      _props$nodeTextWidth = props.nodeTextWidth,
      nodeTextWidth = _props$nodeTextWidth === void 0 ? 100 : _props$nodeTextWidth,
      _props$treeNodePlaceh = props.treeNodePlaceholder,
      treeNodePlaceholder = _props$treeNodePlaceh === void 0 ? 30 : _props$treeNodePlaceh,
      additionalSelectOptions = props.additionalSelectOptions,
      treeExpandedKeys = props.treeExpandedKeys,
      treeDefaultExpandAll = props.treeDefaultExpandAll,
      treeDefaultExpandedKeys = props.treeDefaultExpandedKeys,
      treeSwitcherIcon = props.treeSwitcherIcon,
      _props$treeAutoExpand = props.treeAutoExpandParent,
      treeAutoExpandParent = _props$treeAutoExpand === void 0 ? true : _props$treeAutoExpand,
      showSearch = props.showSearch,
      onClear = props.onClear,
      onSearch = props.onSearch,
      onDropdownVisibleChange = props.onDropdownVisibleChange,
      dropdownStyle = props.dropdownStyle,
      dropdownMatchSelectWidth = props.dropdownMatchSelectWidth,
      reset = _objectWithoutProperties(props, ["treeData", "value", "open", "treeSearchValue", "multiple", "treeCheckable", "onChange", "showTreeIcon", "fieldNames", "virtual", "listHeight", "onTreeExpand", "loadData", "dropdownRender", "nodeTextWidth", "treeNodePlaceholder", "additionalSelectOptions", "treeExpandedKeys", "treeDefaultExpandAll", "treeDefaultExpandedKeys", "treeSwitcherIcon", "treeAutoExpandParent", "showSearch", "onClear", "onSearch", "onDropdownVisibleChange", "dropdownStyle", "dropdownMatchSelectWidth"]);

  var _React$useState = React.useState(valuetoArray(outerValue)),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      value = _React$useState2[0],
      setValue = _React$useState2[1];

  var _React$useState3 = React.useState(outerSearchValue || ''),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      searchValue = _React$useState4[0],
      setSearchValue = _React$useState4[1];

  var _React$useState5 = React.useState(),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      dropdownWidth = _React$useState6[0],
      setDropdownWidth = _React$useState6[1]; // const [expandedKeys, setExpandedKeys] = React.useState<Key[]>(
  //   treeExpandedKeys || [],
  // );


  var _React$useState7 = React.useState(!!outerOpen),
      _React$useState8 = _slicedToArray(_React$useState7, 2),
      open = _React$useState8[0],
      setOpen = _React$useState8[1]; // const [autoExpandParent, setAutoExpandParent] = React.useState<boolean>(
  //   treeAutoExpandParent,
  // );


  var valueRef = React.useRef(outerValue);
  var treeRef = React.useRef(null);
  var selectRef = React.useRef(null); // 保存最深的层级

  var maxLevelRef = React.useRef(0);

  if (typeof outerValue !== 'undefined' && outerValue !== valueRef.current) {
    setValue(valuetoArray(outerValue));
  }

  if (typeof outerOpen !== 'undefined' && outerOpen !== open) {
    setOpen(outerOpen);
  }

  if (typeof outerSearchValue !== 'undefined' && outerSearchValue !== searchValue) {
    setSearchValue(outerSearchValue);
  } // if (
  //   typeof treeExpandedKeys !== 'undefined' &&
  //   treeExpandedKeys !== expandedKeys
  // ) {
  //   setExpandedKeys(treeExpandedKeys);
  // }


  valueRef.current = outerValue;

  var onValueChange = function onValueChange(val) {
    // 单选的情况，不能反选
    if (!multiple && !treeCheckable) {
      if (Array.isArray(val)) {
        if (typeof outerValue === 'undefined') {
          setValue(val.length === 0 ? value : valuetoArray(val));
        }

        onChange === null || onChange === void 0 ? void 0 : onChange(val.length === 0 ? value[0] : val[0]);
      }
    } else {
      if (typeof outerValue === 'undefined') {
        setValue(valuetoArray(val));
      }

      onChange === null || onChange === void 0 ? void 0 : onChange(val);
    }
  };

  var onTreeSelect = function onTreeSelect(selectKeys) {
    if (treeCheckable) return;

    if (!multiple) {
      setOpen(false);
    }

    onValueChange(selectKeys);
  };

  var onTreeCheck = function onTreeCheck(checkedKeys) {
    onValueChange(checkedKeys);
  }; // const onTreeExpand: TreeProps['onExpand'] = (eKeys, info) => {
  //   console.log('eKeys, info....', eKeys, info)
  //   if (typeof treeExpandedKeys === 'undefined') {
  //     setExpandedKeys(eKeys);
  //   }
  // if (typeof treeAutoExpandParent === 'undefined') {
  //   setAutoExpandParent(false);
  // }
  // outerOnTreeExpand?.(eKeys, info);
  // };
  // 当最深的层级变化时更新dropdown宽度
  // 给一个大概的计算，只要节点能看清楚即可


  var onLevelChange = function onLevelChange() {
    var _selectRef$current, _selectRef$current$se, _selectRef$current$se2, _selectRef$current$se3, _selectRef$current$se4;

    var currentLevel = maxLevelRef.current + 1;
    var selectContainerDomWdith = (_selectRef$current = selectRef.current) === null || _selectRef$current === void 0 ? void 0 : (_selectRef$current$se = _selectRef$current.selectRef) === null || _selectRef$current$se === void 0 ? void 0 : (_selectRef$current$se2 = _selectRef$current$se.current) === null || _selectRef$current$se2 === void 0 ? void 0 : (_selectRef$current$se3 = _selectRef$current$se2.containerRef) === null || _selectRef$current$se3 === void 0 ? void 0 : (_selectRef$current$se4 = _selectRef$current$se3.current) === null || _selectRef$current$se4 === void 0 ? void 0 : _selectRef$current$se4.offsetWidth; // 理论上应有宽度

    var shouldBeWidth = currentLevel * treeNodePlaceholder + nodeTextWidth;

    if (shouldBeWidth > selectContainerDomWdith) {
      // 降低优先级
      setTimeout(function () {
        setDropdownWidth(shouldBeWidth);
      });
    }
  };

  var onTreeExpand = function onTreeExpand(eKeys, info) {
    // 展开的节点层级太深时，层级深的节点会看不见
    // 由于虚拟列表的限制，针对此情况动态设置外部容器的宽度
    // 不考虑treeDefaultExpandAll的情况，这种情况下使用者自定义dropdownStyle即可
    if (!dropdownMatchSelectWidth && virtual && typeof listHeight !== 'undefined') {
      var _info$node$level = info.node.level,
          level = _info$node$level === void 0 ? 0 : _info$node$level;

      if (level > maxLevelRef.current) {
        maxLevelRef.current = level;
        onLevelChange();
      }
    }

    outerOnTreeExpand === null || outerOnTreeExpand === void 0 ? void 0 : outerOnTreeExpand(eKeys, info);
  };

  var onSelectDropdownVisibleChange = function onSelectDropdownVisibleChange(visible) {
    if (typeof outerOpen === 'undefined') {
      setOpen(visible);
    }

    if (visible === false) {
      setSearchValue('');
    }

    onDropdownVisibleChange === null || onDropdownVisibleChange === void 0 ? void 0 : onDropdownVisibleChange(visible);
  };

  var onDeselect = function onDeselect(tagValue) {
    onValueChange(value.filter(function (v) {
      return v !== tagValue;
    }));
  };

  var onSelectClear = function onSelectClear() {
    if (typeof outerValue === 'undefined') {
      setValue([]);
    }

    onChange === null || onChange === void 0 ? void 0 : onChange(multiple ? [] : undefined);
    onClear === null || onClear === void 0 ? void 0 : onClear();
  };

  var onSelectSearch = function onSelectSearch(searchVal) {
    var _treeRef$current;

    if (typeof outerSearchValue === 'undefined') {
      setSearchValue(searchVal);
    }

    (_treeRef$current = treeRef.current) === null || _treeRef$current === void 0 ? void 0 : _treeRef$current.onSearchChange(searchVal);
    onSearch === null || onSearch === void 0 ? void 0 : onSearch(searchVal);
  };

  var renderDropdownRender = function renderDropdownRender() {
    var treeDom = /*#__PURE__*/React.createElement(Tree, {
      ref: treeRef,
      searchValue: searchValue,
      treeData: treeData,
      fieldNames: {
        title: fieldNames.title,
        key: fieldNames.value,
        children: fieldNames.children
      },
      switcherIcon: treeSwitcherIcon,
      defaultExpandAll: treeDefaultExpandAll,
      defaultExpandedKeys: treeDefaultExpandedKeys,
      expandedKeys: treeExpandedKeys,
      // autoExpandParent={autoExpandParent}
      autoExpandParent: treeAutoExpandParent,
      // icon={treeIcon}
      showIcon: showTreeIcon,
      allLineClickable: true,
      virtual: virtual,
      height: listHeight,
      selectedKeys: !treeCheckable ? value : undefined,
      checkedKeys: treeCheckable ? value : undefined,
      multiple: multiple,
      checkable: treeCheckable,
      direction: "vertical",
      loadData: loadData,
      onSelect: onTreeSelect,
      onCheck: onTreeCheck,
      onExpand: onTreeExpand
    });

    if (dropdownRender) {
      return dropdownRender(treeDom);
    }

    return treeDom;
  };

  var selectOptions = React.useMemo(function () {
    // 给一个空数组，防止select认为无数据
    var selectOpts = [{
      value: '',
      title: ''
    }].concat(_toConsumableArray(additionalSelectOptions || []));

    if (Array.isArray(value)) {
      value.forEach(function (key) {
        traverse(treeData, function (option) {
          if (option.value === key) {
            selectOpts.push({
              title: option.title,
              value: option.value
            });
          }
        });
      });
    }

    return /*#__PURE__*/React.createElement(React.Fragment, null, selectOpts.map(function (opt) {
      return opt ? /*#__PURE__*/React.createElement(Select.Option, {
        key: opt.value,
        value: opt.value
      }, opt === null || opt === void 0 ? void 0 : opt.title) : null;
    }));
  }, [value, additionalSelectOptions]);

  var renderSelect = function renderSelect() {
    return /*#__PURE__*/React.createElement(Select, Object.assign({
      ref: selectRef,
      open: open,
      value: value,
      mode: multiple || treeCheckable ? 'multiple' : undefined,
      onClear: onSelectClear,
      onDeselect: onDeselect,
      onDropdownVisibleChange: onSelectDropdownVisibleChange,
      dropdownRender: renderDropdownRender,
      onSearch: onSelectSearch,
      showSearch: typeof showSearch !== 'undefined' ? showSearch : !!onSelectSearch,
      dropdownStyle: _objectSpread({
        width: dropdownWidth
      }, dropdownStyle),
      dropdownMatchSelectWidth: dropdownMatchSelectWidth,
      // select组件内部定义的onClick事件会导致 dropdown中的checkbox onChange事件失效
      // @ts-ignore
      onClick: function onClick() {}
    }, reset), selectOptions);
  };

  return /*#__PURE__*/React.createElement(React.Fragment, null, renderSelect());
};

var TreeSelect = /*#__PURE__*/React.forwardRef(TreeSelectRenderFunction);
TreeSelect.defaultProps = {
  virtual: true,
  multiple: false,
  treeCheckable: false,
  treeAutoExpandParent: true,
  dropdownMatchSelectWidth: true
};
TreeSelect.displayName = 'TreeSelect';
export default TreeSelect;