<template>
  <div
    class="el-tree-node"
    @click.stop="handleClick"
    @contextmenu="($event) => this.handleContextMenu($event)"
    v-show="node.visible"
    :class="[
      {
      'is-expanded': expanded,
      'is-current': node.isCurrent && !showCheckbox,
      'is-hidden': !node.visible,
      'is-checked': !node.disabled && node.checked,
      'is-parent': node.childNodes && node.childNodes.length,
      'is-pure-parent': node.childNodes && node.childNodes.length && node.childNodes.every((item) => !item.childNodes || item.childNodes.length === 0)
      },
      `el-tree-node-level-${node.level}`
    ]"
    role="treeitem"
    tabindex="-1"
    :aria-expanded="expanded"
    :aria-disabled="node.disabled"
    :aria-checked="node.checked"
    :draggable="tree.draggable"
    @dragstart.stop="handleDragStart"
    @dragover.stop="handleDragOver"
    @dragend.stop="handleDragEnd"
    @drop.stop="handleDrop"
    ref="node"
  >
    <div
      class="el-tree-node__content"
      :style="showLine || transfer ? {'padding-left': '24px'} : {'padding-left': (node.level - 1) * tree.indent + 12 + 'px'}"
      :class="{'el-tree-node-is-leaf': node.isLeaf, 'el-tree-node-is-tail': isTail, 'is-active': showActiveColor && node.isCurrent, 'el-tree-node__content_disabled': node.disabled}">
      <div class="el-tree-node-indent" v-if="node.level > 1 && showLine">
        <div
          class="el-tree-node-indent-block"
          :style="{ 'margin-right': tree.indent + 'px' }"
          :class="{'el-tree-node-indent-block-lineless': lineless[item - 1]}"
          v-for="item in (node.level - 1)">
        </div>
      </div>
      <div class="el-tree-node__wrap"
        :class="[node.disabled ? 'is-disabled' : 'is-focusable',
          {'is-checked': node.checked, 'is-indeterminate': node.indeterminate}]">
           <span
               @click.stop="handleExpandIconClick"
               v-if="!showLine"
               :class="[
                        'el-tree__icon',
                        'el-tree-node__expand-icon',
                        { 'is-leaf': node.isLeaf, 'expanded': !node.isLeaf && expanded },
                        tree.iconClass ? tree.iconClass : 'el-icon-caret-right'
                      ]"
           >
          </span>
        <template v-else>
          <span v-if="!node.isLeaf" @click.stop="handleExpandIconClick">
            <el-svg
              class="el-tree__icon"
              :icon-class="expanded ? 'tree-retract' : 'tree-expand'"
              size="var(--font-size-title-1)"
            ></el-svg>
          </span>
          <span v-else class="el-icon-file el-tree__icon el-tree-node__expand-icon">
          </span>
        </template>

        <el-checkbox
          v-if="showCheckbox && (node.data.needCheckBox == undefined ? true : node.data.needCheckBox)"
          v-model="node.checked"
          :indeterminate="node.indeterminate"
          :disabled="!!node.disabled"
          @click.native.stop
          @change="handleCheckChange"
        >
        </el-checkbox>
        <!-- 没有对应icon -->
        <span
          v-if="node.loading"
          class="el-tree-node__loading-icon el-icon-loading"
        >
        </span>
        <i v-if="node.data.icon" class="el-tree__icon" :class=[node.data.icon]></i>
        <node-content ref="content" :node="node"></node-content>
      </div>
    </div>
    <el-collapse-transition>
      <div
        class="el-tree-node__children"
        v-if="!renderAfterExpand || childNodeRendered"
        v-show="expanded"
        role="group"
        :aria-expanded="expanded"
      >
        <el-tree-node
          :render-content="renderContent"
          v-for="(child, index) in node.childNodes"
          :render-after-expand="renderAfterExpand"
          :show-checkbox="showCheckbox"
          :isSelect="isSelect"
          :showLine="showLine"
          :key="getNodeKey(child)"
          :isTail="index === node.childNodes.length - 1"
          :node="child"
          @node-expand="handleChildNodeExpand"
          :show-active-color="showActiveColor"
          :isOverflowHidden="isOverflowHidden"
        >
        </el-tree-node>
      </div>
    </el-collapse-transition>
  </div>
</template>

<script type="text/jsx">
import ElCollapseTransition from 'modesign-ui/src/transitions/collapse-transition';
import ElCheckbox from 'modesign-ui/packages/checkbox';
import emitter from 'modesign-ui/src/mixins/emitter';
import { getNodeKey } from './model/util';
import ElSvg from 'modesign-ui/packages/svg';
import ElInput from 'modesign-ui/packages/input';

export default {
  name: 'ElTreeNode',

  componentName: 'ElTreeNode',

  mixins: [emitter],

  props: {
    node: {
      default() {
        return {};
      }
    },
    props: {},
    renderContent: Function,
    renderAfterExpand: {
      type: Boolean,
      default: true
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    isSelect: {
      // 是否是树选择器
      type: Boolean,
      default: false
    },
    // 同一层级的最后一个节点
    isTail: {
      type: Boolean,
      default: false
    },
    // 是否展示连接线
    showLine: {
      type: Boolean,
      default: false
    },
    transfer: {
      type: Boolean,
      default: false
    },
    showActiveColor: {
      type: Boolean,
      default: false
    },
    isOverflowHidden: {
      type: Boolean
    }
  },

  components: {
    ElCollapseTransition,
    ElCheckbox,
    ElSvg,
    ElInput,
    NodeContent: {
      props: {
        node: {
          required: true
        }
      },
      inject: {
        editTree: {
          default: false
        }
      },
      render(h) {
        const parent = this.$parent;
        const tree = parent.tree;
        const {node, editTree } = this;
        const { data, store } = node;
        const draggableItem = tree.draggable ? <i class="el-icon-dragable el-tree__icon"></i> : ''
        const nodeClass = parent.isOverflowHidden ? 'el-tree-node__label overflow-hidden' : 'el-tree-node__label'
        return (
          parent.renderContent
            ? parent.renderContent.call(parent._renderProxy, h, { _self: tree.$vnode.context, node, data, store })
            : tree.$scopedSlots.default
              ? tree.$scopedSlots.default({ node, data })
              : <div class={nodeClass} onClick={() => {
                  parent.clickNode(node)
                }}>
                  { parent.editFlag ?
                    <div style="display: inline-block;">
                      <el-input size="mini" type="text"
                        on-blur={parent.handleBlur}
                        value={node.label} on-input={value => node.label = value}
                        nativeOnKeyup={ parent.handleEnter }
                        ref="editInput"
                        ></el-input>
                    </div>
                    : node.label }
                  {
                    (parent.editFlag || !editTree) ? '' :
                      <span class="operation">
                        <i on-click={ () => parent.edit(event) } class="el-icon-editor el-tree__icon"></i>
                        <i on-click={ () => parent.remove(node, data) } class="el-icon-delete el-tree__icon"></i>
                        { draggableItem }
                      </span>
                  }
                </div>
        );
      }
    }
  },

  data() {
    return {
      tree: null,
      expanded: false,
      childNodeRendered: false,
      oldChecked: null,
      oldIndeterminate: null,
      // 树名称是否在修改状态
      editFlag: false,
      // showLine 模式下是否显示缩进线。
      // 如果父节点是其所在层级的最后一个节点，那么所有的子节点（包括孙子节点等）在父节点所在层级的缩进格都不显示缩进线。
      lineless: this.$parent && this.$parent.tree ? [...this.$parent.lineless, this.$parent.isTail] : []
    };
  },

  watch: {
    'node.indeterminate'(val) {
      this.handleSelectChange(this.node.checked, val);
    },

    'node.checked'(val) {
      this.handleSelectChange(val, this.node.indeterminate);
    },

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

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

    handleSelectChange(checked, indeterminate) {
      if (this.oldChecked !== checked && this.oldIndeterminate !== indeterminate) {
        this.tree.$emit('check-change', this.node.data, checked, indeterminate);
      }
      this.oldChecked = checked;
      this.indeterminate = indeterminate;
    },

    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();
      }
      if (this.tree.checkOnClickNode && !this.node.disabled) {
        this.handleCheckChange(null, {
          target: { checked: !this.node.checked }
        });
      }
      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);
      }
    },

    handleCheckChange(value, ev) {
      this.node.setChecked(ev.target.checked, !this.tree.checkStrictly);
      this.$nextTick(() => {
        const store = this.tree.store;
        this.tree.$emit('check', this.node.data, {
          checkedNodes: store.getCheckedNodes(),
          checkedKeys: store.getCheckedKeys(),
          halfCheckedNodes: store.getHalfCheckedNodes(),
          halfCheckedKeys: store.getHalfCheckedKeys(),
        });
      });
    },

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

    handleDragStart(event) {
      if (!this.tree.draggable) return;
      this.tree.$emit('tree-node-drag-start', event, this);
    },

    handleDragOver(event) {
      if (!this.tree.draggable) return;
      this.tree.$emit('tree-node-drag-over', event, this);
      event.preventDefault();
    },

    handleDrop(event) {
      event.preventDefault();
    },

    handleDragEnd(event) {
      if (!this.tree.draggable) return;
      this.tree.$emit('tree-node-drag-end', event, this);
    },

    edit(ev) {
      this.editFlag = true;
      this.$nextTick(() => {
        this.$refs.content.$refs.editInput.focus();
        ev.stopPropagation()
      })
    },

    remove(node, data) {
      const props = this.tree.props || {};
      const childrenKey = props['children'] || 'children';

      const parent = node.parent;
      const children = parent.data.children || parent.data;
      const index = children.findIndex(d => d[`${childrenKey}`] === data[`${childrenKey}`]);
      children.splice(index, 1);
      this.tree.$emit('tree-node-remove', parent);
    },

    editInput(node, data) {
      node.data.label = data.label;
    },

    handleBlur() {
      this.editFlag = false;
    },

    handleEnter(e) {
      if (e.keyCode === 13) {
        this.editFlag = false;
      }
    },

    clickNode(node) {
      if (this.showCheckbox && node.isLeaf && !this.node.disabled) {
        this.handleCheckChange(null, {
          target: { checked: !node.checked }
        });
      }
    }
  },

  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>
