<template>
  <div>
    <el-card>
      <div class="filter">
        <el-button type="primary" icon="el-icon-circle-plus" @click="showCreate" v-permission="('user:role:add')">新增</el-button>
      </div>
      <el-table :data="roleList" border style="width: 100%;margin-top:20px">
        <el-table-column type='index' width="50px">
          <template slot-scope="scope">
            <span>{{(queryModuleInfo.pageNum -1 ) * queryModuleInfo.pageSize + scope.$index + 1}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="200px"></el-table-column>
        <el-table-column label="用户名称" width="200px">
          <template slot-scope="scope">
            <div v-for="user in scope.row.usernameList" :key="user">
              <div v-text="user" style="display: inline-block;vertical-align: middle;"></div>
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column label="菜单&权限" width="200px">
          <template slot-scope="scope">
            <div v-for="permission in scope.row.permissionIdList" :key="permission">
              <el-tag type="success" v-text="permission"></el-tag>
            </div>
          </template>
        </el-table-column> -->

        <el-table-column prop="createTime" label="创建时间" width="200px"></el-table-column>
        <el-table-column label="操作">
          <slot slot-scope="scope">
            <el-button type="warning" icon="el-icon-edit" @click="editRoleDialog(scope.$index)" v-permission="('user:role:edit')">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" @click="delRoleFrom(scope.row)" v-permission="('user:role:del')">删除</el-button>
          </slot>
        </el-table-column>
      </el-table>
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="queryModuleInfo.pageNum" :page-size="queryModuleInfo.pageSize" layout="total, prev, pager, next" :total="totalNum">
      </el-pagination>
    </el-card>
    <!-- 添加角色 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="50%">
      <el-form ref="addRoleFormRef" :rules="rules" :model="addRoleForm" label-width="90px">
        <el-form-item label="角色名称:" prop="roleName" style="width:400px">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="菜单&权限" prop="roleCode" style="width:700px">
          <div v-for=" (menu,_index) in allPermissionList" :key="menu.menuName">
            <span style="width:100px;display: inline-block;">
              <el-button :type="isMenuNone(_index)?'':(isMenuAll(_index)?'success':'primary')" size="mini" style="width:100px;" @click="checkAll(_index)">{{menu.menuName}}</el-button>
            </span>
            <div style="display:inline-block;margin-left:30px;">
              <el-checkbox-group v-model="addRoleForm.permissionIdList">
                <el-checkbox v-for="perm in menu.permissionList" :label="perm.id" :key="perm.id">
                  {{perm.permissionName}}
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible=false">取 消</el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="addSaveRole">确 定</el-button>
        <el-button type="primary" v-else @click="editSaveRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getRoleList,
  addRolePermission,
  getPermissionList,
  delRolePermission,
  editRolePermission
} from '@/api/getUser'
export default {
  data() {
    return {
      queryModuleInfo: {
        pageNum: 1,
        pageSize: 10
      },
      totalNum: 0,
      roleList: [],
      textMap: {
        update: '编辑角色',
        create: '添加角色'
      },
      dialogStatus: 'create',
      dialogFormVisible: false,
      addRoleForm: {
        roleName: '',
        roleId: '',
        permissionIdList: []
      },
      rules: {
        roleName: [
          {
            required: true,
            message: '角色名称不能为空！',
            trigger: 'blur'
          }
        ]
      },
      allPermissionList: []
    }
  },
  created() {
    this.getRoleList()
    this.getPermissionList()
  },
  methods: {
    // 获取角色列表
    getRoleList() {
      getRoleList(this.queryModuleInfo).then((resp) => {
        this.roleList = resp.data.data.list
        this.totalNum = resp.data.data.total
      })
    },
    // 获取权限列表
    getPermissionList() {
      getPermissionList().then((resp) => {
        this.allPermissionList = resp.data.data
      })
    },
    // 显示新增对话框
    showCreate() {
      // 显示新增对话框
      this.addRoleForm.roleName = ''
      this.addRoleForm.roleId = ''
      this.addRoleForm.permissionIdList = []
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 编辑角色
    editRoleDialog($index) {
      let role = this.roleList[$index]
      this.addRoleForm.roleName = role.roleName
      this.addRoleForm.roleId = role.roleId
      this.addRoleForm.permissionIdList = role.permissionIdList
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    // 对话框方法
    openMessage(message, confirmText, doit) {
      this.$messageBox
        .confirm(message, '确定', {
          cancelButtonText: '取消',
          confirmButtonText: confirmText,
          type: 'warning'
        })
        .then(() => {
          doit()
        })
        .catch(() => {})
    },
    // 删除角色
    delRoleFrom(row) {
      this.openMessage('您确定要删除吗？', '删除', () => {
        delRolePermission({ roleId: row.roleId })
          .then((resp) => {
            if (resp.data.data === true) {
              this.$message.success('删除成功！')
              this.getRoleList()
            } else if (resp.data.data === false) {
              this.$message.error(resp.data.msg)
            }
          })
          .catch((error) => {
            this.$message({ type: 'error', message: error })
          })
      })
    },
    // 保存角色信息
    addSaveRole() {
      this.$refs.addRoleFormRef.validate((valid) => {
        if (!valid) {
          return false
        } else {
          addRolePermission(this.addRoleForm)
            .then((resp) => {
              if (resp.data.data === true) {
                this.$message.success('添加成功！')
                this.dialogFormVisible = false
                this.getRoleList()
              } else {
                this.$message.error(resp.data.msg)
              }
            })
            .catch((error) => {
              this.$message({ type: 'error', message: error })
            })
        }
      })
    },
    // 编辑保存角色
    editSaveRole() {
      editRolePermission(this.addRoleForm)
        .then((resp) => {
          if (resp.data.data === true) {
            this.dialogFormVisible = false
            this.$message.success('修改成功！')
            this.getRoleList()
          } else {
            this.$message.error(resp.data.msg)
          }
        })
        .catch((error) => {
          this.$message({ type: 'error', message: error })
        })
    },
    handleSizeChange(newSize) {
      this.queryModuleInfo.pageSize = newSize
      this.getRoleList()
    },
    handleCurrentChange(newPage) {
      this.queryModuleInfo.pageNum = newPage
      this.getRoleList()
    },
    // 判断本级菜单内的权限是否一个都没选
    isMenuNone(_index) {
      let menu = this.allPermissionList[_index].permissionList
      let result = true
      for (let i = 0; i < menu.length; i++) {
        if (this.addRoleForm.permissionIdList.indexOf(menu[i].id) > -1) {
          result = false
          break
        }
      }
      return result
    },
    isMenuAll(_index) {
      // 判断本级菜单内的权限是否全选了
      let menu = this.allPermissionList[_index].permissionList
      let result = true
      for (let j = 0; j < menu.length; j++) {
        if (this.addRoleForm.permissionIdList.indexOf(menu[j].id) < 0) {
          result = false
          break
        }
      }
      return result
    },
    checkAll(_index) {
      // 点击菜单相当于全选按钮
      let v = this
      if (v.isMenuAll(_index)) {
        // 如果已经全选了,则全部取消
        v.noPerm(_index)
      } else {
        // 如果尚未全选,则全选
        v.allPerm(_index)
      }
    },
    noPerm(_index) {
      // 全部取消选中
      let menu = this.allPermissionList[_index].permissionList
      for (let j = 0; j < menu.length; j++) {
        let idIndex = this.addRoleForm.permissionIdList.indexOf(menu[j].id)
        if (idIndex > -1) {
          this.addRoleForm.permissionIdList.splice(idIndex, 1)
        }
      }
    },
    allPerm(_index) {
      // 全部选中
      let menu = this.allPermissionList[_index].permissionList
      for (let j = 0; j < menu.length; j++) {
        this.addUnique(menu[j].id, this.addRoleForm.permissionIdList)
      }
    },
    addUnique(val, arr) {
      // 数组内防重复地添加元素
      let _index = arr.indexOf(val)
      if (_index < 0) {
        arr.push(val)
      }
    }
  }
}
</script>
<style lang="less" scoped>
</style>
