import * as _vue from "vue";

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 _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" && Symbol.iterator in Object(iter)) 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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

import { inject } from 'vue';
import omit from 'omit.js';
import debounce from 'lodash/debounce';
import FolderOpenOutlined from '@ant-design/icons-vue/FolderOpenOutlined';
import FolderOutlined from '@ant-design/icons-vue/FolderOutlined';
import FileOutlined from '@ant-design/icons-vue/FileOutlined';
import PropTypes from '../_util/vue-types';
import classNames from '../_util/classNames';
import { conductExpandParent, convertTreeToEntities } from '../vc-tree/src/util';
import Tree, { TreeProps } from './Tree';
import { calcRangeKeys, getFullKeyList, convertDirectoryKeysToNodes, getFullKeyListByTreeData } from './util';
import BaseMixin from '../_util/BaseMixin';
import { initDefaultProps, getOptionProps, getComponent, getSlot } from '../_util/props-util';
import { ConfigConsumerProps } from '../config-provider'; // export type ExpandAction = false | 'click' | 'dblclick'; export interface
// DirectoryTreeProps extends TreeProps {   expandAction?: ExpandAction; }
// export interface DirectoryTreeState {   expandedKeys?: string[];
// selectedKeys?: string[]; }

function getIcon(props) {
  var isLeaf = props.isLeaf,
      expanded = props.expanded;

  if (isLeaf) {
    return _vue.createVNode(FileOutlined, null, null);
  }

  return expanded ? _vue.createVNode(FolderOpenOutlined, null, null) : _vue.createVNode(FolderOutlined, null, null);
}

export default {
  name: 'ADirectoryTree',
  mixins: [BaseMixin],
  inheritAttrs: false,
  // model: {
  //   prop: 'checkedKeys',
  //   event: 'check',
  // },
  props: initDefaultProps(_objectSpread(_objectSpread({}, TreeProps()), {}, {
    expandAction: PropTypes.oneOf([false, 'click', 'doubleclick', 'dblclick'])
  }), {
    showIcon: true,
    expandAction: 'click'
  }),
  setup: function setup() {
    return {
      configProvider: inject('configProvider', ConfigConsumerProps)
    };
  },
  data: function data() {
    var props = getOptionProps(this);
    var defaultExpandAll = props.defaultExpandAll,
        defaultExpandParent = props.defaultExpandParent,
        expandedKeys = props.expandedKeys,
        defaultExpandedKeys = props.defaultExpandedKeys;
    var children = getSlot(this);

    var _convertTreeToEntitie = convertTreeToEntities(children),
        keyEntities = _convertTreeToEntitie.keyEntities;

    var state = {}; // Selected keys

    state._selectedKeys = props.selectedKeys || props.defaultSelectedKeys || []; // Expanded keys

    if (defaultExpandAll) {
      if (props.treeData) {
        state._expandedKeys = getFullKeyListByTreeData(props.treeData);
      } else {
        state._expandedKeys = getFullKeyList(children);
      }
    } else if (defaultExpandParent) {
      state._expandedKeys = conductExpandParent(expandedKeys || defaultExpandedKeys, keyEntities);
    } else {
      state._expandedKeys = expandedKeys || defaultExpandedKeys;
    }

    this.onDebounceExpand = debounce(this.expandFolderNode, 200, {
      leading: true
    });
    this.children = null;
    return _objectSpread({
      _selectedKeys: [],
      _expandedKeys: []
    }, state);
  },
  watch: {
    expandedKeys: function expandedKeys(val) {
      this.setState({
        _expandedKeys: val
      });
    },
    selectedKeys: function selectedKeys(val) {
      this.setState({
        _selectedKeys: val
      });
    }
  },
  methods: {
    handleExpand: function handleExpand(expandedKeys, info) {
      this.setUncontrolledState({
        _expandedKeys: expandedKeys
      });
      this.$emit('update:expandedKeys', expandedKeys);
      this.$emit('expand', expandedKeys, info);
      return undefined;
    },
    handleClick: function handleClick(event, node) {
      var expandAction = this.$props.expandAction; // Expand the tree

      if (expandAction === 'click') {
        this.onDebounceExpand(event, node);
      }

      this.$emit('click', event, node);
    },
    handleDoubleClick: function handleDoubleClick(event, node) {
      var expandAction = this.$props.expandAction; // Expand the tree

      if (expandAction === 'dblclick' || expandAction === 'doubleclick') {
        this.onDebounceExpand(event, node);
      }

      this.$emit('doubleclick', event, node);
      this.$emit('dblclick', event, node);
    },
    hanldeSelect: function hanldeSelect(keys, event) {
      var multiple = this.$props.multiple;
      var children = this.children || [];
      var _this$$data$_expanded = this.$data._expandedKeys,
          expandedKeys = _this$$data$_expanded === void 0 ? [] : _this$$data$_expanded;
      var node = event.node,
          nativeEvent = event.nativeEvent;
      var _node$eventKey = node.eventKey,
          eventKey = _node$eventKey === void 0 ? '' : _node$eventKey;
      var newState = {}; // We need wrap this event since some value is not same

      var newEvent = _objectSpread(_objectSpread({}, event), {}, {
        selected: true // Directory selected always true

      }); // Windows / Mac single pick


      var ctrlPick = nativeEvent.ctrlKey || nativeEvent.metaKey;
      var shiftPick = nativeEvent.shiftKey; // Generate new selected keys

      var newSelectedKeys;

      if (multiple && ctrlPick) {
        // Control click
        newSelectedKeys = keys;
        this.lastSelectedKey = eventKey;
        this.cachedSelectedKeys = newSelectedKeys;
        newEvent.selectedNodes = convertDirectoryKeysToNodes(children, newSelectedKeys);
      } else if (multiple && shiftPick) {
        // Shift click
        newSelectedKeys = Array.from(new Set([].concat(_toConsumableArray(this.cachedSelectedKeys || []), _toConsumableArray(calcRangeKeys(children, expandedKeys, eventKey, this.lastSelectedKey)))));
        newEvent.selectedNodes = convertDirectoryKeysToNodes(children, newSelectedKeys);
      } else {
        // Single click
        newSelectedKeys = [eventKey];
        this.lastSelectedKey = eventKey;
        this.cachedSelectedKeys = newSelectedKeys;
        newEvent.selectedNodes = [event.node];
      }

      newState._selectedKeys = newSelectedKeys;
      this.$emit('update:selectedKeys', newSelectedKeys);
      this.$emit('select', newSelectedKeys, newEvent);
      this.setUncontrolledState(newState);
    },
    setTreeRef: function setTreeRef(node) {
      this.tree = node;
    },
    expandFolderNode: function expandFolderNode(event, node) {
      var isLeaf = node.isLeaf;

      if (isLeaf || event.shiftKey || event.metaKey || event.ctrlKey) {
        return;
      }

      if (this.tree.tree) {
        // Get internal vc-tree
        var internalTree = this.tree.tree; // Call internal rc-tree expand function
        // https://github.com/ant-design/ant-design/issues/12567

        internalTree.onNodeExpand(event, node);
      }
    },
    setUncontrolledState: function setUncontrolledState(state) {
      var newState = omit(state, Object.keys(getOptionProps(this)).map(function (p) {
        return "_".concat(p);
      }));

      if (Object.keys(newState).length) {
        this.setState(newState);
      }
    },
    handleCheck: function handleCheck(checkedObj, eventObj) {
      this.$emit('update:checkedKeys', checkedObj);
      this.$emit('check', checkedObj, eventObj);
    }
  },
  render: function render() {
    var _this = this;

    this.children = getSlot(this);

    var _getOptionProps = getOptionProps(this),
        customizePrefixCls = _getOptionProps.prefixCls,
        props = _objectWithoutProperties(_getOptionProps, ["prefixCls"]);

    var getPrefixCls = this.configProvider.getPrefixCls;
    var prefixCls = getPrefixCls('tree', customizePrefixCls);
    var _this$$data = this.$data,
        expandedKeys = _this$$data._expandedKeys,
        selectedKeys = _this$$data._selectedKeys;

    var _this$$attrs = this.$attrs,
        className = _this$$attrs.class,
        restAttrs = _objectWithoutProperties(_this$$attrs, ["class"]);

    var connectClassName = classNames("".concat(prefixCls, "-directory"), className);

    var treeProps = _objectSpread(_objectSpread(_objectSpread({
      icon: getIcon
    }, restAttrs), omit(props, ['onUpdate:selectedKeys', 'onUpdate:checkedKeys', 'onUpdate:expandedKeys'])), {}, {
      prefixCls: prefixCls,
      expandedKeys: expandedKeys,
      selectedKeys: selectedKeys,
      switcherIcon: getComponent(this, 'switcherIcon'),
      ref: this.setTreeRef,
      class: connectClassName,
      onSelect: this.hanldeSelect,
      onClick: this.handleClick,
      onDblclick: this.handleDoubleClick,
      onExpand: this.handleExpand,
      onCheck: this.handleCheck
    });

    return _vue.createVNode(Tree, treeProps, {
      default: function _default() {
        return [_this.children];
      }
    });
  }
};