<template>
  <div :class="{ 'is-fold': !isUnfold }" class="app-tree border-radius-5">
    <!-- <div class="app-tree-unfold-btn" @click="onUnfoldBtnClick">
      <div class="unfold-btn" style="width: 10px; height: 36px; line-height: 36px">
        <i class="el-icon-arrow-left" />
      </div>
    </div> -->
    <div v-show="!isUnfold" class="collapse-btn" @click="onUnfoldBtnClick">
      <i class="el-icon-arrow-left" />
    </div>

    <div v-if="!hideTopbar" class="app-tree-top-bar">
      <div class="app-tree-title-bar">
        <span class="app-tree-title-text">{{ title }}</span>
        <i class="el-icon-arrow-left" @click="onUnfoldBtnClick" />
        <!-- <div class="expand-btn" @click="isExpandAll = !isExpandAll">
          <i :class="[isExpandAll ? 'el-icon-upload2' : 'el-icon-download', 'mr-5']" :title="isExpandAll ? '收起全部' : '展开全部'" />
          {{ isExpandAll ? '收起' : '展开' }}
        </div> -->
      </div>
      <!-- <div class="app-tree-search-bar">
        <el-input v-model="searchVal" :placeholder="searchPlaceholder" clearable />
      </div> -->
      <div v-if="rootAdd" class="app-tree-add-node-btn" @click="onRootAddClick">
        <svg-icon class-name="add-icon" icon-class="add" />
        新增
      </div>
    </div>
    <!-- Tree 内容 -->
    <!-- 懒加载时，不做折叠隐藏 -->
    <div v-if="treeBaseVisible || lazy" class="app-tree-base">
      <el-tree
        v-if="isRendered"
        ref="elTree"
        :data="data"
        :default-checked-keys="defCheckedKeys"
        :default-expand-all="isExpandAll"
        :default-expanded-keys="defExpandedKeys"
        :draggable="draggable"
        :expand-on-click-node="false"
        :filter-node-method="filterNode"
        :lazy="lazy"
        :load="loadNode"
        :node-key="nodeKey"
        :props="props"
        highlight-current
        v-bind="$attrs"
        v-on="$listeners"
        @node-click="onNodeClick"
      >
        <template #default="scope">
          <app-tree-node
            :actions="getActions(scope)"
            :data="scope.data"
            :disabled="checkDisabled(scope.data)"
            :edit="edit"
            :icon="scope.data.icon"
            :img="scope.data.img"
            :label="scope.node.label"
            :props="props"
            @dblclick="onNodeDBClick($event, scope)"
            @node-action-click="onNodeActionClick($event, scope)"
          />
        </template>
      </el-tree>
    </div>
  </div>
</template>

<script>
import AppTreeNode from './AppTreeNode';

const DEF_ACTIONS = [
  { label: '添加', type: 'add' },
  { label: '编辑', type: 'edit' },
  { label: '删除', type: 'delete' },
];
export default {
  name: 'AppTree',
  components: {
    AppTreeNode,
  },
  props: {
    draggable: {
      type: Boolean,
      default: true,
    },
    hideTopbar: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '标题',
    },
    searchPlaceholder: {
      type: String,
      default: '请输入',
    },
    props: {
      type: Object,
      default: () => ({}),
    },
    data: {
      type: Array,
      default: () => [],
    },
    defExpandedKeys: {
      type: Array,
      default: () => [],
    },
    defCheckedKeys: {
      type: Array,
      default: () => [],
    },
    expandAll: {
      type: Boolean,
      default: true,
    },
    nodeKey: {
      type: String,
      default: 'id',
    },
    lazy: {
      type: Boolean,
      default: false,
    },
    rootAdd: {
      type: Boolean,
      default: false,
    },
    actions: {
      type: [Array, Function],
      default: () => DEF_ACTIONS,
    },
    edit: {
      type: Boolean,
      default: false,
    },
    loadNode: {
      type: Function,
      default: () => {},
    },
    reload: {
      type: Function,
      default: null,
    },
    nodeClick: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {
      isUnfold: true,
      searchVal: '',
      isRendered: false, // 渲染完毕
      isExpandAll: this.expandAll,
      treeBaseVisible: true,
    };
  },
  computed: {
    elTree() {
      return this.$refs.elTree;
    },
  },
  watch: {
    searchVal(val) {
      // 懒加载则重新加载数据
      if (typeof this.reload === 'function') {
        this.reload(val);
      } else if (!this.lazy) {
        this.elTree.filter(val);
      }
    },
    expandAll(val) {
      this.isExpandAll = val;
    },
    isExpandAll() {
      this.reloadTree();
    },
    isUnfold(val) {
      this.$emit('unfold', val);
    },
  },

  mounted() {
    this.isRendered = true;
  },
  beforeDestroy() {
    if (this.clickTimer) {
      clearTimeout(this.clickTimer);
      this.clickTimer = null;
    }
  },
  methods: {
    filterNode(value, data, node) {
      if (!value) {
        return true;
      }
      return node?.label.indexOf(value) !== -1;
    },
    onRootAddClick() {
      this.$emit('root-add', true);
    },
    onNodeClick(data, node, tree) {
      const fn = () => {
        this.clickTimer = null;
        const isBooleanDisabled = this.props['disabled'] === true;
        const isFnDisabled = typeof this.props['disabled'] === 'function' && this.props['disabled'](data, node) === true;
        const isDataDisabled = data.disabled === true;
        if (isBooleanDisabled || isFnDisabled || isDataDisabled) return;
        if (this.nodeClick && typeof this.nodeClick === 'function') {
          this.nodeClick(data, node, tree);
        }
      };
      if (this.clickTimer) {
        clearTimeout(this.clickTimer);
        this.clickTimer = null;
        this.clickTimer = setTimeout(() => {
          this.clickTimer = null;
          fn();
        }, 350);
      } else {
        fn();
        this.clickTimer = setTimeout(() => {
          this.clickTimer = null;
        }, 350);
      }
    },
    onNodeActionClick(e, { node, data }) {
      this.$emit('node-action-click', {
        ...e,
        node,
        data,
      });
    },
    onNodeDBClick(e, scope) {
      if (this.clickTimer) {
        clearTimeout(this.clickTimer);
        this.clickTimer = null;
      }
      this.$emit('node-dblclick', e, scope);
    },
    onUnfoldBtnClick() {
      if (this.treeBaseVisible) {
        this.treeBaseVisible = false;
      } else {
        setTimeout(() => {
          this.treeBaseVisible = true;
        }, 300);
      }
      this.isUnfold = !this.isUnfold;
    },
    getActions(scope) {
      if (this.actions && Array.isArray(this.actions)) {
        return this.actions;
      } else if (this.actions && typeof this.actions === 'function') {
        return this.actions(scope, DEF_ACTIONS);
      }
    },
    reloadTree() {
      this.isRendered = false;
      setTimeout(() => {
        this.isRendered = true;
      });
    },
    checkDisabled(data) {
      if (typeof this.props?.disabled === 'function') {
        return this.props.disabled(data);
      } else if (typeof this.props?.disabled === 'boolean') {
        return this.props.disabled;
      }
      return false;
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep {
  //此处为自定义 展开图标
  //.el-tree .el-tree-node__expand-icon.expanded {
  //  -webkit-transform: rotate(0deg);
  //  transform: rotate(0deg);
  //}
  //.el-tree .el-icon-caret-right:before {
  //  content: '\e78a';
  //}
  //.el-tree .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
  //  content: '\e784';
  //}
}

.app-tree {
  width: 280px;
  height: 100%;
  background: #fff;
  border: 0;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  position: relative;
  transition: all 0.3s ease-out;
  .app-tree-top-bar,
  .app-tree-base {
    transition: opacity 0.5s ease-out;
    opacity: 1;
    min-width: 220px;
  }
  .app-tree-top-bar {
    padding: 12px 5px 12px 15px;
    // background: #1890ff;
    background: #fafafa;
    border-bottom: 1px solid #e9e9e9;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    color: #1890ff;
    .app-tree-title-text {
      font-size: 14px;
    }
    i {
      cursor: pointer;
      transition: all 0.4s;
      &:hover {
        opacity: 0.6;
      }
    }
  }

  .unfold-btn {
    background: #c4e3ff;
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
  }

  .app-tree-title-bar {
    display: flex;
    justify-content: space-between;
    //font-weight: bold;
    font-size: 14px;
    line-height: 14px;
    padding-right: 0.2rem;

    .expand-btn {
      display: inline-flex;
      align-items: center;
      color: #1890ff;
      font-weight: 400;
      cursor: pointer;
      .expand-icon {
        margin-right: 6px;
        font-size: 12px;
        color: #1890ff;
        transform: rotate(180deg);
        display: inline-block;
        transition: transform 0.15s ease-in-out;
        &.is-expand {
          transform: rotate(0deg);
        }
      }
    }
  }
  .app-tree-search-bar {
    padding: 0;
    background-color: #fff;
    input {
      font-size: 14px;
      color: #4d4d4d;
      border: none;
    }
  }
  .app-tree-add-node-btn {
    margin-top: 16px;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    font-size: 14px;
    line-height: 20px;
    color: #4d4d4d;
    cursor: pointer;
    .add-icon {
      display: inline-block;
      margin-right: 8px;
    }
  }
  .app-tree-base {
    flex: 1;
    overflow: hidden;
    box-sizing: border-box;
    .el-tree {
      height: 100%;
      overflow-y: auto;
      background: transparent;
      // padding: 0 4px 0 14px;
      border: 0;
      ::v-deep.el-tree-node__content {
        height: 30px;
        display: flex;
        align-items: center;
        &:hover {
          background-color: #eff0f1;
          color: #1890ff;
        }
      }
    }
  }
  ::v-deep.el-tree-node__expand-icon {
    color: #333;
    &.is-leaf {
      color: transparent;
    }
  }
}

.collapse-btn {
  position: absolute;
  right: -1px;
  top: 0;
  color: #fff;
  background: #1890ff;
  width: 12px;
  height: 36px;
  line-height: 36px;
  transform: rotate(-180deg);
  border-radius: 8px;
  cursor: pointer;
  z-index: 9;
  i {
    font-size: 12px;
  }
}

.app-tree-unfold-btn {
  position: absolute;
  right: -1px;
  top: 0px;
  z-index: 9;
  transform: rotate(0);
  color: #fff;
  cursor: pointer;
}
.app-tree.is-fold {
  width: 10px;
  .app-tree-top-bar,
  .app-tree-base {
    opacity: 0;
  }
  .collapse-btn {
    display: inline;
  }
  .app-tree-unfold-btn {
    transform: rotate(-180deg);
    right: 0;
    color: #1890ff;
  }
}
</style>
