web
2025-03-19 ae8d9d380854076d0b2da145576ae08f14a8f835
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
<!--
 * @Author: Liuyi candymxq888@outlook.com
 * @Date: 2024-08-06 16:17:39
 * @LastEditors: Liuyi candymxq888@outlook.com
 * @LastEditTime: 2024-10-23 14:21:49
 * @FilePath: \water-qinghe-web\src\views\system\user\index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <div class="app-container">
       <el-form :model="queryParams" ref="queryRef" :inline="true">
          <el-form-item label="角色名称" prop="name">
             <el-input
                v-model="queryParams.name"
                placeholder="请输入角色名称"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
             />
          </el-form-item>
          <el-form-item>
             <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
             <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
       </el-form>
 
       <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
             <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
             >新增</el-button>
          </el-col>
       </el-row>
       <!--表格及分页-->
       <el-table v-loading="loading" :data="tableData">
          <el-table-column
            v-for="(item, key, index) of tableHeader"
            :prop="key.toString()"
            :label="item"
            :key="index"
            align="center"
          >
        </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
             <template #default="scope">
                <el-button link type="primary" icon="Edit" @click="handlePermission(scope.row)">权限分配</el-button>
                <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-has="['update',route]">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-has="['delete',route]">删除</el-button>
             </template>
          </el-table-column>
        </el-table>
        <pagination
          :total="pageParam.total"
          v-model:page="pageParam.page"
          v-model:limit="pageParam.limit"
          :page-sizes="[10,20,30]"
          @pagination="getList"
        />
       <!-- 添加或修改对话框 -->
       <el-dialog :title="title" v-model="open" append-to-body center>
          <el-form class="form-box" ref="roleRef" :model="form" :rules="rules" label-width='auto'>
                   <el-form-item label="角色名称" prop="name">
                      <el-input v-model="form.name" placeholder="请输入角色名称"/>
                   </el-form-item>
                   <el-form-item label="描述" prop="description">
                      <el-input v-model="form.description" placeholder="请输入内容" />
                   </el-form-item>
                    <el-form-item label="排序" prop="sort">
                     <el-input-number v-model="form.sort" controls-position="right" :min="0" />
                   </el-form-item>
                    <el-form-item></el-form-item>
          </el-form>
          <template #footer>
             <div class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
             </div>
          </template>
       </el-dialog>
       <el-dialog title="权限分配" v-model="openPermission" append-to-body center @close="cancelPermission">
         <div class="permission-box">
                    <div class="tree-box">
                        <div class="check-top">
                            <el-checkbox v-model="allMenuChecked" @change="checkedAllMenu()">已选菜单</el-checkbox>
                            <div style="font-size: 14px;">{{checkedMenusList.length}}/{{ menuTreeListLength }}</div>
                        </div>
                        <el-tree
                            ref="treeMenuRef"
                            :data="menuTreeList"
                            show-checkbox
                            :default-expand-all = false
                            :default-checked-keys="defaultMenu"
                            node-key="id"
                            :props="{label:'name'}"
                            highlight-current
                            @check="changeMenu"
                        />
                    </div>
                    <div class="btn-box">
                        <div class="check-top">
                            <el-checkbox v-model="allPermChecked" @change="checkedAllPermission()" >已选权限</el-checkbox>
                            <div style="font-size: 14px;">{{checkedPermissionList.length}}/{{ showPermissionList.length }}</div>
                        </div>
                        <el-checkbox-group v-model="checkedPermissionList" @change="changePermission">
                            <el-checkbox :label="item.id" v-for="item in showPermissionList">{{item.name}}</el-checkbox>
                        </el-checkbox-group>
                    </div>
                </div>
               <template #footer>
                  <div class="dialog-footer">
                     <el-button type="primary" @click="submitPermission">确 认</el-button>
                     <el-button @click="cancelPermission">取 消</el-button>
                  </div>
               </template>
       </el-dialog>
    </div>
 </template>
 
 <script setup name="Menu">
 import  role from "@/api/system/role";
 import  menu from "@/api/system/menu";
 import  permission from "@/api/system/permission";
 import  { useRoute } from "vue-router";
 import setPostParams from "@/utils/searchParams.js";
 
 const { proxy } = getCurrentInstance();
 let route = useRoute()
 
/**
 * 搜索相关
 */
 /** 搜索按钮操作 */
 function handleQuery() {
   getList({keywords:queryParams.value.name,page:1})
 }
 
 /** 重置按钮操作 */
 function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
 }
 
 /**
  *  Table表格数据列表相关
  */
 
const pageParam = ref({
    total:0,
    limit:0,
    page:0,
})
const tableData = ref([]);
let  tableHeader = ref({
      name: '角色名称',
      description: '描述',
      sort:'排序',
   })
 /** 获取列表 */
 async function getList(val) {
      loading.value = true;
     let postParam = setPostParams(val)
      await role().search(postParam).then((res) =>{
        tableData.value = res.data.list
        pageParam.value.total = res.data.total
        pageParam.value.limit = res.data.limit
        pageParam.value.page = res.data.page
    })
    loading.value = false;
 }
 
 /** 新增按钮操作 */
 async function handleAdd() {
   reset();
   open.value = true;
   title.value = "新增角色";
 }
 
 /** 修改按钮操作 */
 async function handleUpdate(row) {
   reset();
   Object.keys(row).forEach(key => {  
      if (form.value.hasOwnProperty(key)) {  
         form.value[key] = row[key];  
      }  
   });
   form.value.id = row.id
   open.value = true;
   title.value = "修改角色";
 }
 
/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项?').then(function() {
    return role().remove(row.id);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}
 
 /**
  *  新增/修改弹窗Form表单相关
  */
const open = ref(false);
const loading = ref(false);
const title = ref("");
 
const data = reactive({
form:{},
queryParams: {
    name: undefined,
},
rules: {
    name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
    description: [{ required: true, message: "请输入密码", trigger: "blur" }],
},
});
const { queryParams, form, rules } = toRefs(data);
 
 /** 提交按钮 */
 function submitForm() {
   proxy.$refs["roleRef"].validate(valid => {
     if (valid) {
       if (form.value.id != undefined) {
         role().modify(form.value).then(res => {
           proxy.$modal.msgSuccess("修改成功");
           open.value = false;
           getList();
         }).catch(() =>{
            open.value = false;
            proxy.$modal.msgError("修改失败");
         });
       } else {
         role().create(form.value).then(res => {
           proxy.$modal.msgSuccess("新增成功");
           open.value = false;
           getList();
         }).catch(() =>{
            open.value = false;
            proxy.$modal.msgError("新增失败");
         });;
       }
     }
   });
 }
 
 /** 取消按钮 */
 function cancel() {
   open.value = false;
   reset();
 }
 
 /** 表单重置 */
 function reset() {
   form.value = {
        name: '',
        description: '',
        sort: 0,
   };
   proxy.resetForm("roleRef");
 }
 getList();
 
/**
 * 权限分配弹窗相关
 * 
 */
   //控制弹窗
   const userType = JSON.parse(localStorage.getItem('userType'))
   const openPermission = ref(false)
   let treeMenuRef = ref([])
   // let permissionData = ref()
   //菜单
   let menuTreeList = ref([]) //树形菜单(总数据)
   let checkedMenusList = ref([]) //已勾选菜单
   let allMenuChecked = ref(false) //菜单全选状态
   let defaultMenu = ref([]) //回显菜单
   let menuTreeListLength = ref([]) //菜单长度(节点数)
   //按钮权限
   let permissionList = ref([]) //权限列表(总数据)
   let showPermissionList = ref([]) //勾选菜单显示-对应权限
   let checkedPermissionList = ref([]) //已勾选权限
   let allPermChecked = ref(false) //权限全选状态
   //提交权限数据
   let permissionObject = {
         id:'',
         listMenu:'',
         listPermission:'',
      }
    //获取菜单和权限列表数据
   const getPerAndMenuList = async() =>{
      await menu().getListTree().then((res) =>{
         //普通用户和普通管理员筛除系统管理权限
         if(!userType.value == 1){
            res.data.forEach((item,index) =>{
               if(item.id == 10001){
                  res.data.splice(index,1)
               }
            })
            menuTreeList.value = res.data
         }
         menuTreeListLength.value = countTreeNodes(menuTreeList.value)
 
      })
      await permission().search({limit:100}).then((res) =>{
         permissionList.value = res.data.list
      })
   }
 
   /**权限分配按钮*/
   async function handlePermission(row){
      openPermission.value = true
      permissionObject.id = row.id
      await role().getListMenuAndPermission(row.id).then((res) =>{
         //设置选中菜单数据
         let menuList = []
         res.data.menus.forEach((item) =>{
            menuList.push(item.id)
         })
         checkedMenusList.value = menuList
         //设置已选择菜单,显示选项
         //因为tree组件默认勾选只要子级id,如果加入了父级id会把当前父级下的子级全部勾选,所以先找出子级id放默认数组
         let childMenu = []
            res.data.menus.forEach((obj) => {
                // 检查当前对象是否有子级
                let hasChildren = res.data.menus.some((child) => child.parentId === obj.id);
                // 如果没有子级,则将当前对象添加到最后一级对象数组中
                if (!hasChildren) {
                    childMenu.push(obj);
                }
            });
            defaultMenu.value = childMenu.map((obj) => obj.id); //返回id数组
            isAllChecked()
 
          //根据菜单显示权限数据
         showPermissionList.value = permissionList.value.filter(( item ) => menuList.includes(item.menuId))
         let list = []
         res.data.permissions.forEach((item) =>{
            list.push(item.id)
         })
         checkedPermissionList.value = list
      })
   }
 
   //已选菜单
   const changeMenu = () =>{
      getShowPermission()
      //点击菜单时,过滤不属于已选菜单项的已选择的权限,不过滤无法自动取消
      let list = []
      checkedPermissionList.value.forEach((checkedItem) =>{
         showPermissionList.value.forEach((item) =>{
          if(item.id == checkedItem ){
            list.push(checkedItem)
          }
         })
      })
       checkedPermissionList.value =  list
       isAllChecked()
   }
   //全选菜单
   const checkedAllMenu = () =>{
      if(allMenuChecked.value == true){
         let list = []
         menuTreeList.value.forEach(( item ) => list.push( item.id ))
         treeMenuRef.value.setCheckedKeys(list, false)
         //根据已选菜单并显示对应权限
         getShowPermission()  
         }else{
            treeMenuRef.value.setCheckedKeys([], false)
            checkedMenusList.value = []
            showPermissionList.value = []
            allPermChecked.value = false
         }
   }
   //判断菜单是否全选,控制全选项
   const isAllChecked = () =>{
         if(menuTreeListLength.value == checkedMenusList.value.length){ 
            allMenuChecked.value = true
         }else{
            allMenuChecked.value = false
         }
       }
   //已选权限
   const changePermission = (list) =>{
      console.log('permissionCurrent',list);
   }
   //全选权限
   const checkedAllPermission = () =>{
      if(allPermChecked.value == true && showPermissionList.value.length > 0){
      let list = []
      showPermissionList.value.forEach((item) => list.push(item.id))
      checkedPermissionList.value = list
      }else{
         checkedPermissionList.value = []
      }
      // console.log('checkedPermissionList.value',checkedPermissionList.value);
   }
   //基于已选菜单显示按钮权限
   const getShowPermission = () =>{
      //选中菜单
      checkedMenusList.value = treeMenuRef.value.getCheckedKeys(false).concat(treeMenuRef.value.getHalfCheckedKeys())
       //根据菜单显示权限
      showPermissionList.value = permissionList.value.filter(( item ) => checkedMenusList.value.includes(item.menuId))
   }
   //遍历树形节点拿到树形数组长度(节点数)
    const countTreeNodes = (tree) => {
        let count = 0;
        const traverse = (node) => {
            // 每遍历一个节点,计数加一
            count++;
            // 如果当前节点有子节点,则递归遍历子节点
            if (node.children && node.children.length > 0) {
                node.children.forEach((child) => traverse(child));
            }
        }
        // 遍历树形结构的每个根节点
        tree.forEach((node) => traverse(node));
        return count;
    }
    //提交分配权限
    const submitPermission = async() =>{
      permissionObject.listMenu = checkedMenusList.value
      permissionObject.listPermission = checkedPermissionList.value
      await role().setListMenuAndPermission(permissionObject).then((res) =>{
         // console.log('res',res);
      })
      cancelPermission()
    }
    //取消分配权限
    const cancelPermission = () =>{
      openPermission.value = false
      showPermissionList.value = []
      checkedPermissionList.value = []
      checkedMenusList.value = []
      treeMenuRef.value.setCheckedKeys([], false)
    }
 
   getList();
   getPerAndMenuList()
 </script>
 <style>
 .permission-box{
   display: flex;
   width: 100%;
   height:600px;
   justify-content: space-around;
   .tree-box{
      width: 48%;
      height:90%;
      background-color: white;
       overflow-y: auto;
   }
   .btn-box{
      width: 48%;
      height:90%;
      display: flex;
      flex-direction: column;
      background-color: rgb(255, 255, 255);
   }
   .check-top{
      background-color: rgb(223, 234, 245);
      border-radius: 10px 10px 0 0;
      display:flex;
      justify-content:space-between;
      align-items: center;
      padding: 0 10px;
      }
 
 }
 .el-checkbox-group {
     height: 100%;
     overflow-y: auto;
     .el-checkbox {
         width: 100%;
         margin: 0;
         height: 26px;
         padding-left: 18px;
         box-sizing: border-box;
         .el-checkbox__label {
             font-size: 14px;
         }
 
     }
 }
</style>