<template>
  <div class="Role-management">
    <!-- 左侧 -->
    <div class="left-content">
      <el-button class="newly-added" type="success" @click="newlyadded">新增</el-button>
      <LTable class="leftTable" @handleRowClick="tablerow" :dataSource="lefttableData" ref="Ltable" :options="options" :columns="columns"></LTable>
    </div>

    <!-- 右侧 -->
    <div class="right-content">
      <div class="right-title">{{ rightrolename }}</div>
      <div class="right-table">
        <div class="right-table-btn">
          <el-button type="success" @click="adduserechodata">添加</el-button>
          <el-button type="warning" @click="deletuser">删除</el-button>
        </div>
        <LTable :fetch="initGetlistByRoleId" class="rightTable" @select-all="selectAll" @selection-change="selection" :pagination="pagination" :dataSource="rightTableData" ref="Rtable" :options="rightOptions" :columns="rightColumns"></LTable>
      </div>
    </div>

    <!-- 配置菜单弹出框 -->
    <el-dialog v-if="menuDialog" title="配置菜单" :visible="menuDialog" :before-close="menuDialogClose" width="400px" :close-on-click-modal="false" modal-append-to-body custom-class="newly-added-dialog">
      <el-scrollbar style="height: 300px">
        <el-tree ref="treeref" :data="menutreedata" show-checkbox node-key="id" default-expand-all :default-checked-keys="checkedArr" :props="defaultProps"> </el-tree>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="menuDialogClose">取 消</el-button>
        <el-button type="primary" @click="menuConfirm">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 新增弹出框 -->
    <el-dialog :visible="dialogDialog" width="420px" :before-close="lconmaskoff" :close-on-click-modal="false" modal-append-to-body custom-class="newly-added-dialog">
      <template slot="title">
        <span>{{ dyncmictitle }}</span>
      </template>
      <el-form ref="addroleform" status-icon class="Add-role-form" :model="Addroleform" :rules="Addrolerules">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="Addroleform.roleName" placeholder="请填写角色名称" />
        </el-form-item>
        <el-form-item label="角色标识" prop="roleKey">
          <el-input v-model="Addroleform.roleKey" placeholder="默认角色标识全拼" />
        </el-form-item>
        <el-form-item label="角色描述" prop="remark">
          <el-input :rows="4" type="textarea" v-model="Addroleform.remark" placeholder="默认角色描述" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer" style="text-align: center">
        <el-button @click="lconmaskoff()">取 消</el-button>
        <el-button type="primary" @click="determine('addroleform')">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加用户弹出框 -->
    <AddUserDialog ref="AddUserDialog" @handerClick="handerClick" :activeRow="activeRow" />
  </div>
</template>

<script>
import { useMessage } from '@/utils/element-ui'
import { roleList, addRole, addEdit, menuList, roleDelete, listByRoleId, userList, cancelAll, selectAll, roleAuthMenu } from '@/api/system/role'
import { Addrolerules, options, columns, rightOptions, rightColumns } from './index'
import { deepClone } from '@/utils/index'
import { getMenusData } from '@/utils/route'
export default {
  name: 'Role',
  components: {},
  data() {
    return {
      columns: columns(this),
      options,
      rightOptions,
      rightColumns: rightColumns(this),
      roleCheckedItem: '',
      menuDialog: false,
      menutreedata: getMenusData(),
      checkedArr: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },

      rightrolename: '',
      addeditstatus: null,
      activeRow: null,
      lefttableData: [],
      dialogDialog: false,
      Addroleform: {
        roleName: '',
        remark: '',
        roleKey: ''
      },
      Addrolerules,
      rightTableData: [],
      multipleSelection: [],
      pagination: {
        total: 0,
        pageSize: 10,
        pageIndex: 1
      },
      rightActiveArr: []
    }
  },
  computed: {
    dyncmictitle() {
      if (this.addeditstatus == '新增') {
        return '添加角色'
      }
      if (this.addeditstatus == '编辑') {
        return '编辑角色'
      }
      return ''
    }
  },

  created() {
    this.getRoleList('created')
    this.getMenuList()
  },
  methods: {
    async initGetlistByRoleId() {
      let postData = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.pageIndex,
        roleId: this.activeRow.roleId
      }

      const { data, code } = await listByRoleId(postData)
      if (code == 200) {
        this.rightTableData = data.list
        this.pagination.total = data.totalCount
      }
    },
    // 全选
    selectAll(data) {
      this.rightActiveArr = []
      if (data.length > 0) {
        data.forEach((item) => {
          this.rightActiveArr.push(item.userId)
        })
      } else {
        this.rightActiveArr = []
      }
    },
    // 单选
    selection(data) {
      this.rightActiveArr = []
      data.forEach((item) => {
        this.rightActiveArr.push(item.userId)
      })
    },
    async handerClick(activeArr) {
      let userIds = []
      activeArr.forEach((i) => {
        userIds.push(i.userId)
      })
      let postData = {
        roleId: this.activeRow.roleId,
        userIdArr: userIds
      }
      const { code } = await selectAll(postData)
      if (code == 200) {
        this.getlistByRoleId(this.activeRow.roleId)
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
      }
      this.$refs.Rtable.clearSelection()
      this.rightActiveArr = []
    },

    async getlistByRoleId(id) {
      let postData = {
        pageSize: this.pagination.pageSize,
        pageIndex: this.pagination.pageIndex,
        roleId: id
      }
      const { data, code } = await listByRoleId(postData)
      if (code == 200) {
        this.rightTableData = data.list
        this.pagination.total = data.totalCount
      }
    },
    async getMenuList() {
      const { data, code } = await menuList()
      if (code == 200) {
      }
    },
    async getRoleList(created) {
      const { rows, code } = await roleList()
      if (code == 200) {
        this.lefttableData = rows
        if (created && this.lefttableData[0]) {
          this.tablerow(this.lefttableData[0])
          this.$refs.Ltable.setCurrentRow(this.lefttableData[0])
        }
      }
    },
    // 操作栏点击配置菜单
    menuClick(val) {
      this.menuDialog = true
      //  赋值给当前选中
      this.roleCheckedItem = val.row
      this.checkedArr = val.row.permissions
    },
    // 配置菜单弹框确认按钮
    async menuConfirm() {
      const arr = this.$refs.treeref.getCheckedNodes()
      const result = arr.map((item) => {
        if (!item.children) {
          return item.id
        }
      })
      const orderResult = result.filter((item) => item !== undefined)
      let params = {
        roleId: this.roleCheckedItem.roleId,
        menuKeyList: orderResult
      }
      await roleAuthMenu(params)
      this.getRoleList('created')
      useMessage('success', '配置成功')
      this.menuDialog = false
      location.reload()
    },

    // 添加用户回显数据接口
    adduserechodata() {
      if (this.activeRow) {
        this.$refs.AddUserDialog.opneDialog()
      } else {
        useMessage('warning', '请在左边点击一条数据，再做新增！')
      }
    },

    tablerow(row) {
      this.rightrolename = row.roleName + '列表'
      this.activeRow = row
      this.pagination.pageIndex = 1
      this.getlistByRoleId(row.roleId)
      this.$refs.Rtable.clearSelection()
      this.rightActiveArr = []
    },
    lconmaskoff() {
      this.dialogDialog = false
      this.$refs['addroleform'].resetFields()
      this.Addroleform = {
        roleName: '',
        remark: '',
        roleKey: ''
      }
    },
    // 关闭配置菜单
    menuDialogClose() {
      this.menuDialog = false
    },
    cancel(fromName) {
      this.dialogDialog = false
      this.$refs[fromName].resetFields()
    },
    handRemove(row) {
      this.$confirm('是否确认删除该数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          const { code } = await roleDelete(row.roleId)
          if (code == 200) {
            this.getRoleList()
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
        })
        .catch(() => {})
    },
    // 编辑
    edit(slode) {
      this.addeditstatus = '编辑'
      this.dialogDialog = true
      const row = slode.row
      this.Addroleform = deepClone(row)
    },
    // 新增，编辑提交按钮
    determine(addroleform) {
      this.$refs[addroleform].validate(async (valid) => {
        if (valid) {
          // 表单校验成功
          if (this.addeditstatus == '新增') {
            const { code } = await addRole(this.Addroleform)
            if (code == 200) {
              useMessage('success', '新增角色成功')
              this.dialogDialog = false
              this.$refs[addroleform].resetFields()
              this.getRoleList()
            }
          } else if (this.addeditstatus == '编辑') {
            const { code } = await addEdit(this.Addroleform)
            if (code == 200) {
              useMessage('success', '编辑角色成功')
              this.dialogDialog = false
              this.$refs[addroleform].resetFields()
              this.getRoleList()
            }
          }
        } else {
          // 表单校验失败
          return false
        }
      })
    },

    // 新增按钮
    newlyadded() {
      this.addeditstatus = '新增'
      this.dialogDialog = true
      this.Addroleform.roleName = ''
      this.Addroleform.remark = ''
      this.Addroleform.roleKey = ''
    },

    // 批量删除
    deletuser() {
      this.$confirm('是否确认删除选中数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let postData = {
            roleId: this.activeRow.roleId,
            userIdArr: this.rightActiveArr
          }
          const { code } = await cancelAll(postData)
          if (code == 200) {
            this.getlistByRoleId(this.activeRow.roleId)
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
          }
          this.$refs.Rtable.clearSelection()
          this.rightActiveArr = []
        })
        .catch(() => {})
    },
    handleSelection(val) {
      this.multipleSelection = val
    }
  }
}
</script>

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