"use strict";

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));

var _react = _interopRequireWildcard(require("react"));

var _arrayTreeFilter = _interopRequireDefault(require("array-tree-filter"));

var _classnames = _interopRequireDefault(require("classnames"));

var _mutipleDropdownNode = _interopRequireDefault(require("./mutiple-dropdown-node"));

var _select = _interopRequireDefault(require("../select"));

var _rcCascader = _interopRequireDefault(require("../components/rc-cascader"));

var _KeyCode = _interopRequireDefault(require("../components/rc-util/KeyCode"));

var _context = require("../config-provider/context");

var _input = _interopRequireDefault(require("../input"));

var _components = require("../components");

var _ReactNodeValidate = require("../utils/ReactNodeValidate");

var _scrollInfinite = require("../select/scrollInfinite");

var _util = require("./_util");

var _loadingBasicGray = _interopRequireDefault(require("../spin/gif/loading-basic-gray.gif"));

// @ts-ignore
var DownLine = _components.Icons.DownLine,
    RightLine = _components.Icons.RightLine,
    CloseFill = _components.Icons.CloseFill;

function getFieldNames(_ref) {
  var fieldNames = _ref.fieldNames;
  return fieldNames;
}

function getFilledFieldNames(props) {
  var fieldNames = getFieldNames(props) || {};
  var names = {
    children: fieldNames.children || 'children',
    label: fieldNames.label || 'label',
    value: fieldNames.value || 'value'
  };
  return names;
}

function highlightKeyword(str, keyword, prefixCls) {
  return str.split(keyword).map(function (node, index) {
    return index === 0 ? node : [/*#__PURE__*/_react.default.createElement("span", {
      className: "".concat(prefixCls, "-menu-item-keyword"),
      key: "seperator"
    }, keyword), node];
  });
} // 搜索时 拍平树


function flattenTree(options, props) {
  var ancestor = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  var names = getFilledFieldNames(props);
  var flattenOptions = [];
  var childrenName = names.children;
  options.forEach(function (option) {
    var path = ancestor.concat(option);

    if (props.changeOnSelect || !option[childrenName] || !option[childrenName].length) {
      flattenOptions.push(path);
    }

    if (option[childrenName]) {
      flattenOptions = flattenOptions.concat(flattenTree(option[childrenName], props, path));
    }
  });
  return flattenOptions;
}

var Cascader = function Cascader(props) {
  var _classNames, _classNames3;

  var onChange = props.onChange,
      placeholder = props.placeholder,
      className = props.className,
      disabled = props.disabled,
      autoFocus = props.autoFocus,
      suffixIcon = props.suffixIcon,
      defaultValue = props.defaultValue,
      pickerTitle = props.pickerTitle,
      showPickerTitle = props.showPickerTitle,
      _props$popupVisible = props.popupVisible,
      popupVisible = _props$popupVisible === void 0 ? false : _props$popupVisible,
      multiple = props.multiple,
      collapse = props.collapse,
      dropdownMenuColumnWidth = props.dropdownMenuColumnWidth,
      dropdownMenuColumnStyle = props.dropdownMenuColumnStyle,
      onPopupVisibleChange = props.onPopupVisibleChange,
      getPopupContainer = props.getPopupContainer,
      showSearch = props.showSearch,
      _props$readOnly = props.readOnly,
      readOnly = _props$readOnly === void 0 ? true : _props$readOnly,
      outerInputValue = props.inputValue,
      size = props.size,
      dropdownRender = props.dropdownRender,
      dropdownFooterContent = props.dropdownFooterContent,
      style = props.style,
      allowClear = props.allowClear,
      onPopupScroll = props.onPopupScroll,
      scrollInfinite = props.scrollInfinite,
      infiniteHasMore = props.infiniteHasMore,
      loadData = props.loadData,
      tagRender = props.tagRender,
      _props$maxTagCount = props.maxTagCount,
      maxTagCount = _props$maxTagCount === void 0 ? 1 : _props$maxTagCount,
      maxTagTextLength = props.maxTagTextLength,
      onInputChange = props.onInputChange,
      restProps = (0, _objectWithoutProperties2.default)(props, ["onChange", "placeholder", "className", "disabled", "autoFocus", "suffixIcon", "defaultValue", "pickerTitle", "showPickerTitle", "popupVisible", "multiple", "collapse", "dropdownMenuColumnWidth", "dropdownMenuColumnStyle", "onPopupVisibleChange", "getPopupContainer", "showSearch", "readOnly", "inputValue", "size", "dropdownRender", "dropdownFooterContent", "style", "allowClear", "onPopupScroll", "scrollInfinite", "infiniteHasMore", "loadData", "tagRender", "maxTagCount", "maxTagTextLength", "onInputChange"]);

  var _React$useContext = _react.default.useContext(_context.ConfigContext),
      contextSize = _React$useContext.size,
      getPrefixClassName = _React$useContext.getPrefixClassName,
      getCtxPopupContainer = _React$useContext.getPopupContainer;

  var endSize = size || contextSize;
  var prefixCls = getPrefixClassName('cascader'); // const rcCascaderPrefixCls = classNames(prefixCls, {
  //   [`${prefixCls}-size`]: size
  // })
  // console.log('rcCascaderPrefixCls..', rcCascaderPrefixCls)

  var _useState = (0, _react.useState)(outerInputValue),
      _useState2 = (0, _slicedToArray2.default)(_useState, 2),
      inputValue = _useState2[0],
      setInputValue = _useState2[1];

  var _useState3 = (0, _react.useState)(props.value || props.defaultValue),
      _useState4 = (0, _slicedToArray2.default)(_useState3, 2),
      value = _useState4[0],
      setRcVal = _useState4[1];

  var _useState5 = (0, _react.useState)(popupVisible),
      _useState6 = (0, _slicedToArray2.default)(_useState5, 2),
      selectVisible = _useState6[0],
      setSelectVisible = _useState6[1];

  var _useState7 = (0, _react.useState)(false),
      _useState8 = (0, _slicedToArray2.default)(_useState7, 2),
      inputFocused = _useState8[0],
      setInputFocused = _useState8[1];

  var inputRef = (0, _react.useRef)(null); // const mutipleTreeValsRef = useRef(value);

  var clearSelectionTimeout;

  if ('value' in props && props.value !== value) {
    setRcVal(props.value); // mutipleTreeValsRef.current = props.value;
  }

  if ('inputValue' in props && outerInputValue !== inputValue) {
    setInputValue(outerInputValue); // mutipleTreeValsRef.current = props.value;
  }

  if ('popupVisible' in props && props.popupVisible !== selectVisible) {
    setSelectVisible(!!props.popupVisible);
  }

  _react.default.useEffect(function () {
    return function () {
      if (clearSelectionTimeout) {
        clearTimeout(clearSelectionTimeout);
      }
    };
  }, []); // 搜索数据


  var flattenOptions = showSearch ? flattenTree(props.options, props) : undefined;
  var pickerCls = (0, _classnames.default)("".concat(prefixCls, "-picker"), (_classNames = {}, (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-picker-with-value"), inputValue), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-picker-disabled"), disabled), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-picker-show-search"), !!showSearch), (0, _defineProperty2.default)(_classNames, "".concat(prefixCls, "-picker-focused"), inputFocused), _classNames), className);

  var renderEmpty = function renderEmpty() {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-no-data")
    }, "\u6682\u65E0\u6570\u636E");
  }; // keep value when filtering


  var keepFilteredValueField = '__KEEP_FILTERED_OPTION_VALUE'; // 搜索的方法 数据处理；

  function defaultFilterOption(val, path, arr) {
    return path.some(function (option) {
      return option[arr.label].indexOf(val) > -1;
    });
  }

  function defaultRenderFilteredOption(val, path, prefixClss, arr) {
    return path.map(function (option, index) {
      var label = option[arr.label];
      var node = label.indexOf(inputValue) > -1 ? highlightKeyword(label, val, prefixClss) : label;
      return index === 0 ? node : [' / ', node];
    });
  }

  function getEmptyNode(renderEmptys, arr, notFoundContent) {
    var _ref2;

    return _ref2 = {}, (0, _defineProperty2.default)(_ref2, arr.value, 'NOT_FOUND'), (0, _defineProperty2.default)(_ref2, arr.label, notFoundContent || renderEmptys('Cascader')), (0, _defineProperty2.default)(_ref2, "disabled", true), (0, _defineProperty2.default)(_ref2, "isEmptyNode", true), _ref2;
  }

  function defaultSortFilteredOption(a, b, val, arr) {
    function callback(elem) {
      return elem[arr.label].indexOf(val) > -1;
    }

    return a.findIndex(callback) - b.findIndex(callback);
  } // We limit the filtered item count by default


  var defaultLimit = 50; // 过滤数据

  var generateFilteredOptions = function generateFilteredOptions(prefixClss, renderEmptys) {
    var notFoundContent = props.notFoundContent;
    var arr = getFilledFieldNames(props);
    var _showSearch$filter = showSearch.filter,
        filter = _showSearch$filter === void 0 ? defaultFilterOption : _showSearch$filter,
        _showSearch$render = showSearch.render,
        render = _showSearch$render === void 0 ? defaultRenderFilteredOption : _showSearch$render,
        _showSearch$sort = showSearch.sort,
        sort = _showSearch$sort === void 0 ? defaultSortFilteredOption : _showSearch$sort,
        _showSearch$limit = showSearch.limit,
        limit = _showSearch$limit === void 0 ? defaultLimit : _showSearch$limit; // Limit the filter if needed

    var filtered;

    if (limit > 0) {
      filtered = [];
      var matchCount = 0; // Perf optimization to filter items only below the limit

      flattenOptions.some(function (path) {
        var match = filter(inputValue, path, arr);

        if (match) {
          filtered.push(path);
          matchCount += 1;
        }

        return matchCount >= limit;
      });
    } else {
      filtered = flattenOptions.filter(function (path) {
        return filter(inputValue, path, arr);
      });
    }

    filtered = filtered.sort(function (a, b) {
      return sort(a, b, inputValue, arr);
    });

    if (filtered.length > 0) {
      var field = arr.value === arr.label ? keepFilteredValueField : arr.value;
      return filtered.map(function (path) {
        var _ref3;

        return _ref3 = {
          klein__IS_FILTERED_OPTION: true,
          path: path
        }, (0, _defineProperty2.default)(_ref3, field, path.map(function (o) {
          return o[arr.value];
        })), (0, _defineProperty2.default)(_ref3, arr.label, render(inputValue, path, prefixClss, arr)), (0, _defineProperty2.default)(_ref3, "disabled", path.some(function (o) {
          return !!o.disabled;
        })), (0, _defineProperty2.default)(_ref3, "isEmptyNode", true), (0, _defineProperty2.default)(_ref3, "checked", props.hasChecked), _ref3;
      });
    }

    return [getEmptyNode(renderEmptys, arr, notFoundContent)];
  };

  var handlePopupVisibleChange = function handlePopupVisibleChange(flag) {
    if (!('popupVisible' in props)) {
      setSelectVisible(flag);
      setInputFocused(flag);
      setInputValue(function (pre) {
        return pre;
      });
    }

    onPopupVisibleChange === null || onPopupVisibleChange === void 0 ? void 0 : onPopupVisibleChange(flag);
  }; // 搜索 过滤数据


  var handleInputChange = function handleInputChange(e) {
    if (!popupVisible) {
      handlePopupVisibleChange(true);
    }

    setInputVal(e.target.value);
  }; // 清除选中值


  var clearSelection = function clearSelection(e) {
    e.preventDefault();
    e.stopPropagation();

    if (!inputValue) {
      handlePopupVisibleChange(false);
      clearSelectionTimeout = setTimeout(function () {
        setValue([]);
      }, 200);
    } else {
      setInputVal('');
    }
  }; // render clear icon


  var renderClearIcon = ((value === null || value === void 0 ? void 0 : value.length) > 0 || (inputValue === null || inputValue === void 0 ? void 0 : inputValue.length) > 0) && allowClear ? /*#__PURE__*/_react.default.createElement(CloseFill, {
    className: "".concat(prefixCls, "-picker-clear"),
    onClick: clearSelection
  }) : null;
  var options = props.options;
  var arrPd = getFilledFieldNames(props);

  if (options && options.length > 0) {
    // console.log(options, '----options'); // szp
    if (inputValue && showSearch) {
      options = generateFilteredOptions(prefixCls, renderEmpty);
    }
  } else {
    options = [getEmptyNode(renderEmpty, arrPd, props.notFoundContent)];
  }

  var handleInputBlur = function handleInputBlur() {
    setInputFocused(false);
  };

  var handleInputClick = function handleInputClick(e) {
    // Prevent `Trigger` behaviour.
    if (inputFocused || popupVisible) {
      e.stopPropagation();
    }
  }; // 阻止回退键的删除事件 在showSearch 属性


  var handleKeyDown = function handleKeyDown(e) {
    if (e.keyCode === _KeyCode.default.BACKSPACE || e.keyCode === _KeyCode.default.SPACE) {
      e.stopPropagation();
    }
  };

  var setValue = function setValue(arrVal) {
    var selectedOptions = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

    if (!('value' in props)) {
      setRcVal(arrVal);
    } // if (mutipleValues) {
    //   onChange?.(mutipleValues);
    //   return;
    // }


    onChange === null || onChange === void 0 ? void 0 : onChange(arrVal, selectedOptions);
  };

  var setInputVal = function setInputVal(val) {
    if (typeof outerInputValue === 'undefined') {
      setInputValue(val);
    }

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

  var handleChange = function handleChange(values, selectedOptions) {
    setInputValue(''); // 搜索过滤的时候

    if (selectedOptions[0].klein__IS_FILTERED_OPTION) {
      var unwrappedValue = selectedOptions[0][keepFilteredValueField] === undefined ? values[0] : selectedOptions[0][keepFilteredValueField];
      var unwrappedSelectedOptions = selectedOptions[0].path;
      setValue(unwrappedValue, unwrappedSelectedOptions);
      return;
    }

    setValue(values, selectedOptions);
  };

  var defaultDisplayRender = function defaultDisplayRender(label) {
    return label.join(' / ');
  };

  var getLabel = function getLabel() {
    var _props$displayRender = props.displayRender,
        displayRender = _props$displayRender === void 0 ? defaultDisplayRender : _props$displayRender;

    if (value) {
      // 未选择的时候 可能是undefined
      var arrs = getFilledFieldNames(props);
      var unwrappedValue = Array.isArray(value[0]) ? value[0] : value;
      var selectedOptions = (0, _arrayTreeFilter.default)(props.options, function (o, level) {
        return o[arrs.value] === unwrappedValue[level];
      }, {
        childrenKeyName: arrs.children
      }); // debugger

      var label = selectedOptions.length ? selectedOptions.map(function (o) {
        return o[arrs.label];
      }) : value;
      return displayRender(label, selectedOptions);
    }

    return null;
  };

  var rcCascaderPopupClassName = (0, _classnames.default)((0, _defineProperty2.default)({}, "".concat(prefixCls, "-menu-empty"), options.length === 1 && options[0].value === 'NOT_FOUND')); // 输入框后面的图标

  var arrowCls = (0, _classnames.default)((_classNames3 = {}, (0, _defineProperty2.default)(_classNames3, "".concat(prefixCls, "-picker-arrow"), true), (0, _defineProperty2.default)(_classNames3, "".concat(prefixCls, "-picker-arrow-expand"), popupVisible), _classNames3));
  var pickerLabelCls = (0, _classnames.default)("".concat(prefixCls, "-picker-label"), (0, _defineProperty2.default)({}, "".concat(prefixCls, "-picker-").concat(endSize), endSize)); // 获取到输入框中的icon

  var getInputIcon = function getInputIcon() {
    return suffixIcon ? (0, _ReactNodeValidate.replaceElement)(suffixIcon, /*#__PURE__*/_react.default.createElement("span", {
      className: "".concat(prefixCls, "-picker-arrow")
    }, suffixIcon), function () {
      var _classNames5;

      return {
        className: (0, _classnames.default)((_classNames5 = {}, (0, _defineProperty2.default)(_classNames5, suffixIcon.props.className, suffixIcon.props.className), (0, _defineProperty2.default)(_classNames5, "".concat(prefixCls, "-picker-arrow"), true), _classNames5))
      };
    }) : /*#__PURE__*/_react.default.createElement(DownLine, {
      className: arrowCls
    });
  };

  var renderElement = props.children || /*#__PURE__*/_react.default.createElement("span", {
    className: pickerCls,
    style: style,
    title: showPickerTitle ? pickerTitle || getLabel() : undefined
  }, (value === null || value === void 0 ? void 0 : value.length) > 0 ? /*#__PURE__*/_react.default.createElement("span", {
    className: pickerLabelCls
  }, getLabel()) : null, /*#__PURE__*/_react.default.createElement(_input.default, {
    ref: inputRef,
    tabIndex: -1,
    placeholder: value && value.length > 0 ? undefined : placeholder,
    className: "".concat(prefixCls, "-input"),
    disabled: disabled,
    value: inputValue,
    readOnly: (0, _util.isReadOnly)(showSearch, readOnly),
    onChange: !(0, _util.isReadOnly)(showSearch, readOnly) ? handleInputChange : undefined,
    onClick: !(0, _util.isReadOnly)(showSearch, readOnly) ? handleInputClick : undefined,
    onKeyDown: handleKeyDown,
    onBlur: !(0, _util.isReadOnly)(showSearch, readOnly) ? handleInputBlur : undefined,
    size: endSize
  }), renderClearIcon, getInputIcon());
  /** ------ 级联多选 ------ */


  var onItemRemove = function onItemRemove(curVal) {
    var result = value.filter(function (keys) {
      return keys.join('/') !== curVal;
    });
    setValue(result);
  };

  var renderMutipleSelect = function renderMutipleSelect() {
    var fields = getFilledFieldNames(props);

    var _getSelectOpts = (0, _util.getSelectOpts)(fields, value, props.options),
        _getSelectOpts2 = (0, _slicedToArray2.default)(_getSelectOpts, 2),
        selectOpts = _getSelectOpts2[0],
        selectVals = _getSelectOpts2[1];

    var selectProps = {
      placeholder: '请选择' || placeholder,
      mode: 'multiple',
      dropdownRender: function dropdownRender(menu) {
        return null;
      },
      dropdownStyle: {
        padding: 0
      },
      value: selectVals,
      onDeselect: onItemRemove,
      tagRender: tagRender,
      maxTagCount: maxTagCount,
      maxTagTextLength: maxTagTextLength,
      showSearch: false,
      showArrow: true,
      suffixIcon: suffixIcon
    };

    if (typeof collapse === 'boolean') {
      selectProps.maxTagCount = maxTagCount;
    } else {
      selectProps.maxTagCount = collapse;
    }

    return /*#__PURE__*/_react.default.createElement(_select.default, Object.assign({}, selectProps, {
      style: style,
      className: className
    }), selectOpts.map(function (item) {
      return /*#__PURE__*/_react.default.createElement(_select.default.Option, {
        key: item.value,
        value: item.value
      }, item.label);
    }));
  };

  var onTreeCheck = function onTreeCheck(keys, info) {
    setValue(info.checkedChildrenKeys, []); // mutipleTreeValsRef.current = keys as CascaderValueType[];
  };

  var onTreeSelect = function onTreeSelect(keys, info, checkedKeys) {
    // 如果是多选 + 数据按需加载的情况下
    if (multiple && loadData) {
      setValue(checkedKeys, []);
    }
  };

  var defaultDropdownRender = function defaultDropdownRender(menus) {
    var _options;

    return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, multiple && ((_options = options) === null || _options === void 0 ? void 0 : _options.filter(function (item) {
      return !item.isEmptyNode;
    }).length) ? /*#__PURE__*/_react.default.createElement(_mutipleDropdownNode.default, {
      treeData: options,
      onCheck: onTreeCheck,
      onSelect: onTreeSelect,
      checkedKeys: value,
      loadData: loadData,
      columnWidth: dropdownMenuColumnWidth,
      columnStyle: dropdownMenuColumnStyle,
      fieldNames: getFilledFieldNames(props)
    }) : menus, dropdownFooterContent && /*#__PURE__*/_react.default.createElement("div", {
      className: "".concat(prefixCls, "-footer")
    }, dropdownFooterContent));
  };
  /** ------ 级联多选 ------ */


  var loadingIcon = /*#__PURE__*/_react.default.createElement("span", {
    className: "".concat(prefixCls, "-menu-item-loading-icon")
  }, /*#__PURE__*/_react.default.createElement("img", {
    src: _loadingBasicGray.default,
    style: {
      width: 16,
      marginTop: 3
    },
    alt: "\u52A0\u8F7D\u4E2D\u3002\u3002\u3002\u3002"
  })); // fetch options by scroll infinite


  var handleScroll = (0, _react.useCallback)((0, _scrollInfinite.scrollInfiniteFun)(infiniteHasMore, scrollInfinite, onPopupScroll), [infiniteHasMore, scrollInfinite, onPopupScroll]);
  return /*#__PURE__*/_react.default.createElement(_rcCascader.default, Object.assign({}, restProps, {
    getPopupContainer: getPopupContainer || getCtxPopupContainer,
    prefixCls: prefixCls,
    options: options,
    value: value,
    dropdownMenuColumnStyle: (0, _objectSpread2.default)({
      width: dropdownMenuColumnWidth
    }, dropdownMenuColumnStyle),
    popupClassName: rcCascaderPopupClassName,
    popupVisible: selectVisible,
    onPopupVisibleChange: handlePopupVisibleChange,
    onChange: handleChange,
    expandIcon: /*#__PURE__*/_react.default.createElement(RightLine, null),
    loadingIcon: loadingIcon,
    disabled: disabled,
    dropdownRender: dropdownRender || defaultDropdownRender,
    onPopupScroll: handleScroll,
    loadData: loadData
  }), !multiple ? renderElement : renderMutipleSelect());
};

Cascader.defaultProps = {
  // size: 'medium',
  disabled: false,
  allowClear: true,
  infiniteHasMore: true
};
var _default = Cascader;
exports.default = _default;