<template>
  <el-dialog title="角色分配" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
    <el-table ref="multipleTable" :data="tableData" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column prop="roleName" label="角色名称" align="center"> </el-table-column>
      <el-table-column prop="roleKey" label="角色标识" align="center"> </el-table-column>
    </el-table>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handSubmit">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { optionselect, authRole } from '@/api/system/user'
export default {
  name: 'RoleDialog',
  components: {},
  data() {
    // 这里存放数据
    return {
      dialogVisible: false,
      tableData: [],
      selection: [],
      activeRow: null
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    async getList() {
      const { code, data } = await optionselect()
      if (code == 200) {
        this.tableData = data
      }
    },
    handleClose() {
      this.$nextTick(() => {
        this.$refs.multipleTable.clearSelection()
      })

      this.activeRow = null
      this.selection = []
      this.dialogVisible = false
    },
    openRoleDialog(row) {
      this.activeRow = row
      this.dialogVisible = true
      if (row.roleIds) {
        row.roleIds.forEach((element) => {
          this.tableData.forEach((item) => {
            if (element == item.roleId) {
              this.$nextTick(() => {
                this.$refs.multipleTable.toggleRowSelection(item)
              })
            }
          })
        })
      }
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    async handSubmit() {
      let roleId = []
      this.selection.forEach((i) => {
        roleId.push(i.roleId)
      })
      let postData = {
        userId: this.activeRow.userId,
        roleIds: roleId
      }
      const { code } = await authRole(postData)
      if (code == 200) {
        this.$refs.multipleTable.clearSelection()
        this.activeRow = null
        this.selection = []
        this.dialogVisible = false
        this.$emit('handSubmit')
        this.$message({
          type: 'success',
          message: '操作成功!'
        })
      }
    }
  }
}
</script>

<style lang="scss">
@import './index.scss';
</style>
