"use strict";

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); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _antd = require("antd");
require("./style/index.less");
var _utils = require("../../utils");
var _icons = require("@ant-design/icons");
var _TreeSelect = _interopRequireDefault(require("./style/TreeSelect"));
var _classnames = _interopRequireDefault(require("classnames"));
var _util = require("../../RefactorTree/util");
var _useLanguage = require("../../hooks/use-language");
var _lodash = _interopRequireDefault(require("lodash"));
var _excluded = ["treeData", "value", "showFullLevel", "separator", "disabled", "disabledFields", "fieldStatus", "treeOptionName", "placeholder", "protoTreeNode", "onSelect", "labelInValue", "filedName", "collapsable", "collapsableCount", "collapsableTitleRender", "collapsableClassName"];
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache(e) { if ("function" != typeof WeakMap) return null; var r = new WeakMap(), t = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(e) { return e ? t : r; })(e); }
function _interopRequireWildcard(e, r) { if (!r && e && e.__esModule) return e; if (null === e || "object" != _typeof(e) && "function" != typeof e) return { default: e }; var t = _getRequireWildcardCache(r); if (t && t.has(e)) return t.get(e); var n = { __proto__: null }, a = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var u in e) if ("default" !== u && Object.prototype.hasOwnProperty.call(e, u)) { var i = a ? Object.getOwnPropertyDescriptor(e, u) : null; i && (i.get || i.set) ? Object.defineProperty(n, u, i) : n[u] = e[u]; } return n.default = e, t && t.set(e, n), n; }
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 _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; }
var RefactorTreeSelect = /*#__PURE__*/_react.default.forwardRef(function (props, ref) {
  var _props$treeData = props.treeData,
    treeData = _props$treeData === void 0 ? [] : _props$treeData,
    value = props.value,
    showFullLevel = props.showFullLevel,
    _props$separator = props.separator,
    separator = _props$separator === void 0 ? '/' : _props$separator,
    disabled = props.disabled,
    disabledFields = props.disabledFields,
    fieldStatus = props.fieldStatus,
    _props$treeOptionName = props.treeOptionName,
    treeOptionName = _props$treeOptionName === void 0 ? {
      title: 'title',
      label: 'label',
      value: 'value',
      children: 'children',
      disabled: 'disabled'
    } : _props$treeOptionName,
    placeholder = props.placeholder,
    protoTreeNode = props.protoTreeNode,
    _onSelect = props.onSelect,
    labelInValue = props.labelInValue,
    filedName = props.filedName,
    collapsable = props.collapsable,
    _props$collapsableCou = props.collapsableCount,
    collapsableCount = _props$collapsableCou === void 0 ? 2 : _props$collapsableCou,
    collapsableTitleRender = props.collapsableTitleRender,
    collapsableClassName = props.collapsableClassName,
    otherProps = _objectWithoutProperties(props, _excluded);
  var lang = (0, _useLanguage.useLanguageObject)(); // 当前使用的语言包
  var componentName = 'refactor-tree-select';
  var _useStyle = (0, _TreeSelect.default)(componentName),
    _useStyle2 = _slicedToArray(_useStyle, 2),
    wrapSSR = _useStyle2[0],
    hashId = _useStyle2[1];
  // 重组数据
  var transTreeData = (0, _react.useMemo)(function () {
    var newTree = _lodash.default.cloneDeep(treeData || []);
    return (0, _util.transDataParam)(newTree, (otherProps === null || otherProps === void 0 ? void 0 : otherProps.fieldNames) || treeOptionName, {
      separator: separator,
      disabledFields: disabledFields
    }); // 通过转换后的数据
  }, [treeData, treeOptionName, otherProps.fieldNames, separator, disabledFields]);
  // 设置名称字段值
  var setLabelKeyName = function setLabelKeyName() {
    var _otherProps$fieldName;
    return showFullLevelKeyName || ((_otherProps$fieldName = otherProps.fieldNames) === null || _otherProps$fieldName === void 0 ? void 0 : _otherProps$fieldName.label) || treeOptionName.title || treeOptionName.label;
  };
  // 判断是否指定显示完整名称
  var showFullLevelKeyName = (0, _react.useMemo)(function () {
    return showFullLevel ? 'treeFullLevelName' : otherProps === null || otherProps === void 0 ? void 0 : otherProps.treeNodeLabelProp;
  }, [showFullLevel, otherProps === null || otherProps === void 0 ? void 0 : otherProps.treeNodeLabelProp]);
  var _useState = (0, _react.useState)(false),
    _useState2 = _slicedToArray(_useState, 2),
    showAllPath = _useState2[0],
    setShowAllPath = _useState2[1]; // 显示所有树选择路径
  var renderTreeSelectNodePath = function renderTreeSelectNodePath() {
    var _nodeInfo$matchNode$;
    if (otherProps.multiple || otherProps !== null && otherProps !== void 0 && otherProps.treeCheckable) {
      // 获取节点路径   otherProps?.treeCheckStrictly || labelInValue  状态下, value值是labelInValue
      var pathNodes = (0, _utils.getNodePaths)(transTreeData, otherProps !== null && otherProps !== void 0 && otherProps.treeCheckStrictly || labelInValue ? (value || []).map(function (vItem) {
        return vItem.value;
      }) : value, {
        childrenParam: treeOptionName.children,
        keyParam: treeOptionName.value
      }, _objectSpread({}, otherProps));
      var togglePath = function togglePath() {
        setShowAllPath(!showAllPath);
      };
      if (pathNodes.length > 0) {
        return /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("div", {
          className: (0, _classnames.default)('tree-select-viewonly-list', showAllPath ? 'collapsed' : '', collapsableClassName)
        }, pathNodes.map(function (pathItem, index) {
          if (pathItem.length > 0) {
            var _pathItem;
            // 超过2个且不显示所有
            if (index > (collapsableCount - 1 <= 0 ? 0 : collapsableCount - 1) && !showAllPath) return '';
            var labelText = (_pathItem = pathItem[(pathItem === null || pathItem === void 0 ? void 0 : pathItem.length) - 1]) === null || _pathItem === void 0 ? void 0 : _pathItem[setLabelKeyName()];
            // const labelText = showFullLevelKeyName
            //   // '只取最后一个节点，或者只取label值'
            //   ? pathItem[pathItem?.length - 1]?.[setLabelKeyName()]
            //   // 直接子节点全部过滤
            //   : pathItem.map((i: any) => {
            //     return i[setLabelKeyName()]
            //   }).join(separator)
            return collapsableTitleRender ? collapsableTitleRender === null || collapsableTitleRender === void 0 ? void 0 : collapsableTitleRender(index, labelText, pathItem) : /*#__PURE__*/_react.default.createElement("div", {
              className: (0, _classnames.default)('tree-select-viewonly-item'),
              key: index
            }, /*#__PURE__*/_react.default.createElement("b", null, "\xB7 "), " ", labelText);
          }
        }), pathNodes.length > (collapsableCount <= 0 ? 1 : collapsableCount) ? /*#__PURE__*/_react.default.createElement("div", {
          className: "toggle-icon",
          onClick: togglePath
        }, !showAllPath ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, (lang === null || lang === void 0 ? void 0 : lang['field.expand']) || '展开', " ", /*#__PURE__*/_react.default.createElement(_icons.DownOutlined, null)) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, (lang === null || lang === void 0 ? void 0 : lang['field.collapse']) || '收起', " ", /*#__PURE__*/_react.default.createElement(_icons.UpOutlined, null))) : null));
      } else {
        return '-';
      }
    }
    var nodeInfo = (0, _utils.getParentNodes)(transTreeData, labelInValue ? value === null || value === void 0 ? void 0 : value.value : value, {
      childrenParam: treeOptionName.children,
      keyParam: treeOptionName.value
    }, _objectSpread({}, otherProps));
    return (nodeInfo === null || nodeInfo === void 0 || (_nodeInfo$matchNode$ = nodeInfo.matchNode[0]) === null || _nodeInfo$matchNode$ === void 0 ? void 0 : _nodeInfo$matchNode$[setLabelKeyName()]) || '-'; // 只读显示时，只返回文本
  };
  if (fieldStatus === 'viewOnly') {
    return /*#__PURE__*/_react.default.createElement("div", {
      className: (0, _classnames.default)(componentName, hashId, otherProps === null || otherProps === void 0 ? void 0 : otherProps.className, componentName + '-viewOnly')
    }, function (_nodeInfo$matchNode$2) {
      // 有值且显示要显示完整路径时;或者配置collapsable（适用于未配置showFullLevelKeyName但是多选下想用可展示状态的情况下，即每项都能单独显示而不是直接全部拼接在一起显示）
      if (showFullLevelKeyName || otherProps.treeCheckable && collapsable || otherProps.multiple && collapsable) {
        return renderTreeSelectNodePath();
      }
      // 多选状态
      if (otherProps.multiple || otherProps.treeCheckable) {
        if (otherProps !== null && otherProps !== void 0 && otherProps.treeCheckStrictly || labelInValue) {
          return value && value.length > 0 ? value.map(function (item) {
            return item[setLabelKeyName()] || item['title'] || item['label'];
          }).join(',') : '-';
        }
        var pathNodes = (0, _utils.getNodePaths)(transTreeData, value, {
          childrenParam: treeOptionName.children,
          keyParam: treeOptionName.value
        }, _objectSpread({}, otherProps));
        return pathNodes.length > 0 ? pathNodes.map(function (nItem) {
          var _nItem;
          return (_nItem = nItem[nItem.length - 1]) === null || _nItem === void 0 ? void 0 : _nItem[setLabelKeyName()];
        }).join(',') : '-';
      }
      var nodeInfo = (0, _utils.getParentNodes)(transTreeData, labelInValue ? value === null || value === void 0 ? void 0 : value.value : value, {
        childrenParam: treeOptionName.children,
        keyParam: treeOptionName.value
      }, _objectSpread({}, otherProps));
      return (nodeInfo === null || nodeInfo === void 0 || (_nodeInfo$matchNode$2 = nodeInfo.matchNode[0]) === null || _nodeInfo$matchNode$2 === void 0 ? void 0 : _nodeInfo$matchNode$2[setLabelKeyName()]) || '-'; // 只读显示时，只返回文本
    }());
  }
  return wrapSSR( /*#__PURE__*/_react.default.createElement(_antd.TreeSelect, _extends({
    placeholder: placeholder,
    value: value,
    ref: ref
  }, otherProps, {
    treeNodeLabelProp: showFullLevel ? 'treeFullLevelName' : otherProps === null || otherProps === void 0 ? void 0 : otherProps.treeNodeLabelProp,
    className: (0, _classnames.default)(componentName, hashId, otherProps === null || otherProps === void 0 ? void 0 : otherProps.className),
    labelInValue: labelInValue,
    showCheckedStrategy: otherProps.showCheckedStrategy,
    disabled: disabled,
    onSelect: function onSelect(value, node, extra) {
      var newNodeInfo = (0, _utils.getParentNodes)(transTreeData, value, {
        childrenParam: treeOptionName.children,
        keyParam: treeOptionName.value
      });
      if (_onSelect) _onSelect(value, _objectSpread(_objectSpread({}, node), newNodeInfo.matchNode[0]), extra, newNodeInfo.nodeParent);
    },
    onOpenChange: function onOpenChange(open) {
      var _otherProps$onOpenCha;
      otherProps === null || otherProps === void 0 || (_otherProps$onOpenCha = otherProps.onOpenChange) === null || _otherProps$onOpenCha === void 0 || _otherProps$onOpenCha.call(otherProps, open);
    },
    onSearch: function onSearch(value) {
      var _otherProps$onSearch;
      otherProps === null || otherProps === void 0 || (_otherProps$onSearch = otherProps.onSearch) === null || _otherProps$onSearch === void 0 || _otherProps$onSearch.call(otherProps, value);
    },
    treeData: transTreeData,
    fieldNames: _objectSpread(_objectSpread({}, treeOptionName), {}, {
      label: (treeOptionName === null || treeOptionName === void 0 ? void 0 : treeOptionName.title) || (treeOptionName === null || treeOptionName === void 0 ? void 0 : treeOptionName.label)
    }, (otherProps === null || otherProps === void 0 ? void 0 : otherProps.fieldNames) || {})
  })));
});
var _default = exports.default = RefactorTreeSelect;