<template>
  <div class="app-container">
    <h4 class="form-header h4">基本信息</h4>
    <el-form ref="form" :model="form" :inline="true" label-width="auto">
      <el-form-item label="姓名" prop="nickName"><el-input v-model="form.nickName" disabled /></el-form-item>
      <el-form-item label="账号" prop="userName"><el-input v-model="form.userName" disabled /></el-form-item>
    </el-form>
    <h4 class="form-header h4">角色信息</h4>
    <el-table
      border
      :row-key="getRowKey"
      @row-click="clickRow"
      ref="table"
      @selection-change="handleSelectionChange"
      :header-cell-style="{ 'text-align': 'left' }"
      :cell-style="{ 'text-align': 'left' }"
      style="width: 575px;"
      :data="roles.slice((pageNum - 1) * pageSize, pageNum * pageSize)"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55"></el-table-column>
      <el-table-column label="角色名称" align="center" prop="roleName" />
      <template slot="empty">
        <el-empty></el-empty>
      </template>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="pageNum" :limit.sync="pageSize" />

    <el-form>
      <el-form-item style="text-align: left;margin-top:30px;">
        <el-button type="primary" @click="submitForm()">提交</el-button>
        <el-button @click="close()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getAuthRole, updateAuthRole } from '@/api/system/user';

export default {
  name: 'AuthRole',
  data() {
    return {
      // 分页信息
      total: 0,
      pageNum: 1,
      pageSize: 10,
      // 选中角色编号
      roleIds: [],
      // 角色信息
      roles: [],
      // 用户信息
      form: {}
    };
  },
  created() {
    const userId = this.$route.params && this.$route.params.userId;
    if (userId) {
      getAuthRole(userId).then(response => {
        this.form = response.user;
        this.roles = response.roles;
        this.total = this.roles.length;
        this.$nextTick(() => {
          this.roles.forEach(row => {
            if (row.flag) {
              this.$refs.table.toggleRowSelection(row);
            }
          });
        });
      });
    }
  },
  methods: {
    /** 单击选中行数据 */
    clickRow(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.roleIds = selection.map(item => item.roleId);
    },
    // 保存选中的数据编号
    getRowKey(row) {
      return row.roleId;
    },
    /** 提交按钮 */
    submitForm() {
      const userId = this.form.userId;
      const roleIds = this.roleIds.join(',');
      updateAuthRole({ userId: userId, roleIds: roleIds }).then(response => {
        this.$modal.msgSuccess('授权成功');
        this.close();
      });
    },
    /** 关闭按钮 */
    close() {
      const obj = { path: '/system/user' };
      this.$tab.closeOpenPage(obj);
    }
  }
};
</script>
