<template>
  <div
    ref="node"
    class="hn-easy-tree-node"
    role="treeitem"
    tabindex="-1"
    :aria-expanded="expanded"
    :class="{
      'is-expanded': expanded,
      'is-current': node.isCurrent,
      'is-last-child': node.isLastChild,
      'is-leaf': node.isLeaf,
    }"
    @click.stop="handleClick"
    @contextmenu="($event) => this.handleContextMenu($event)"
  >
    <div
      class="hn-easy-tree-node__content"
      :style="{ 'padding-left': (node.level - 1) * tree.indent + 'px' }">
      <!-- branch -->
      <tree-branch
        v-if="showBranch && node.level !== 1"
        :indent="tree.indent"
        :hide-bottom="node.parent.isLastChild && node.isLastChild"
        :hide-vertical-positions="collectHideVertical()"
        :node="node" />
      <!-- icon -->
      <span
        v-if="!node.isLeaf"
        :class="[
          'hn-easy-tree-node__expand-icon',
          tree.iconClass ? tree.iconClass : 'hn-iconfont-user'
        ]"
        @click.stop="handleExpandIconClick"
      >
      </span>
      <!-- content -->
      <node-content :node="node"></node-content>
    </div>
    <hn-collapse-transition>
      <div
        class="hn-easy-tree-node__children"
        v-if="!renderAfterExpand || childNodeRendered"
        v-show="expanded"
        role="group"
        :aria-expanded="expanded"
      >
        <hn-tree-node
          v-for="child in node.childNodes"
          :key="getNodeKey(child)"
          :render-content="renderContent"
          :render-after-expand="renderAfterExpand"
          :node="child"
          :show-branch="showBranch"
          @node-expand="handleChildNodeExpand">
        </hn-tree-node>
      </div>
    </hn-collapse-transition>
  </div>
</template>

<script type="text/jsx">
  import HNCollapseTransition from 'heiner-ui/src/transitions/collapse-transition';
  import TreeBranch from './tree-branch.vue';
  import emitter from 'heiner-ui/src/mixins/emitter';
  import { getNodeKey } from './model/util';

  export default {
    name: 'HnTreeNode',

    componentName: 'HnTreeNode',

    mixins: [emitter],

    props: {
      node: {
        default() {
          return {};
        }
      },
      renderContent: Function,
      renderAfterExpand: {
        type: Boolean,
        default: true
      },
      showBranch: {
        type: Boolean,
        default: true
      },
    },

    components: {
      HNCollapseTransition,
      TreeBranch,
      NodeContent: {
        props: {
          node: {
            required: true
          }
        },
        render(h) {
          const parent = this.$parent;
          const tree = parent.tree;
          const node = this.node;
          const { data, store } = node;
          return (
            parent.renderContent
              ? parent.renderContent.call(parent._renderProxy, h, { _self: tree.$vnode.context, node, data, store })
              : tree.$scopedSlots.default
                ? tree.$scopedSlots.default({ node, data })
                : <span class="hn-easy-tree-node__label">{ node.label }</span>
          );
        }
      }
    },

    data() {
      return {
        tree: null,
        expanded: false,
        childNodeRendered: false,
      };
    },

    watch: {
      'node.expanded'(val) {
        this.$nextTick(() => this.expanded = val);
        if (val) {
          this.childNodeRendered = true;
        }
      }
    },

    methods: {
      collectHideVertical() {
        const arr = [];
        let { parent } = this.node;
        while (parent) {
          if ((parent.isLastChild && parent.parent && parent.parent.isLastChild)) {
            arr.push(parent.level - 2);
          }
          parent = parent.parent
        }
        return arr;
      },

      getNodeKey(node) {
        return getNodeKey(this.tree.nodeKey, node.data);
      },

      handleClick() {
        const store = this.tree.store;
        store.setCurrentNode(this.node);
        this.tree.$emit('current-change', store.currentNode ? store.currentNode.data : null, store.currentNode);
        this.tree.currentNode = this;
        if (this.tree.expandOnClickNode) {
          this.handleExpandIconClick();
        }
        this.tree.$emit('node-click', this.node.data, this.node, this);
      },

      handleContextMenu(event) {
        if (this.tree._events['node-contextmenu'] && this.tree._events['node-contextmenu'].length > 0) {
          event.stopPropagation();
          event.preventDefault();
        }
        this.tree.$emit('node-contextmenu', event, this.node.data, this.node, this);
      },

      handleExpandIconClick() {
        if (this.node.isLeaf) return;
        if (this.expanded) {
          this.tree.$emit('node-collapse', this.node.data, this.node, this);
          this.node.collapse();
        } else {
          this.node.expand();
          this.$emit('node-expand', this.node.data, this.node, this);
        }
      },

      handleChildNodeExpand(nodeData, node, instance) {
        this.broadcast('HnTreeNode', 'tree-node-expand', node);
        this.tree.$emit('node-expand', nodeData, node, instance);
      },
    },

    created() {
      const parent = this.$parent;

      if (parent.isTree) {
        this.tree = parent;
      } else {
        this.tree = parent.tree;
      }

      const tree = this.tree;
      if (!tree) {
        console.warn('Can not find node\'s tree.');
      }

      const props = tree.props || {};
      const childrenKey = props['children'] || 'children';

      this.$watch(`node.data.${childrenKey}`, () => {
        this.node.updateChildren();
      });

      if (this.node.expanded) {
        this.expanded = true;
        this.childNodeRendered = true;
      }
      if(this.tree.accordion) {
        this.$on('tree-node-expand', node => {
          if(this.node !== node) {
            this.node.collapse();
          }
        });
      }
    }
  };
</script>
