/**
 * tdesign v0.32.0
 * (c) 2021 tdesign
 * @license MIT
 */

'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var upperFirst = require('lodash/upperFirst');
var pick = require('lodash/pick');
var utils_mixins = require('../utils/mixins.js');
var configProvider_configReceiver = require('../config-provider/config-receiver.js');
var _common_js_tree_treeStore = require('../_common/js/tree/tree-store.js');
var tree_treeItem = require('./tree-item.js');
var tree_props = require('./props.js');
var utils_renderTnode = require('../utils/render-tnode.js');
var tree_constants = require('./constants.js');
var tree_util = require('./util.js');
var utils_event = require('../utils/event.js');
require('vue');
require('@babel/runtime/helpers/defineProperty');
require('../config-provider/zh_CN_config.js');
require('@babel/runtime/helpers/classCallCheck');
require('@babel/runtime/helpers/createClass');
require('lodash/difference');
require('lodash/camelCase');
require('lodash/isPlainObject');
require('../_common/js/tree/tree-node.js');
require('@babel/runtime/helpers/asyncToGenerator');
require('@babel/runtime/helpers/toConsumableArray');
require('@babel/runtime/regenerator');
require('lodash/uniqueId');
require('lodash/get');
require('../_common/js/tree/tree-node-model.js');
require('lodash/isFunction');
require('tdesign-icons-vue');
require('../checkbox/index.js');
require('../checkbox/group.js');
require('../_chunks/dep-44e6bdf6.js');
require('@babel/runtime/helpers/typeof');
require('lodash/intersection');
require('../config.js');
require('../checkbox/checkbox.js');
require('../utils/classnames.js');
require('../checkbox/props.js');
require('../utils/helper.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@babel/runtime/helpers/slicedToArray');
require('../checkbox/checkbox-group-props.js');
require('../utils/map-props.js');
require('../utils/withInstall.js');
require('lodash/capitalize');
require('../loading/index.js');
require('../loading/loading.js');
require('../loading/icon/gradient.js');
require('../utils/set-style.js');
require('../utils/dom.js');
require('raf');
require('lodash/isString');
require('../utils/easing.js');
require('../utils/transfer-dom.js');
require('../loading/props.js');
require('../loading/plugin.js');
require('../utils/ripple.js');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var upperFirst__default = /*#__PURE__*/_interopDefaultLegacy(upperFirst);
var pick__default = /*#__PURE__*/_interopDefaultLegacy(pick);

var _TdTree = utils_mixins["default"](configProvider_configReceiver["default"]("tree")).extend({
  name: "TTree",
  model: {
    prop: "value",
    event: "change"
  },
  props: tree_props["default"],
  data: function data() {
    var checkProps = this.checkProps,
        empty = this.empty,
        icon = this.icon,
        label = this.label,
        line = this.line,
        operations = this.operations;
    return {
      store: null,
      nodesMap: null,
      mouseEvent: null,
      treeNodes: [],
      treeScope: {
        checkProps: checkProps,
        empty: empty,
        icon: icon,
        label: label,
        line: line,
        operations: operations,
        scopedSlots: null
      },
      transitionCD: null
    };
  },
  computed: {
    classList: function classList() {
      var list = [tree_constants.CLASS_NAMES.tree];
      var disabled = this.disabled,
          hover = this.hover,
          transition = this.transition,
          checkable = this.checkable,
          expandOnClickNode = this.expandOnClickNode;

      if (disabled) {
        list.push(tree_constants.CLASS_NAMES.disabled);
      }

      if (hover) {
        list.push(tree_constants.CLASS_NAMES.treeHoverable);
      }

      if (checkable) {
        list.push(tree_constants.CLASS_NAMES.treeCheckable);
      }

      if (transition) {
        list.push(tree_constants.CLASS_NAMES.treeTransition);
      }

      if (expandOnClickNode) {
        list.push(tree_constants.CLASS_NAMES.treeBlockNode);
      }

      return list;
    }
  },
  watch: {
    data: function data(list) {
      this.rebuild(list);
    },
    value: function value(nVal) {
      this.store.replaceChecked(nVal);
    },
    expanded: function expanded(nVal) {
      this.store.replaceExpanded(nVal);
    },
    actived: function actived(nVal) {
      this.store.replaceActived(nVal);
    }
  },
  methods: {
    renderItem: function renderItem(node) {
      var h = this.$createElement;
      var treeScope = this.treeScope;
      var treeItem = h(tree_treeItem["default"], {
        "key": node.value,
        "attrs": {
          "node": node,
          "treeScope": treeScope
        },
        "on": {
          "click": this.handleClick,
          "change": this.handleChange
        }
      });
      return treeItem;
    },
    getNodesMap: function getNodesMap() {
      var nodesMap = this.nodesMap;

      if (!nodesMap) {
        nodesMap = new Map();
        this.nodesMap = nodesMap;
      }

      return nodesMap;
    },
    updateNodesMap: function updateNodesMap() {
      var store = this.store,
          treeNodes = this.treeNodes;
      var nodesMap = this.getNodesMap();
      var index = 0;

      while (index < treeNodes.length) {
        var nodeView = treeNodes[index];

        if (nodeView && nodeView.componentInstance) {
          var node = nodeView.componentInstance.node;

          if (node && !store.getNode(node.value)) {
            var nodeViewIndex = treeNodes.indexOf(nodeView);
            treeNodes.splice(nodeViewIndex, 1);
            nodeView.componentInstance.$destroy();
            nodesMap.set(node.value, null);
            nodesMap["delete"](node.value);
          } else {
            index += 1;
          }
        } else {
          index += 1;
        }
      }
    },
    refresh: function refresh() {
      var _this = this;

      var store = this.store,
          treeNodes = this.treeNodes;
      var nodesMap = this.getNodesMap();
      this.updateNodesMap();
      var index = 0;
      var allNodes = store.getNodes();
      allNodes.forEach(function (node) {
        if (nodesMap.has(node.value)) {
          var nodeView = nodesMap.get(node.value);
          var nodeViewIndex = treeNodes.indexOf(nodeView);

          if (nodeViewIndex !== index) {
            treeNodes.splice(nodeViewIndex, 1);
            treeNodes.splice(index, 0, nodeView);
          }
        } else if (node.visible) {
          var _nodeView = _this.renderItem(node);

          treeNodes.splice(index, 0, _nodeView);
          nodesMap.set(node.value, _nodeView);
        }

        index += 1;
      });
    },
    updateStoreConfig: function updateStoreConfig() {
      var store = this.store;
      if (!store) return;
      var storeProps = pick__default["default"](this, ["keys", "expandAll", "expandLevel", "expandMutex", "expandParent", "activable", "activeMultiple", "disabled", "checkable", "checkStrictly", "load", "lazy", "valueMode", "filter"]);
      store.setConfig(storeProps);
    },
    updateExpanded: function updateExpanded() {
      var store = this.store,
          expanded = this.expanded,
          expandParent = this.expandParent;

      if (Array.isArray(expanded)) {
        var expandedMap = new Map();
        expanded.forEach(function (val) {
          expandedMap.set(val, true);

          if (expandParent) {
            var node = store.getNode(val);
            node.getParents().forEach(function (tn) {
              expandedMap.set(tn.value, true);
            });
          }
        });
        var expandedArr = Array.from(expandedMap.keys());
        store.setExpanded(expandedArr);
      }
    },
    build: function build() {
      var _this2 = this;

      var list = this.data;
      var actived = this.actived,
          value = this.value,
          valueMode = this.valueMode,
          filter = this.filter;
      var store = new _common_js_tree_treeStore.TreeStore({
        valueMode: valueMode,
        filter: filter,
        onLoad: function onLoad(info) {
          _this2.handleLoad(info);
        },
        onUpdate: function onUpdate() {
          _this2.refresh();
        }
      });
      this.store = store;
      this.updateStoreConfig();

      if (!Array.isArray(list)) {
        list = [];
      }

      store.append(list);
      store.refreshNodes();

      if (Array.isArray(value)) {
        store.setChecked(value);
      }

      this.updateExpanded();

      if (Array.isArray(actived)) {
        store.setActived(actived);
      }

      this.refresh();
    },
    rebuild: function rebuild(list) {
      this.getNodesMap().clear();
      this.treeNodes.length = 0;
      var store = this.store,
          value = this.value,
          actived = this.actived;
      store.reload(list);

      if (Array.isArray(value)) {
        store.setChecked(value);
      }

      this.updateExpanded();

      if (Array.isArray(actived)) {
        store.setActived(actived);
      }

      store.refreshState();
    },
    toggleActived: function toggleActived(item) {
      var node = tree_util.getNode(this.store, item);
      return this.setActived(node, !node.isActived());
    },
    setActived: function setActived(item, isActived) {
      var node = tree_util.getNode(this.store, item);
      var actived = node.setActived(isActived);
      var mouseEvent = this.mouseEvent;
      var ctx = {
        node: node.getModel(),
        e: mouseEvent
      };
      utils_event.emitEvent(this, "active", actived, ctx);
      return actived;
    },
    toggleExpanded: function toggleExpanded(item) {
      var node = tree_util.getNode(this.store, item);
      return this.setExpanded(node, !node.isExpanded());
    },
    setExpanded: function setExpanded(item, isExpanded) {
      var node = tree_util.getNode(this.store, item);
      var expanded = node.setExpanded(isExpanded);
      var mouseEvent = this.mouseEvent;
      var ctx = {
        node: node.getModel(),
        e: mouseEvent
      };
      utils_event.emitEvent(this, "expand", expanded, ctx);
      return expanded;
    },
    toggleChecked: function toggleChecked(item) {
      var node = tree_util.getNode(this.store, item);
      return this.setChecked(node, !node.isChecked());
    },
    setChecked: function setChecked(item, isChecked) {
      var node = tree_util.getNode(this.store, item);
      var checked = node.setChecked(isChecked);
      var ctx = {
        node: node.getModel()
      };
      utils_event.emitEvent(this, "change", checked, ctx);
      return checked;
    },
    handleLoad: function handleLoad(info) {
      var node = info.node;
      var ctx = {
        node: node.getModel()
      };
      var value = this.value,
          expanded = this.expanded,
          actived = this.actived,
          store = this.store;

      if (value && value.length > 0) {
        store.replaceChecked(value);
      }

      if (expanded && expanded.length > 0) {
        store.replaceExpanded(expanded);
      }

      if (actived && actived.length > 0) {
        store.replaceActived(actived);
      }

      utils_event.emitEvent(this, "load", ctx);
    },
    handleClick: function handleClick(state) {
      var expandOnClickNode = this.expandOnClickNode;
      var mouseEvent = state.mouseEvent,
          event = state.event,
          node = state.node;

      if (!node || this.disabled || node.disabled) {
        return;
      }

      this.mouseEvent = mouseEvent;
      var shouldExpand = expandOnClickNode;
      var shouldActive = true;
      ["trigger", "ignore"].forEach(function (markName) {
        var mark = tree_util.getMark(markName, event.target, event.currentTarget);
        var markValue = (mark === null || mark === void 0 ? void 0 : mark.value) || "";

        if (markValue.indexOf("expand") >= 0) {
          if (markName === "trigger") {
            shouldExpand = true;
          } else if (markName === "ignore") {
            shouldExpand = false;
          }
        }

        if (markValue.indexOf("active") >= 0) {
          if (markName === "ignore") {
            shouldActive = false;
          }
        }
      });

      if (shouldExpand) {
        this.toggleExpanded(node);
      }

      if (shouldActive) {
        this.toggleActived(node);
      }

      var ctx = {
        node: node.getModel(),
        e: mouseEvent
      };
      utils_event.emitEvent(this, "click", ctx);
      this.mouseEvent = null;
    },
    handleChange: function handleChange(state) {
      var disabled = this.disabled;
      var node = state.node;

      if (!node || disabled || node.disabled) {
        return;
      }

      this.toggleChecked(node);
    },
    setItem: function setItem(value, options) {
      var _this3 = this;

      var node = this.store.getNode(value);
      var spec = options;
      var keys = Object.keys(spec);

      if (node && spec) {
        ["expanded", "actived", "checked"].forEach(function (name) {
          if (keys.includes(name)) {
            _this3["set".concat(upperFirst__default["default"](name))](node, spec[name]);

            delete spec[name];
          }
        });
        node.set(spec);
      }
    },
    getItem: function getItem(value) {
      var node = this.store.getNode(value);
      return node === null || node === void 0 ? void 0 : node.getModel();
    },
    getItems: function getItems(value) {
      var nodes = this.store.getNodes(value);
      return nodes.map(function (node) {
        return node.getModel();
      });
    },
    appendTo: function appendTo(para, item) {
      var _this4 = this;

      var list = [];

      if (Array.isArray(item)) {
        list = item;
      } else {
        list = [item];
      }

      list.forEach(function (item2) {
        var val = (item2 === null || item2 === void 0 ? void 0 : item2.value) || "";
        var node = tree_util.getNode(_this4.store, val);

        if (node) {
          _this4.store.appendNodes(para, node);
        } else {
          _this4.store.appendNodes(para, item2);
        }
      });
    },
    insertBefore: function insertBefore(value, item) {
      var val = (item === null || item === void 0 ? void 0 : item.value) || "";
      var node = tree_util.getNode(this.store, val);

      if (node) {
        this.store.insertBefore(value, node);
      } else {
        this.store.insertBefore(value, item);
      }
    },
    insertAfter: function insertAfter(value, item) {
      var val = (item === null || item === void 0 ? void 0 : item.value) || "";
      var node = tree_util.getNode(this.store, val);

      if (node) {
        this.store.insertAfter(value, node);
      } else {
        this.store.insertAfter(value, item);
      }
    },
    remove: function remove(value) {
      return this.store.remove(value);
    },
    getIndex: function getIndex(value) {
      return this.store.getNodeIndex(value);
    },
    getParent: function getParent(value) {
      var node = this.store.getParent(value);
      return node === null || node === void 0 ? void 0 : node.getModel();
    },
    getParents: function getParents(value) {
      var nodes = this.store.getParents(value);
      return nodes.map(function (node) {
        return node.getModel();
      });
    },
    getPath: function getPath(value) {
      var node = this.store.getNode(value);
      var pathNodes = [];

      if (node) {
        pathNodes = node.getPath().map(function (node2) {
          return node2.getModel();
        });
      }

      return pathNodes;
    }
  },
  created: function created() {
    this.build();
  },
  render: function render() {
    var h = arguments[0];
    var classList = this.classList,
        treeNodes = this.treeNodes,
        treeScope = this.treeScope,
        scopedSlots = this.$scopedSlots;
    var scopeProps = pick__default["default"](this, ["checkProps", "disableCheck", "icon", "label", "line", "operations"]);
    this.updateStoreConfig();
    Object.assign(treeScope, scopeProps);
    treeScope.scopedSlots = scopedSlots;
    var emptyNode = null;
    var treeNodeList = null;

    if (treeNodes.length <= 0) {
      var useLocale = !this.empty && !this.$scopedSlots.empty;
      emptyNode = h("div", {
        "class": tree_constants.CLASS_NAMES.treeEmpty
      }, [useLocale ? this.t(this.global.empty) : utils_renderTnode.renderTNodeJSX(this, "empty")]);
    }

    treeNodeList = h("transition-group", {
      "attrs": {
        "name": tree_constants.FX.treeNode,
        "tag": "div",
        "enter-active-class": tree_constants.CLASS_NAMES.treeNodeEnter,
        "leave-active-class": tree_constants.CLASS_NAMES.treeNodeLeave
      },
      "class": tree_constants.CLASS_NAMES.treeList
    }, [treeNodes]);
    return h("div", {
      "class": classList
    }, [treeNodeList, emptyNode]);
  }
});

exports["default"] = _TdTree;
//# sourceMappingURL=td-tree.js.map
