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 = ["treeData", "rootName", "rootKey", "emptyDescription", "searchOptionName", "defaultSelectedKeys", "nodeExtra", "selectable", "nodeControl", "limitKey", "checkedKeys", "checkStrictly", "onSelect", "onCheck", "titleRender", "disabledFields", "showSearch", "searchText", "searchConfig", "searchTrigger", "searchAuto", "searchExtra", "children", "footer", "wrapperStyle", "wrapperClassname", "fullHeight"];
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 _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 _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 _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; }
// 重构树控件，可直接配置数据
import React, { useMemo, useState, useCallback, useContext, useImperativeHandle, useRef, useEffect } from 'react';
import { Tree, Empty, Popconfirm, Input, Button } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import SpecIcon from "../SpecIcon/index";
import { transDataParam, resetDataWithLimit, resetDataWithDisabled, selectAllExcludingDisabled } from "./util";
import { filterTreeNodes, getLastLeafParentNodes } from "../utils/index";
var Search = Input.Search;
import { useLanguageObject } from "../hooks/use-language";
import useStyle from "./style";
import { FanContext } from "../ConfigContext";
import classNames from 'classnames';

// @ts-ignore

// @ts-ignore
var RefactorTree = /*#__PURE__*/React.forwardRef(function (props, ref) {
  var componentName = 'spec-standard-refactor-tree';
  var _useStyle = useStyle(componentName),
    _useStyle2 = _slicedToArray(_useStyle, 2),
    wrapSSR = _useStyle2[0],
    hashId = _useStyle2[1];
  var lang = useLanguageObject(); // 当前使用的语言包
  var InitFanContext = useContext(FanContext);
  var providerConfig = InitFanContext['RefactorTree'] || {}; // 使用上下文（全局配置）设置扩展的配置项
  var ConcatTreeProps = _objectSpread(_objectSpread({}, providerConfig), props);
  var treeData = ConcatTreeProps.treeData,
    rootName = ConcatTreeProps.rootName,
    rootKey = ConcatTreeProps.rootKey,
    emptyDescription = ConcatTreeProps.emptyDescription,
    searchOptionName = ConcatTreeProps.searchOptionName,
    defaultSelectedKeys = ConcatTreeProps.defaultSelectedKeys,
    nodeExtra = ConcatTreeProps.nodeExtra,
    _ConcatTreeProps$sele = ConcatTreeProps.selectable,
    selectable = _ConcatTreeProps$sele === void 0 ? true : _ConcatTreeProps$sele,
    nodeControl = ConcatTreeProps.nodeControl,
    limitKey = ConcatTreeProps.limitKey,
    checkedKeys = ConcatTreeProps.checkedKeys,
    checkStrictly = ConcatTreeProps.checkStrictly,
    onSelect = ConcatTreeProps.onSelect,
    onCheck = ConcatTreeProps.onCheck,
    titleRender = ConcatTreeProps.titleRender,
    disabledFields = ConcatTreeProps.disabledFields,
    _ConcatTreeProps$show = ConcatTreeProps.showSearch,
    showSearch = _ConcatTreeProps$show === void 0 ? false : _ConcatTreeProps$show,
    searchText = ConcatTreeProps.searchText,
    searchConfig = ConcatTreeProps.searchConfig,
    _ConcatTreeProps$sear = ConcatTreeProps.searchTrigger,
    searchTrigger = _ConcatTreeProps$sear === void 0 ? 'search' : _ConcatTreeProps$sear,
    _ConcatTreeProps$sear2 = ConcatTreeProps.searchAuto,
    searchAuto = _ConcatTreeProps$sear2 === void 0 ? true : _ConcatTreeProps$sear2,
    searchExtra = ConcatTreeProps.searchExtra,
    children = ConcatTreeProps.children,
    footer = ConcatTreeProps.footer,
    wrapperStyle = ConcatTreeProps.wrapperStyle,
    wrapperClassname = ConcatTreeProps.wrapperClassname,
    fullHeight = ConcatTreeProps.fullHeight,
    otherProps = _objectWithoutProperties(ConcatTreeProps, _excluded);
  // const { title, value, children, disabled } = { value: 'value', title: 'title', children: 'children', disabled: 'disabled', ...optionName }

  var searchInputRef = useRef();
  var _useState = useState(''),
    _useState2 = _slicedToArray(_useState, 2),
    searchReactorValue = _useState2[0],
    setSearchReactorValue = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    searchInputValue = _useState4[0],
    setSearchInputValue = _useState4[1]; // 搜索触发输入框的值
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    refactorExpandedKeys = _useState6[0],
    setRefactorExpandedKeys = _useState6[1];
  var optionName = useMemo(function () {
    return _objectSpread(_objectSpread(_objectSpread({}, {
      value: 'value',
      title: 'title',
      children: 'children',
      disabled: 'disabled'
    }), (otherProps === null || otherProps === void 0 ? void 0 : otherProps.optionName) || {}), (otherProps === null || otherProps === void 0 ? void 0 : otherProps.fieldNames) || {});
  }, [otherProps === null || otherProps === void 0 ? void 0 : otherProps.optionName, otherProps === null || otherProps === void 0 ? void 0 : otherProps.fieldNames]);

  // 重新组合指定数据源字段
  var transTreeData = useMemo(function () {
    var afterTransData = transDataParam(treeData, optionName); // 通过转换后的数据
    var resultData;
    // 如果有配置根节点,则添加 一个根节点数据
    resultData = rootName ? [_defineProperty(_defineProperty(_defineProperty(_defineProperty({}, optionName.title || 'title', rootName), optionName.value || 'value', rootKey || '0'), optionName.key || 'key', rootKey || '0'), optionName.children || 'children', afterTransData)] : afterTransData;
    // 有配置limitKey指定限制同级节点时，添加判断节点选择限制(在父子节点不相关联条件下使用checkStrictly=true)
    if (checkStrictly && limitKey && checkedKeys) {
      if (Array.isArray(checkedKeys) && checkedKeys.length > 0 || checkedKeys && Array.isArray(checkedKeys.checked) && checkedKeys.checked.length > 0) {
        resultData = resetDataWithLimit(Array.isArray(checkedKeys) ? checkedKeys : checkedKeys.checked, resultData, optionName, limitKey);
      }
    }
    if (disabledFields && Array.isArray(disabledFields)) {
      resultData = resetDataWithDisabled(resultData, optionName, disabledFields);
    }
    return filterTreeNodes(resultData, searchReactorValue, searchOptionName || {
      childrenParam: optionName['children'],
      keyParam: optionName['title']
    });
  }, [treeData, optionName, checkStrictly, limitKey, checkedKeys, disabledFields, searchReactorValue, searchOptionName, optionName]);
  //
  var selectAllData = useMemo(function () {
    return selectAllExcludingDisabled(transTreeData, optionName, false);
  }, [transTreeData, optionName]);
  // 动态更新配置expandedKeys
  useEffect(function () {
    if (searchReactorValue) {
      var _getLastLeafParentNod = getLastLeafParentNodes(transTreeData, {
          childrenParam: optionName['children'],
          keyParam: optionName['value']
        }),
        leafParentKeys = _getLastLeafParentNod.leafParentKeys;
      setRefactorExpandedKeys(leafParentKeys);
    }
  }, [transTreeData, searchReactorValue, optionName]);

  // 动态扩展配置项：动态更新配置expandedKeys及autoExpandParent的节点，使得匹配到可默认展开对应的上层节点
  var refactorDynamicProps = useMemo(function () {
    if (searchReactorValue) {
      return {
        expandedKeys: refactorExpandedKeys,
        // (leafParentKeys || []).concat(leafNodes.map(item => item[optionName['value']])),
        autoExpandParent: true,
        onExpand: function onExpand(keys) {
          setRefactorExpandedKeys(keys);
        }
      };
    } else {
      return {};
    }
  }, [searchReactorValue, refactorExpandedKeys]);
  useImperativeHandle(ref, function () {
    return {
      selectAllData: selectAllData,
      transTreeData: transTreeData,
      clearSearchKey: function clearSearchKey() {
        if (searchTrigger === 'search' || !searchAuto && searchConfig.hasOwnProperty('onSearch')) {
          // 清空搜索
          onRefactorSearch('');
          if (!searchAuto && searchConfig.hasOwnProperty('onSearch')) {
            setSearchInputValue('');
          }
        }
        if (searchTrigger === 'change' || !searchAuto && searchConfig.hasOwnProperty('onChange')) {
          // 清空搜索
          onRefactorChange({
            target: {
              value: ''
            }
          });
        }
      }
    };
  }, [transTreeData]);
  var onRefactorChange = useCallback(function (eOrValue) {
    if (!searchAuto || searchTrigger === 'search') {
      var _searchConfig$onChang;
      setSearchInputValue(eOrValue === null || eOrValue === void 0 ? void 0 : eOrValue.target.value);
      searchConfig === null || searchConfig === void 0 || (_searchConfig$onChang = searchConfig.onChange) === null || _searchConfig$onChang === void 0 || _searchConfig$onChang.call(searchConfig, eOrValue);
      return;
    }
    if (searchTrigger === 'change') {
      var _searchConfig$onChang2;
      searchConfig === null || searchConfig === void 0 || (_searchConfig$onChang2 = searchConfig.onChange) === null || _searchConfig$onChang2 === void 0 || _searchConfig$onChang2.call(searchConfig, eOrValue);
      setSearchReactorValue(eOrValue === null || eOrValue === void 0 ? void 0 : eOrValue.target.value);
      return;
    }
  }, [searchTrigger, searchConfig]);
  var onRefactorSearch = useCallback(function (eOrValue, event, extraVa) {
    if (!searchAuto || searchTrigger === 'change') {
      var _searchConfig$onSearc;
      searchConfig === null || searchConfig === void 0 || (_searchConfig$onSearc = searchConfig.onSearch) === null || _searchConfig$onSearc === void 0 || _searchConfig$onSearc.call(searchConfig, eOrValue, event, extraVa);
      return;
    }
    if (searchTrigger === 'search') {
      var _searchConfig$onSearc2;
      searchConfig === null || searchConfig === void 0 || (_searchConfig$onSearc2 = searchConfig.onSearch) === null || _searchConfig$onSearc2 === void 0 || _searchConfig$onSearc2.call(searchConfig, eOrValue, event, extraVa);
      setSearchInputValue(eOrValue);
      setSearchReactorValue(eOrValue);
      return;
    }
  }, [searchTrigger, searchConfig, searchAuto]);
  // 全选
  // const selectAll = (action?: string) => {
  //   const selectResult = selectAllExcludingDisabled(transTreeData, optionName, false)
  //   otherProps?.onSelectAll?.(action === 'clear' ? [] : selectResult.keys, selectResult)
  // }

  var handleToSelectTreeNode = function handleToSelectTreeNode(key, e) {
    var currentData = e.node;
    var multiSelectedData = [];
    e.selectedNodes.map(function (item) {
      return multiSelectedData.push(item);
    }); // 多选条件下,当前选中所有节点数据
    onSelect && onSelect(key, _objectSpread({
      currentData: currentData,
      multiData: multiSelectedData
    }, e), e);
  };
  var handleToCheckTreeNode = function handleToCheckTreeNode(keys, e) {
    var currentData = e.node;
    var multiCheckedData = [];
    e.checkedNodes.map(function (item) {
      return multiCheckedData.push(item);
    }); // 多选条件下,当前选中所有节点数据
    onCheck && onCheck(keys, {
      currentData: currentData,
      multiData: multiCheckedData
    }, e);
  };
  var handleNodeControl = function handleNodeControl(e, type, nodeData) {
    e.stopPropagation();
    var onEdit = nodeControl.onEdit,
      onDelete = nodeControl.onDelete;
    if (type === 'edit') {
      onEdit && onEdit(nodeData);
    }
    if (type === 'delete') {
      onDelete && onDelete(nodeData);
    }
  };
  var renderNodeTitle = function renderNodeTitle(item) {
    if (titleRender) return titleRender(item);
    return /*#__PURE__*/React.createElement(React.Fragment, null, item[optionName.title || 'title'], nodeControl ? /*#__PURE__*/React.createElement("span", {
      className: "treeControl"
    }, /*#__PURE__*/React.createElement("a", {
      onClick: function onClick(e) {
        handleNodeControl(e, 'edit', item);
      }
    }, /*#__PURE__*/React.createElement(SpecIcon, {
      name: 'edit'
    })), /*#__PURE__*/React.createElement(Popconfirm, {
      placement: 'top',
      title: "".concat((lang === null || lang === void 0 ? void 0 : lang['global.delete.confirm']) || '确定要删除', "\uFF1A").concat(item[optionName.title || 'title'], "\uFF1F"),
      icon: /*#__PURE__*/React.createElement(SpecIcon, {
        name: "question"
      }),
      onConfirm: function onConfirm(e) {
        handleNodeControl(e, 'delete', item);
      }
    }, /*#__PURE__*/React.createElement("a", {
      onClick: function onClick(e) {
        return e.stopPropagation();
      }
    }, /*#__PURE__*/React.createElement(SpecIcon, {
      name: 'delete'
    })))) : null, nodeExtra && nodeExtra(item));
  };
  var RenderTree = function RenderTree() {
    if (transTreeData.length == 0) {
      return /*#__PURE__*/React.createElement(Empty, {
        image: Empty.PRESENTED_IMAGE_SIMPLE,
        description: emptyDescription
      });
    } else {
      var defExpand = [];
      if (defaultSelectedKeys && defaultSelectedKeys.length > 0) {
        defExpand = defaultSelectedKeys;
      } else {
        defExpand = rootKey ? [rootKey] : ['0'];
      }
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Tree, _extends({}, otherProps, refactorDynamicProps, {
        onSelect: function onSelect(keys, e) {
          return handleToSelectTreeNode(keys, e);
        },
        onCheck: function onCheck(keys, e) {
          return handleToCheckTreeNode(keys, e);
        },
        defaultExpandedKeys: defExpand,
        defaultSelectedKeys: defaultSelectedKeys,
        selectable: selectable,
        checkedKeys: checkedKeys,
        checkStrictly: checkStrictly,
        treeData: transTreeData,
        titleRender: renderNodeTitle,
        fieldNames: optionName
      })));
    }
  };
  return wrapSSR( /*#__PURE__*/React.createElement("div", {
    className: classNames(componentName, wrapperClassname, fullHeight ? 'spec-standard-refactor-tree-fullheight' : '', hashId),
    style: wrapperStyle
  }, children, showSearch && /*#__PURE__*/React.createElement("div", {
    className: 'spec-standard-refactor-tree-searchbar'
  }, /*#__PURE__*/React.createElement(Search, _extends({
    allowClear: true,
    ref: searchInputRef,
    enterButton: !searchAuto && searchConfig.hasOwnProperty('onSearch') || searchTrigger === "search" ? /*#__PURE__*/React.createElement(Button, {
      type: 'default',
      icon: /*#__PURE__*/React.createElement(SearchOutlined, null),
      style: {
        padding: '0 8px'
      }
    }, searchText || (lang === null || lang === void 0 ? void 0 : lang['filter.submit']) || '查询') : false,
    placeholder: (lang === null || lang === void 0 ? void 0 : lang['field.input.placeholder']) || '请输入',
    value: !searchAuto || searchTrigger === 'search' ? searchInputValue : searchReactorValue
  }, searchConfig, {
    onSearch: onRefactorSearch,
    onChange: onRefactorChange
  })), searchExtra && /*#__PURE__*/React.createElement("div", {
    className: 'spec-standard-refactor-tree-search-extra'
  }, searchExtra)), RenderTree(), footer && /*#__PURE__*/React.createElement("div", {
    className: 'spec-standard-refactor-tree-footer'
  }, footer)));
});
export default RefactorTree;