<template>
  <div class="v-component v-role-manage">
    <div class="role-manage-content">
      <role-list :list="roleList" :current-id="currentRoleId" @select-role="selectRole" @oper-role="openRoleModal"></role-list>
      <permission-tree ref="permission-tree" :sys-id="sysId" :role-id="currentRoleId" :permission-list="allPermissionList"></permission-tree>
    </div>
    <add-modal ref="add-modal" :sys-id="sysId" @success="addSuccess"></add-modal>
    <edit-modal ref="edit-modal" :sys-id="sysId" @success="editSuccess"></edit-modal>
    <delete-modal ref="delete-modal" @delete="deleteRole" title="删除角色" content="确定要删除该角色吗？"></delete-modal>
    <Spin size="large" fix v-if="loading"></Spin>
  </div>
</template>

<script>
import role from '../../apis/role'
import roleList from './role-list'
import permissionTree from './permission-tree'
import addModal from './add-modal'
import editModal from './edit-modal'
import deleteModal from '../delete-modal'
import collect from '../../utils/collect'

export default {
  name: 'RoleManage',
  data () {
    return {
      sysId: '',
      roleList: [],
      allPermissionList: [],
      currentRoleId: '',
      operData: {},
      loading: false
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      try {
        this.loading = true
        let res = await role.getRoleList()
        if (!res.data.length) return
        let { sysId = '', sysRoles = [], permissions = [] } = res.data[0]
        this.sysId = sysId
        this.roleList = sysRoles
        this.allPermissionList = permissions
        this.selectRole()
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    selectRole (roleId) {
      if (roleId) {
        this.currentRoleId = roleId
      } else {
        let roleIdList = collect.getValueList(this.roleList, 'id')
        if (roleIdList.includes(this.currentRoleId)) return
        this.currentRoleId = this.roleList[0].id
      }
      this.$nextTick(() => {
        this.$refs['permission-tree'].getPermissions()
      })
    },
    openRoleModal (type, role = {}) {
      this.operData = role
      this.$refs[`${type}-modal`].openModal(role)
    },
    addSuccess (roleId) {
      this.currentRoleId = roleId
      this.$refs['permission-tree'].emptyPermission()
      this.getRoleList()
    },
    editSuccess () {
      this.getRoleList()
    },
    async deleteRole () {
      try {
        this.loading = true
        await role.deleteRole(this.operData.id)
        this.$Message.success('删除成功')
        this.getRoleList()
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    }
  },
  components: {
    roleList,
    permissionTree,
    addModal,
    editModal,
    deleteModal
  }
}
</script>