<template>
  <div class="role-menu-wrapper">
    <div class="left">
      <el-tree
        ref="menuTree"
        v-loading="loading"
        :data="treeData"
        show-checkbox
        node-key="Id"
        highlight-current
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-expanded-keys="expandedKeys"
        @check="handleCheck"
        @node-click="handleNodeClick"
      />
    </div>
    <div class="right">
      <RoleFunction ref="roleFunction" />
    </div>

  </div>
</template>
<script>
import { getRoleMenuFunction, updateRoleMenu } from '@/api/admin'
import RoleFunction from './RoleFunction'
export default {
  name: 'RoleMenu',
  components: { RoleFunction },
  data() {
    return {
      defaultProps: {
        label: 'MenuName',
        children: 'Children'
      },
      treeData: [],
      loading: false,
      expandedKeys: []
    }
  },
  methods: {
    getMenus(roleId) {
      this.roleId = roleId
      this.expandedKeys = []
      this.treeData = []
      this.loading = true
      this.$refs['roleFunction'].resetTable()
      getRoleMenuFunction(roleId)
        .then((res) => {
          this.loading = false
          this.treeData = res.Result
          this.expandedKeys.push(res.Result[0].Id)
          this.selectedArr = []
          this.$nextTick(function() {
            const arr = this.setNodeChecked(this.treeData)
            arr.forEach(item => {
              this.$refs.menuTree.setChecked(item, true, false)
              this.expandedKeys.push(item)
            })
          })
        })
        .catch(() => {
          this.loading = false
        })
    },
    handleCheck(data, currentChecked) {
      const arrID = []
      const { checkedNodes, halfCheckedNodes } = currentChecked
      halfCheckedNodes.forEach((item) => {
        arrID.push(item.Id)
      })
      checkedNodes.forEach((item) => {
        arrID.push(item.Id)
      })
      const param = { roleId: this.roleId, menuFunctionId: arrID }
      updateRoleMenu(param).then((res) => {
        if (res.IsSuccess) {
          this.$message.success('Updated successfully')
        }
      })
    },
    handleNodeClick(data) {
      this.$refs['roleFunction'].getFunctions(this.roleId, data.Id)
    },
    setNodeChecked(arr) {
      for (var i in arr) {
        if (arr[i].IsSelect) {
          this.selectedArr.push(arr[i].Id)
        }
        if (arr[i].Children && arr[i].Children.length) {
          this.setNodeChecked(arr[i].Children)
        }
      }
      return this.selectedArr
    }
  }
}
</script>
<style lang="scss" scoped>
  .role-menu-wrapper{
    height: 100%;
    display: flex;
    .right{
      width: 3;
      flex-grow: 6;
      overflow-y: auto;
      border-right: 1px solid #ccc;
    }
    .left{
      width: 0;
      flex-grow: 7;
      overflow-y: auto;
      thead {
        .el-table-column--selection {
          .cell {
            display: none;
          }
        }
      }
    }
  }
</style>
