<template>
    <el-dialog
      v-dialogDrag
      :visible.sync="showModal"
      title="分配角色"
    >
    <div style="text-align: center;overflow-y: auto;height: 450px">
      <ul :id="treeId" class="ztree" v-loading="isLoading"/>
    </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>
/**
 * 管理员选择角色 Ztree
 */
import { sysRole, sysUser } from '../../../api'
export default {
  data() {
    return {
      isLoading: true,
      treeId: '',
      showModal: false,
      modalVal: false,
      OrgObj: {
        idsList: [],
        namesList: []
      },
      treeObj: {},
      setting: {
        data: {
          simpleData: {
            enable: true,
            idKey: 'id',
            pIdKey: 'pid'
          }
        },
        check: {
          enable: true
        },
        callback: {
          onClick: this.zTreeOnClick
        }
      }
    }
  },
  methods: {
    _openRoleZtree(ID) {
      this.showModal = true
      this.modalVal = true
      this.treeId = 'userRole' + this.$randomCode()
      this._search(ID)
    },
    _editRoleZtree(ID) {
      // 编辑回显 tree name
      this.modalVal = false
      this.treeId = 'userRole' + this.$randomCode()
      this._search(ID)
    },
    _search: async function(ID) {
      this.isLoading = false
      const result = await sysRole.roleTreeList()
      this.treeObj = $.fn.zTree.init($('#' + this.treeId), this.setting, result)
      if (ID !== undefined) {
        this._echoTree(ID)
      } else {
        this.isLoading = false
      }
    },
    // 回显选中的节点树
    _echoTree: async function(ID) {
      const result = await sysUser.managerInfo(ID)
      const roleIds = result.roles
      if (roleIds.length > 0) {
        for (let i = 0; i < roleIds.length; i++) {
          this.treeObj.checkNode(
            this.treeObj.getNodeByParam('id', roleIds[i].id),
            true
          )
        }
      }
      this.isLoading = false
      if (this.modalVal === false) {
        this._ok()
      }
    },
    zTreeOnClick(e, treeId, treeNode, clickFlag) {
      this.treeObj.checkNode(treeNode, !treeNode.checked, true)
    },
    _resultChange(ids, names) {
      this.OrgObj.idsList = ids // 所选中的ids
      this.OrgObj.namesList = names // 所选中的names
      this.$emit('on-result-change', this.OrgObj)
      this.showModal = false
    },
    _cancel() {
      this._resultChange([], [])
    },
    _ok() {
      const nodesIdsList = []
      const nodesNameList = []
      const nodes = this.treeObj.getCheckedNodes(true)
      for (let i = 0; i < nodes.length; i++) {
        nodesIdsList.push(nodes[i].id)
        nodesNameList.push(nodes[i].name)
      }
      this._resultChange(nodesIdsList, nodesNameList)
    }
  }
}
</script>
