<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!-- 角色列表 -->
      <el-col :xs="24" :sm="24" :md="18" :lg="18" :xl="18" style="margin-bottom: 10px">
        <el-card class="box-card">
          <el-form ref="searchForm" :model="searchForm" label-width="80px">
            <div style="margin-bottom: 10px;">
              <el-row style="line-height: 40px; text-align: right;">
                <el-col :span="3"><label class="search-label">角色名称</label></el-col>
                <el-col :span="8">
                  <el-input v-model.trim="searchForm.name" placeholder="请输入角色名称" clearable @keyup.enter.native="list" />
                </el-col>
                <el-col :offset="10" :span="2">
                  <el-button size="small" type="primary" icon="el-icon-search" @click="list">搜索</el-button>
                </el-col>
              </el-row>
            </div>
          </el-form>
          <el-row>
            <white-board>
              <el-row>
                <el-col style="text-align: right;">
                  <el-button size="small" icon="el-icon-plus" type="success" plain @click="handleAdd">新增</el-button>
                </el-col>
              </el-row>

              <el-row style="padding: 10px 0px;">
                <el-table :data="tableData" style="width: 100%;" highlight-current-row stripe @current-change="handleSelectChange">
                  <el-table-column prop="id" label="标识" width="150" />
                  <el-table-column prop="name" label="角色名称" show-overflow-tooltip />
                  <el-table-column prop="remarks" label="备注" show-overflow-tooltip />
                  <el-table-column label="操作" width="150" fixed="right">
                    <template slot-scope="scope">
                      <el-button size="small" type="primary" plain @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                      <el-button v-if="!scope.row.isDel" size="small" type="danger" plain @click="handleIsDel(scope.$index, scope.row)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </white-board>
          </el-row>

          <el-row>
            <el-pagination :current-page="searchForm.page" :page-sizes="[10, 20, 50, 100]" :page-size="50" layout="total, sizes, prev, pager, next, jumper" :total="total" small @size-change="changeSizeChange" @current-change="changeCurrentChange" />
          </el-row>
        </el-card>
      </el-col>
      <!-- 菜单分配列表 -->
      <el-col :xs="24" :sm="24" :md="6" :lg="6" :xl="6">
        <el-card class="box-card">
          <div slot="header" class="clearfix">
            <span>菜单分配</span>
          </div>
          <el-row>
            <el-col style="text-align: right;">
              <el-button size="small" icon="el-icon-check" type="success" plain @click="handleSave">保存</el-button>
            </el-col>
          </el-row>
          <el-row style="padding: 10px 0px;">
            <el-tree
              ref="tree"
              :props="props"
              node-key="value"
              show-checkbox
              :default-checked-keys="checkedMenus"
              :data="menuData"
            /></el-row>
        </el-card>
      </el-col>
    </el-row>

    <edit-role-dialog :visible="dialogVisible" :dialog-title="dialogTitle" :form="form" @cancelDialog="cancelDialog" @refresh="list" />
  </div>
</template>

<script>
import EditRoleDialog from '@/views/platform/system/role/editRoleDialog'
import roleApi from '@/api/platform/roleApi'

export default {
  name: 'RoleIndex',
  components: {
    'edit-role-dialog': EditRoleDialog
  },
  data() {
    return {
      dialogTitle: '',
      dialogVisible: false,
      total: 0,
      tableData: [],
      selectedRoleId: '',
      checkedMenus: [],
      props: {
        children: 'children',
        label: 'label'
      },
      form: {
        id: '',
        name: '',
        deptIds: [],
        remarks: ''
      },
      searchForm: {
        name: '',
        isDel: false,
        page: 1,
        size: 50
      },
      menuData: []
    }
  },
  mounted() {
    this.list()
    this.getMenuNodes()
  },
  methods: {
    list() {
      this.selectedRoleId = ''
      this.tableData = []
      // 清除菜单选中
      this.checkedMenus = []
      this.$refs.tree.setCheckedKeys([])
      roleApi.page(this.searchForm).then(data => {
        this.total = data.total
        this.tableData = data.data
      })
    },
    getMenuNodes() {
      roleApi.menuNodes().then(data => {
        this.menuData = data
      })
    },
    handleSave() {
      if (this.selectedRoleId === '') {
        this.$message('请先选中一个角色')
        return
      }
      const f = {
        roleId: this.selectedRoleId,
        menuIds: []
      }
      // 获取选中的节点（不包括半选中的节点）
      let c = this.$refs.tree.getCheckedNodes()
      // 实现效果：如果子节点的父节点被选中（父节点的子节点元素被全选），则获取父节点消息，如果没有全部选中，则获取子节点
      // 实现原理：如果节点有父节点且父节点被选中了，那么这个父节点就是为全选的状态的，使用数组过滤，可得出结果
      c = Array.from(c).filter(item => !(item.parent && item.parent.checked))
      Array.from(c).forEach(node => {
        f.menuIds.push(node.id)
      })
      roleApi.saveMenu(f).then(() => {
        this.$message({
          message: '保存成功',
          type: 'success'
        })
        this.list()
      })
    },
    handleAdd() {
      this.form = {
        id: '',
        name: '',
        deptIds: [],
        remarks: ''
      }
      this.dialogTitle = '新增'
      this.dialogVisible = true
    },
    handleIsDel(index, row) {
      roleApi.handleIsDel(row.id).then(data => {
        this.list()
      })
    },
    handleEdit(index, row) {
      this.form = JSON.parse(JSON.stringify(row))
      this.dialogTitle = '编辑'
      this.dialogVisible = true
    },
    changeSizeChange(val) {
      this.searchForm.size = val
      this.list()
    },
    changeCurrentChange(val) {
      this.searchForm.page = val
      this.list()
    },
    cancelDialog(visible) {
      this.dialogVisible = visible
    },
    handleSelectChange(val) {
      this.selectedRoleId = val.id
      // 清除菜单选中
      this.$refs.tree.setCheckedKeys([])
      this.checkedMenus = val.menuIds
    }
  }
}
</script>

<style scoped>
</style>
