<template>
  <div id="areaTree" class="addrTree">
    <ul :id="treeId" class="ztree"></ul>
  </div>
</template>

<script>
import $ from 'jquery'
export default {
  name: 'editableTree',
  components: {},
  props: {
    treeData: {
      // 树 data
      type: Array,
      default() {
        return []
      },
    },
    editable: {
      // 是否可编辑
      type: Boolean,
      default: true,
    },
    btn: {
      // 按钮集合
      type: Array,
      default() {
        return ['add', 'del']
      },
    },
    selectFirstNode: {
      // 是否默认选中第一个节点
      type: Boolean,
      default: false,
    },
    pIdKey: {
      type: String,
      default: 'parentId',
    },
  },
  data() {
    return {
      treeId: 'treeDemo' + new Date().getTime(),
      setting: {
        view: {
          addHoverDom: this.editable && this.showBtn('add') && this.addHoverDom,
          showIcon: false,
          showLine: true,
          selectedMulti: false,
        },
        edit: {
          enable: this.editable,
          showRemoveBtn: this.showBtn('del') && this.showRemoveBtn,
          showRenameBtn: this.showBtn('edit') && this.showRenameBtn,
          removeTitle: '删除',
          renameTitle: '修改',
        },
        data: {
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: this.pIdKey,
            rootPId: 0,
          },
        },
        callback: {
          onClick: this.zTreeOnClick,
          beforeDrag: this.beforeDrag,
          onExpand: this.onExpand,
          beforeRemove: this.beforeRemove,
          beforeEditName: this.beforeEditName,
          beforeRename: this.beforeRename,
          onRename: this.onRename,
          onRemove: this.onRemove,
        },
      },
      zNodes: [],
      log: '',
      className: 'dark',
      newCount: 1,
      curDragNodes: '',
      autoExpandNode: '',
      action: 'add',
    }
  },
  methods: {
    zTreeOnClick(event, treeId, treeNode) {
      this.$emit('treeNodeClick', treeNode)
    },
    beforeDrag(treeId, treeNodes) {
      return false
    },
    onExpand(event, treeId, treeNode) {
      if (treeNode === this.autoExpandNode) {
        this.className = this.className === 'dark' ? '' : 'dark'
        this.showLog('[ ' + this.getTime() + ' onExpand ]&nbsp;&nbsp;&nbsp;&nbsp;' + treeNode.name)
      }
    },
    remove() {
      // 移除节点
      var zTree = $.fn.zTree.getZTreeObj(this.treeId),
        nodes = zTree.getSelectedNodes(),
        treeNode = nodes[0]
      this.$emit('delTreeNode', treeNode)
    },
    beforeRemove(treeId, treeNode) {
      if (treeNode.id) {
        console.log('delete:', treeNode)
        this.$emit('deleteNode', treeNode) // 触发删除
      }
      return false
    },
    onRemove(e, treeId, treeNode) {
      this.showLog('[ ' + this.getTime() + ' onRemove ]&nbsp;&nbsp;&nbsp;&nbsp; ' + treeNode.name)
    },
    onRename(event, treeId, treeNode, isCancel) {
      console.log('rename')
      this.$emit('treeInfoEvent', treeNode, event)
    },
    beforeRename(treeId, treeNode, newName) {
      if (newName.length == 0) {
        alert('节点名称不能为空.')
        var zTree = $.fn.zTree.getZTreeObj(this.treeId)
        setTimeout(function () {
          zTree.editName(treeNode)
        }, 10)
        return false
      } else if (newName.length > 20) {
        alert('节点名称不能大于20个字符.')
        var zTree = $.fn.zTree.getZTreeObj(this.treeId)
        setTimeout(function () {
          zTree.editName(treeNode)
        }, 10)
        return false
      }
      return true
    },
    showLog(str) {
      if (!this.log) this.log = $('#log')
      this.log.append("<li class='" + this.className + "'>" + str + '</li>')
      if (this.log.children('li').length > 8) {
        this.log.get(0).removeChild(this.log.children('li')[0])
      }
    },
    getTime() {
      var now = new Date(),
        h = now.getHours(),
        m = now.getMinutes(),
        s = now.getSeconds(),
        ms = now.getMilliseconds()
      return h + ':' + m + ':' + s + ' ' + ms
    },
    addHoverDom(treeId, treeNode) {
      if (treeNode.addDis != true) {
        let _this = this
        var sObj = $('#' + treeNode.tId + '_span')
        if (treeNode.editNameFlag || $('#addBtn_' + treeNode.tId).length > 0) return
        var addStr =
          "<span class='button add' id='addBtn_" + treeNode.tId + "' title='新增' onfocus='this.blur();'>新增</span>"
        sObj.after(addStr)
        var btn = $('#addBtn_' + treeNode.tId)
        if (btn)
          btn.bind('click', function () {
            _this.add(treeNode)
          })
      }
    },
    add(treeNode) {
      // 增加子节点
      this.action = 'add' // 切换为add
      var zTree = $.fn.zTree.getZTreeObj(this.treeId)
      var isParent = false
      var nodes = zTree.getSelectedNodes()
      var treeNode2 = nodes[0]
      if (treeNode) {
        treeNode2 = zTree.addNodes(treeNode, {
          id: '',
          pId: treeNode.id,
          sysCode: treeNode.sysCode || treeNode.valStr,
          isParent: isParent,
          name: '新子节点' + this.newCount++,
        })
      } else {
        treeNode2 = zTree.addNodes(null, { id: '', pId: 0, isParent: isParent, name: '新节点' + this.newCount++ })
      }
      if (treeNode2) {
        zTree.editName(treeNode2[0])
      } else {
        alert('叶子节点被锁定，无法增加子节点')
      }
    },
    addTopNodes() {
      this.action = 'add'
      var zTree = $.fn.zTree.getZTreeObj(this.treeId)
      var treeNode = zTree.addNodes(null, { id: '', pId: 0, isParent: true, name: '新节点' + this.newCount++ })
      zTree.editName(treeNode[0])
      this.treeNodeMessage = zTree.getNodes() //Root节点信息
      this.$emit('RootNodes', this.treeNodeMessage)
    },
    showRemoveBtn(treeId, treeNode) {
      if (treeNode.removeDis == true) return false
      return true
    },
    showRenameBtn(treeId, treeNode) {
      if (treeNode.renameDis == true) return true
      return false
    },
    showBtn(button) {
      if (this.btn && this.btn.length > 0) {
        if (this.btn.findIndex((v) => v == button) > -1) {
          return true
        } else {
          return false
        }
      } else {
        return false
      }
    },
    selectFirstNodeFun() {
      // 选中第一个节点
      if (this.selectFirstNode) {
        const treeObj = $.fn.zTree.getZTreeObj(this.treeId)
        console.log(treeObj)
        let nodes = treeObj.getNodes()
        if (nodes.length > 0) {
          treeObj.selectNode(nodes[0])
        }
      }
    },
    selectNode(node) {
      const treeObj = $.fn.zTree.getZTreeObj(this.treeId)
      treeObj.selectNode(node)
    },
    queryTreeFun(data) {
      this.searchTree(data)
    },
    searchTree(info) {
      var treeObj = $.fn.zTree.getZTreeObj(this.treeId)
      if (info.val == '') {
        $.fn.zTree.init($('#' + this.treeId), this.setting, this.treeData)
      } else {
        function filter(node) {
          return node.name.indexOf(info.val) > -1
        }
        let nodes = treeObj.transformToArray(this.treeData)
        nodes = JSON.parse(JSON.stringify(nodes))
        nodes.map((item) => {
          if (item.hasOwnProperty('children')) {
            delete item.children
          }
          return item
        })

        nodes = nodes.filter((v) => v.name.indexOf(info.val) > -1)
        nodes = treeObj.transformTozTreeNodes(nodes)
        $.fn.zTree.init($('#' + this.treeId), this.setting, nodes)
        treeObj.expandAll(true)
      }
    },
  },
  watch: {
    treeData(val) {
      $.fn.zTree.init($('#' + this.treeId), this.setting, val)
      this.selectFirstNodeFun()
    },
  },
  mounted() {
    this.$nextTick(() => {
      $.fn.zTree.init($('#' + this.treeId), this.setting, this.treeData)
      this.selectFirstNodeFun()
    })
  },
}
</script>
<style lang="scss" scope>
.addrTree {
  position: relative;
  height: 100%;
  background: #fff;
  .tree_title {
    height: 30px;
    line-height: 30px;
    padding: 0 10px;
    background: #fafafa;
    button {
      float: right;
      margin: 4px 4px 0 0;
    }
  }
  .ztree {
    height: 100%;
    overflow: auto;
    padding: 5px;
    li span.button.add {
      background-position: -143px 0;
    }
  }
  [treenode_a] {
    vertical-align: middle;
    .button.add {
      margin-right: 2px;
      display: none;
    }
    &:hover {
      .button.add {
        display: inline-block;
      }
    }
    span {
      vertical-align: middle !important;
    }
  }
  [treenode_a].curSelectedNode {
    .button.add {
      display: inline-block;
    }
  }
  [treenode_switch] {
    vertical-align: middle;
  }
}
</style>