<template>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      :close-on-click-modal="false"
      title="选择上级菜单"
    >
    <div>
      <Form onsubmit="return false">
        <Form-item>
          <el-input
            v-model="key"
            style="width: 460px;"
            type="text"
            placeholder="请输入菜单名称,回车查询"
            @keyup.enter.native="_search"
          />
        </Form-item>
      </Form>
    </div>
    <div style="text-align: center;overflow-y: auto;height: 450px">
      <ul :id="treeId" class="ztree" v-show="isTree" v-loading="isLoading"></ul>
    </div>
    <div slot="footer" class="btn-width">
      <el-button style="margin-left: 8px" @click="_cancel">
        取消
      </el-button>
      <el-button type="primary" @click="_ok">
        确定
      </el-button>
    </div>
    </el-dialog>
</template>
<script>
/**
 * 选择上级菜单tree
 */
import { equipType } from '../../../api'
export default {
  data() {
    return {
      showModal: false,
      selNotes: [],
      isLoading: true,
      isTree: false,
      treeId: '',
      key: '',
      treeObj: {},
      setting: {
        data: {
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: 'pid'
          }
        },
        check: {
          enable: true,
          chkStyle: 'radio',
          radioType: 'all'
        },
        view: {
          showIcon: false
        },
        callback: {
          onClick: this.zTreeOnClick, //  双击节点
          onDblClick: this.zTreeOnDblClick
        }
      }
    }
  },
  methods: {
    _open() {
      this.showModal = true
      this.isLoading = true
      this.isTree = false
      this.treeId = 'selResource' + this.$randomCode()
      this.key = ''
      this._search()
      this.selNotes = []
    },
    _search: async function() {
      const data = {
        type: 0
      }
      if (this.key) {
        data.name = this.key
      }
      const result = await equipType.getTree(data)
      this.treeObj = $.fn.zTree.init($('#' + this.treeId), this.setting, result)
      setTimeout(() => {
        this.isLoading = false
        this.isTree = true
        // treeObj.expandAll(true);
      }, 300)
    },
    zTreeOnClick(event, treeId, treeNode) {
      this.treeObj.checkNode(treeNode, !treeNode.checked, true)
    },
    zTreeOnDblClick(event, treeId, treeNode) {
      if (treeNode) {
        this.$emit('on-result-change', treeNode)
        this.showModal = false
      }
    },
    _cancel() {
      this.showModal = false
    },
    _ok() {
      this.selNotes = this.treeObj.getCheckedNodes(true)
      this.$emit('on-result-change', this.selNotes[0]) // 向父及传递数据
      this.showModal = false
    }
  }
}
</script>
