<template>
  <div>
    <div>
      <Form onsubmit="return false">
        <Form-item style="width:100%">
          <Input v-model="key" placeholder="请输入关键字，回车查询" style="width:100%" icon="ios-search-strong" @on-enter="_search" /></Input>
        </Form-item>
      </Form>
    </div>
    <!--加载中-->
    <div v-show="isloading" class="demo-spin-container spin-bg">
      <Spin fix size="large" />
    </div>
    <ul v-show="isTree" id="roleTree" class="ztree tree_height" style="overflow-x: auto;" />
  </div>
</template>
<script>
/**
 * 添加编辑Ztree
 */
import { sysRole } from '../../../api'
let setting
let treeObj
export default {
  data() {
    return {
      key: '',
      isloading: true,
      isTree: false,
      firstNode: [],
      treeListData: []
    }
  },
  mounted() {
    this._treeHeight()
  },
  methods: {
    _Ztree() {
      this.isloading = true
      this.isTree = false
      setting = {
        data: {
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: 'pid'
          }
        },
        callback: {
          onClick: this.zTreeOnClick //  单击节点
        }
      }
      this._getRoleTree()
    },

    _getRoleTree: async function() {
      const treeList = await sysRole.roleTreeList({})
      this.treeListData = treeList
      treeObj = $.fn.zTree.init($('#roleTree'), setting, treeList)
      setTimeout(() => {
        this.isloading = false
        this.isTree = true
        treeObj.expandAll(true)
      }, 300)
    },
    zTreeOnClick(event, treeId, treeNode) {
      this.$emit('on-result-change', treeNode) // 向父及传递数据
    },
    _search() {
      if (this.key !== '') {
        this.isloading = true
        this.isTree = false
        this.key = $.trim(this.key)
        this.$store.dispatch('SysRole/roleTreeKeyword', this.key).then(() => {
          treeObj = $.fn.zTree.init(
            $('#roleTree'),
            setting,
            this.$store.state.SysRole.treeList
          )
          setTimeout(() => {
            this.isloading = false
            this.isTree = true
            treeObj.expandAll(true)
          }, 300)
        })
      } else {
        this._Ztree()
      }
    },
    _treeHeight() {
      $('.tree_height').height(document.documentElement.clientHeight - 225)
    }
  }
}
</script>
