<template>
  <div class="el-multi-node"
    @click.stop="handleClick"
    v-show="node.visible"
    :style="{'height': expanded && node.level === 1 ? setExpandedHeight : 'auto','width': node.level === 1 ? 100/ 3 +'%' : 100/ tree.cols +'%'}"
    :class="['el-multi-node-' + node.level,{
      'is-expanded': childNodeRendered && expanded,
      'is-current': tree.store.currentNode === node,
      'is-hidden': !node.visible,
    }]">
    <div class="el-multi-node__content" :style="{ 'padding-left': tree.indent + 'px'}">
     <!-- <i class="el-multi-node__cor" :style="{'top': setChildTop +'px','position':'absolute','left': '20px'}"></i>-->
      <el-checkbox
        v-if="showCheckbox"
        v-model="node.checked"
        :disabled="node.disabled === true ? true : false"
        :indeterminate="node.indeterminate"
        @change="handleCheckChange"
        @click.native.stop="handleUserClick">
      </el-checkbox>
      <span
        v-if="node.loading"
        class="el-multi-node__loading-icon el-icon-loading">
      </span><!--gpuAcceleration: false, -->
      <el-tooltip :content="node.label" placement="top" v-if="showTooltip" effect="light" :popper-options="{boundariesPadding: 30}">
        <node-content :node="node"></node-content>
      </el-tooltip>
      <node-content :node="node" v-else></node-content>
      <el-badge :value="leafCheckLimit ? node.isLeafChecksLimit : node.isLeafChecks" v-if="!node.isLeaf"/>
      <span
        @click.stop="handleExpandIconClick()"
        class="el-multi-node__expand-icon el-icon-arrow-down"
        :class="{ 'is-leaf': node.isLeaf, expanded: !node.isLeaf && expanded }">
      </span>
      <i :class="[setIcon, 'el-multi-node__lastleaf-icon',{'is-clicked' : node.lastLeaf}]" v-if="!showCheckbox && !expandOnClickNode && !node.isLeaf"  @click.stop="showLastLeafNodes()"></i>
    </div>
    <div
      v-if="node.lastLeaf"
      v-show="expanded"
      class="el-multi-node__children"
      :style="{'width':'100%' , 'position': 'absolute', 'top': node.level< 2 ? setChildTop + 'px': 0, 'left': 0,'z-index': node.level + 1}">
      <div class="el-multi-node__lastleaf">
        <div class="el-multi-node__lastleaf-back">
          <el-breadcrumb  class="el-multi-node__breadcrumb" :style="{'padding-left': tree.indent + 'px'}">
            <el-breadcrumb-item   @click.native="handleClostlastLeaf()">{{node.data.label}} <span class="el-multi-node__expand-icon el-icon-arrow-up"></span>
              <i class="el-icon-menu el-multi-node__lastleaf-icon is-clicked" ></i>
            </el-breadcrumb-item>
            <el-breadcrumb-item> 全部店铺</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="el-multi-node__lastleaf-item"
             :style="{'width':  100/ tree.cols +'%'}"
             v-for="list in node.isLeafNodes"
             v-if="!node.isLeaf"><span class="el-multi-node__lastleaf-mark" v-if="list.mark">独</span><span class="el-multi-node__lastleaf-value">{{list.label}}</span></div>
      </div>
    </div>
      <div
        v-else
        class="el-multi-node__children"
        v-show="expanded"
        :style="{'width':'100%' , 'position': 'absolute', 'top': node.level< 2 ? setChildTop + 'px': 0, 'left': 0,'z-index': node.level + 1}">
          <el-breadcrumb  class="el-multi-node__breadcrumb" separator=">"  v-if="node.level > 1 && expanded" :style="{'padding-left': tree.indent + 'px'}">
            <el-breadcrumb-item @click.native="handleExpand4" v-if="node.level> 4">{{this.$parent.$parent.$parent.$parent.node.data.label}}</el-breadcrumb-item>
            <el-breadcrumb-item @click.native="handleExpand3" v-if="node.level> 3">{{this.$parent.$parent.$parent.node.data.label}}</el-breadcrumb-item>
            <el-breadcrumb-item @click.native="handleExpand2" v-if="node.level> 2">{{this.$parent.$parent.node.data.label}}</el-breadcrumb-item>
            <el-breadcrumb-item @click.native="handleExpand1">{{this.$parent.node.data.label}}</el-breadcrumb-item>
            <el-breadcrumb-item>{{node.data.label}}</el-breadcrumb-item>
          </el-breadcrumb>
          <div
            v-if="node.childNodes.length > 0 && showSelectall"
            class="el-multi-select-all"
            :style="{'padding-left': tree.indent + 'px','width':  100/ tree.cols +'%'}">
            <el-checkbox
              v-model="node.checked"
              :disabled="node.disabled === true ? true : false"
              :indeterminate="node.indeterminate"
              @change="handleCheckChange"
              @click.native.stop="handleUserClick">全选
            </el-checkbox>
            <el-badge :value="leafCheckLimit ? node.isLeafChecksLimit : node.isLeafChecks"   v-if="!node.isLeaf"/>
          </div>
          <el-multi-node
            :render-content="renderContent"
            v-for="child in node.childNodes"
            :key="getNodeKey(child)"
            :node="child"
            @node-expand="handleChildNodeExpand">
          </el-multi-node>
      </div>


  </div>
</template>

<script type="text/jsx">
  import CollapseTransition from 'nui-v2/src/transitions/collapse-transition';
  import ElCheckbox from 'nui-v2/packages/checkbox';
  import emitter from 'nui-v2/src/mixins/emitter';

  export default {
    name: 'ElMultiNode',

    componentName: 'ElMultiNode',

    mixins: [emitter],

    props: {
      node: {
        default() {
          return {};
        }
      },
      props: {},
      renderContent: Function
    },
    computed: {
    },
    components: {
      ElCheckbox,
      CollapseTransition,
      NodeContent: {
        props: {
          node: {
            required: true
          }
        },
        render(h) {
          const parent = this.$parent;
          const node = this.node;
          const data = node.data;
          const store = node.store;
          return (
            parent.renderContent
              ? parent.renderContent.call(parent._renderProxy, h, { _self: parent.tree.$vnode.context, node, data, store })
              : <span class={this.node.disabled === true ? 'el-multi-node__label is-disabled' : 'el-multi-node__label'}>{ this.node.label } </span>
          );
        }
      }
    },

    data() {
      return {
        tree: null,
        expanded: false,
        childNodeRendered: false,
        showCheckbox: false,
        showSelectall: false,
        showTooltip: false,
        expandOnClickNode: false,
        oldChecked: null,
        oldIndeterminate: null,
        setExpandedHeight: '',
        oldCheckNumbers: 0,
        setChildTop: 36, // 第二级以上层级定位(目前元素高度为36px)
        setPosition: 0,  // 层级高度配置值
        setIcon: null,  // 设置图标（显示最后一层级的）
        expandTips: '展开',
        control: {
          tips: '显示店铺',
          status: '' // 最后一层级显示时，子级是否已展开状态
        }
      };
    },

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

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

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

    methods: {
      childStyles(){
        return {}
      },
      getNodeKey(node, index) {
        const nodeKey = this.tree.nodeKey;
        if (nodeKey && node) {
          return node.data[nodeKey];
        }
        return index;
      },

      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();
        }
        this.tree.$emit('node-click', this.node.data, this.node, this);
      },

      handleUserClick() {
        if (this.node.indeterminate) {
          this.node.setChecked(this.node.checked, !this.tree.checkStrictly);
        }
      },

      handleCheckChange(ev) {
        if (!this.node.indeterminate) {
          this.node.setChecked(ev, !this.tree.checkStrictly);
        }
      },

      handleChildNodeExpand(nodeData, node, instance) {
        this.broadcast('ElMultiNode', 'multi-node-expand', node);
        this.tree.$emit('node-expand', nodeData, node, instance);
      },
      handleExpandIconClick(value) {
        if (this.node.isLeaf) return;
        if (this.expanded) {
          this.expandTips = '展开';
          this.tree.$emit('node-collapse', this.node.data, this.node, this);
          this.node.collapse();
          switch (this.node.level) {
            case 1:
              this.handleExpandAll();
              break;
          }
          if (this.node.lastLeaf) {
            this.node.lastLeaf = false;
          }
        } else {
          this.expandTips = '折叠';
          this.node.expand();
          this.$emit('node-expand', this.node.data, this.node, this);
          this.$nextTick(() => {
            // 设置一级节点的高度(赋于 子节点的内容区高度)
            switch (this.node.level) {
              case 1:
                this.setExpandedHeight =  this.$el.lastChild.clientHeight + this.setPosition + 'px';
                break;
              case 2:
                this.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.setExpandedHeight = this.$el.lastChild.clientHeight + this.setPosition + 'px';
                break;
              case 3:
                this.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.setExpandedHeight = this.$el.lastChild.clientHeight + this.setPosition + 'px';
                break;
              case 4:
                this.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$parent.setExpandedHeight = this.$el.lastChild.clientHeight + this.setPosition + 'px';
                break;
              case 5:
                this.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$parent.$parent.$el.lastChild.style.height = this.$el.lastChild.clientHeight  + 'px';
                this.$parent.$parent.$parent.$parent.setExpandedHeight = this.$el.lastChild.clientHeight + this.setPosition + 'px';
                break;
              default:
                break;
            }
          });
        }
      },
      // 关闭全部子级
      handleExpandAll(){
        this.$el.style.height= 'auto';
        let x = this.$el.getElementsByClassName('el-multi-node__children');
        for (let i = 0; i < x.length; i++) {
          x[i].style.height = 'auto';
        }
        this.node.lastLeaf = false;
        const confirmChild = (childNodes) => {
          for (let i = 0, j = childNodes.length; i < j; i++) {
            const child = childNodes[i];
            child.expanded = false;
            child.lastLeaf = false;
            // 如果还有子集，再做遍历
            if (child.childNodes.length > 0) {
              confirmChild(child.childNodes);
            }
          };
        };
        confirmChild(this.node.childNodes);
      /*  if(this.node.childNodes.length > 0) {
          this.node.childNodes.forEach(function(e){
            e.expanded = false;
            e.lastLeaf = false;
            if(e.childNodes.length>0){
              e.childNodes.forEach(function(f){
                f.expanded = false;
                f.lastLeaf = false;
                if(f.childNodes.length>0){
                  f.childNodes.forEach(function(g){
                    g.expanded = false;
                    g.lastLeaf = false;
                    if(g.childNodes.length>0){
                      g.childNodes.forEach(function(h){
                        h.expanded = false;
                        h.lastLeaf = false;
                      })
                    }
                  })
                }
              })
            }
          })
        }*/
      },
      // 面包屑层级折叠
      handleExpand1(){
        this.node.collapse();
        this.$nextTick(() => {
          switch (this.node.level) {
            case 2:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.setExpandedHeight = this.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 3:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.setExpandedHeight = this.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 4:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.setExpandedHeight = this.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 5:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$parent.setExpandedHeight = this.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            default:
              break;
          }
       });
      },
      handleExpand2(){
        this.node.collapse();
        this.$parent.node.collapse();
        this.expanded = false;
        this.childNodeRendered = false;
        this.$nextTick(() => {
          switch (this.node.level) {
            case 3:;
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.setExpandedHeight = this.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 4:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.setExpandedHeight = this.$parent.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 5:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$parent.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$parent.setExpandedHeight = this.$parent.$parent.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            default:
              break;
            }
          });
      },
      handleExpand3(){
        this.node.collapse();
        this.$parent.node.collapse();
        this.$parent.$parent.node.collapse();
        this.expanded = false;
        this.childNodeRendered = false;
        this.$nextTick(() => {
          switch (this.node.level) {
            case 4:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$el.lastChild.style.height =  'auto';
              this.$parent.$parent.$parent.setExpandedHeight = this.$parent.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            case 5:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$parent.$el.lastChild.style.height = this.$parent.$parent.$parent.$el.lastChild.clientHeight + 'px';
              this.$parent.$parent.$parent.$parent.setExpandedHeight = this.$parent.$parent.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            default:
              break;
          }
        });
      },
      handleExpand4(){
        this.node.collapse();
        this.$parent.node.collapse();
        this.$parent.$parent.node.collapse();
        this.$parent.$parent.$parent.node.collapse();
        this.expanded = false;
        this.childNodeRendered = false;
        this.$nextTick(() => {
          switch (this.node.level) {
            case 5:
              this.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$parent.$el.lastChild.style.height = 'auto';
              this.$parent.$parent.$parent.$parent.setExpandedHeight = this.$parent.$parent.$parent.$parent.$el.lastChild.clientHeight + this.setPosition + 'px';
              break;
            default:
              break;
          }
        });
      },
      // 显示店铺功能：确认显示全部时，子级是否已经展开
      confirmNextLevelIsShow(nextLevel) {
        // 根节点才需要做判断
        if (this.node.level === 1) {
          if(this.expanded) {
            nextLevel = true; //展开过
          } else {
            nextLevel = false; //未展开过
          }
        }
        return nextLevel;
      },
      // 显示店铺功能：显示最后一层级的节点数据
      showLastLeafNodes(value) {
        this.control.status = this.confirmNextLevelIsShow();
        if (this.node.lastLeaf) {
          // 关闭
          this.handleClostlastLeaf();
          this.control.tips="显示店铺";
          this.expandTips="展开";
        } else {
          // 显示
          this.node.lastLeaf = true;
          this.control.tips="关闭店铺";
          if (this.control.status){
            this.$nextTick(() => {
              this.$el.lastChild.style.height = 'auto';
              this.setExpandedHeight =  this.$el.lastChild.clientHeight + this.setPosition + 'px';
            })
          } else {
            this.handleExpandIconClick();
          }
        }
        this.tree.$emit('last-leaf-click', this.node.isLeafNodes); // 点击事件获取本数据的最后一层节点
      },
      // 显示店铺功能：关闭显示最后一层级的节点数据
      handleClostlastLeaf() {
        this.node.lastLeaf = false;
        this.$nextTick(() => {
          switch (this.node.level) {
            case 1:
              if (this.expanded){
                this.node.collapse();
              }
              this.$nextTick(() => {
                this.$el.lastChild.style.height = 'auto';
                this.setExpandedHeight =  this.$el.lastChild.clientHeight + this.setPosition + 'px';
              })
              break;
            default:
              this.handleExpand1(); // 其他level时，默认返回上一级数据
              break;
          }
        })
      }
    },
    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();
      });

      this.showCheckbox = tree.showCheckbox;
      this.showSelectall = tree.showSelectall;
      this.showTooltip = tree.showTooltip;
      this.expandOnClickNode = tree.expandOnClickNode;

//      this.setChildTop = tree.setChildTop;
      this.setPosition = tree.setPosition;
      this.setIcon = tree.setIcon;

      this.leafCheckLimit = tree.leafCheckLimit; // 最后一层节点选中数量限制

      if (this.node.expanded) {
        this.expanded = true;
        this.childNodeRendered = true;
      }

      if(this.tree.accordion) {
        this.$on('multi-node-expand', node => {
          if(this.node !== node) {
            this.node.collapse();
            this.handleExpandAll(); // 关闭全部子集
            this.node.lastLeaf = false;
          }
        });
      }
    },
    mounted() {
//      this.$nextTick(() => {
//        if (this.node.level == 1) {
//         this.setChildTop = this.$parent.$el.getElementsByClassName('el-multi-node-1')[0].clientHeight;
//        }
//      })
    }
  };
</script>
