zhou zhou
2026-04-13 adb016e4492d927ed3eb9fc098294ffc81c06ae3
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
490
491
492
493
494
495
496
497
498
499
500
501
<!-- 用户管理页面 -->
<template>
  <div class="user-page art-full-height">
    <UserSearch
      v-model="searchForm"
      :dept-tree-options="deptTreeOptions"
      :role-options="roleOptions"
      @search="handleSearch"
      @reset="handleReset"
    />
 
    <ElCard class="art-table-card">
      <ArtTableHeader v-model:columns="columnChecks" :loading="loading" @refresh="refreshData">
        <template #left>
          <ElSpace wrap>
            <ElButton v-auth="'add'" @click="showDialog('add')" v-ripple>新增用户</ElButton>
            <ElButton
              v-auth="'delete'"
              type="danger"
              :disabled="selectedRows.length === 0"
              @click="handleBatchDelete"
              v-ripple
            >
              批量删除
            </ElButton>
            <ElButton v-auth="'query'" :loading="exportLoading" @click="handleExport" v-ripple
              >导出</ElButton
            >
          </ElSpace>
        </template>
      </ArtTableHeader>
 
      <ArtTable
        :loading="loading"
        :data="data"
        :columns="columns"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @pagination:size-change="handleSizeChange"
        @pagination:current-change="handleCurrentChange"
      />
 
      <UserDialog
        v-model:visible="dialogVisible"
        :type="dialogType"
        :user-data="currentUserData"
        :role-options="roleOptions"
        :dept-tree-options="deptTreeOptions"
        @submit="handleDialogSubmit"
      />
 
      <UserDetailDrawer
        v-model:visible="detailDrawerVisible"
        :loading="detailLoading"
        :user-data="detailUserData"
      />
    </ElCard>
  </div>
</template>
 
<script setup>
  import request from '@/utils/http'
  import { guardRequestWithMessage } from '@/utils/sys/requestGuard'
  import { useUserStore } from '@/store/modules/user'
  import {
    fetchDeleteUser,
    fetchExportUserReport,
    fetchGetDeptTree,
    fetchGetRoleOptions,
    fetchGetUserDetail,
    fetchResetUserPassword,
    fetchSaveUser,
    fetchUpdateUser,
    fetchUpdateUserStatus
  } from '@/api/system-manage'
  import { useTable } from '@/hooks/core/useTable'
  import { useAuth } from '@/hooks/core/useAuth'
  import ArtButtonTable from '@/components/core/forms/art-button-table/index.vue'
  import { ElMessage, ElMessageBox, ElSwitch, ElTag } from 'element-plus'
  import UserSearch from './modules/user-search.vue'
  import UserDialog from './modules/user-dialog.vue'
  import UserDetailDrawer from './modules/user-detail-drawer.vue'
  import {
    buildUserDialogModel,
    buildUserPageQueryParams,
    buildUserSavePayload,
    buildUserSearchParams,
    createUserSearchState,
    getUserPaginationKey,
    getUserStatusMeta,
    mergeUserDetailRecord,
    normalizeDeptTreeOptions,
    normalizeRoleOptions,
    normalizeUserListRow,
    formatUserRoleNames
  } from './userPage.helpers'
 
  defineOptions({ name: 'User' })
 
  const searchForm = ref(createUserSearchState())
  const dialogType = ref('add')
  const dialogVisible = ref(false)
  const currentUserData = ref(buildUserDialogModel())
  const detailDrawerVisible = ref(false)
  const detailLoading = ref(false)
  const detailUserData = ref({})
  const selectedRows = ref([])
  const roleOptions = ref([])
  const deptTreeOptions = ref([])
  const exportLoading = ref(false)
  const RESET_PASSWORD = '123456'
  const { hasAuth } = useAuth()
  const userStore = useUserStore()
 
  const fetchUserPage = (params = {}) => {
    return request.post({
      url: '/user/page',
      params: buildUserPageQueryParams(params)
    })
  }
 
  const {
    columns,
    columnChecks,
    data,
    loading,
    pagination,
    getData,
    replaceSearchParams,
    resetSearchParams,
    handleSizeChange,
    handleCurrentChange,
    refreshData,
    refreshCreate,
    refreshUpdate,
    refreshRemove
  } = useTable({
    core: {
      apiFn: fetchUserPage,
      apiParams: buildUserPageQueryParams(searchForm.value),
      paginationKey: getUserPaginationKey(),
      columnsFactory: () => [
        {
          type: 'selection',
          width: 52,
          fixed: 'left',
          align: 'center'
        },
        {
          prop: 'username',
          label: '用户名',
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'nickname',
          label: '昵称',
          minWidth: 120,
          showOverflowTooltip: true
        },
        {
          prop: 'deptLabel',
          label: '部门',
          minWidth: 140,
          showOverflowTooltip: true
        },
        {
          prop: 'phone',
          label: '手机号',
          minWidth: 130
        },
        {
          prop: 'email',
          label: '邮箱',
          minWidth: 180,
          showOverflowTooltip: true
        },
        {
          prop: 'roleNames',
          label: '角色',
          minWidth: 180,
          showOverflowTooltip: true,
          formatter: (row) => formatUserRoleNames(row.roles) || row.roleNames || '-'
        },
        {
          prop: 'status',
          label: '状态',
          width: 180,
          formatter: (row) => {
            const statusMeta = getUserStatusMeta(row.statusBool ?? row.status)
            if (!hasAuth('edit')) {
              return h(ElTag, { type: statusMeta.type, effect: 'light' }, () => statusMeta.text)
            }
            return h('div', { class: 'flex items-center gap-2' }, [
              h(ElSwitch, {
                modelValue: row.statusBool ?? statusMeta.bool,
                loading: row._statusLoading,
                'onUpdate:modelValue': (value) => handleStatusChange(row, value)
              }),
              h(ElTag, { type: statusMeta.type, effect: 'light' }, () => statusMeta.text)
            ])
          }
        },
        {
          prop: 'updateTimeText',
          label: '更新时间',
          minWidth: 180,
          sortable: true,
          formatter: (row) => row.updateTimeText || '-'
        },
        {
          prop: 'createTimeText',
          label: '创建时间',
          minWidth: 180,
          sortable: true,
          formatter: (row) => row.createTimeText || '-'
        },
        {
          prop: 'operation',
          label: '操作',
          width: 220,
          fixed: 'right',
          formatter: (row) => {
            const buttons = []
 
            if (hasAuth('query')) {
              buttons.push(
                h(ArtButtonTable, {
                  type: 'view',
                  onClick: () => openDetail(row)
                })
              )
            }
 
            if (hasAuth('edit')) {
              buttons.push(
                h(ArtButtonTable, {
                  type: 'edit',
                  onClick: () => openEditDialog(row)
                }),
                h(ArtButtonTable, {
                  icon: 'ri:key-2-line',
                  iconClass: 'bg-warning/12 text-warning',
                  onClick: () => handleResetPassword(row)
                })
              )
            }
 
            if (hasAuth('delete')) {
              buttons.push(
                h(ArtButtonTable, {
                  type: 'delete',
                  onClick: () => handleDelete(row)
                })
              )
            }
 
            return h('div', buttons)
          }
        }
      ]
    },
    transform: {
      dataTransformer: (records) => {
        if (!Array.isArray(records)) {
          return []
        }
        return records.map((item) => normalizeUserListRow(item))
      }
    }
  })
 
  const loadLookups = async () => {
    try {
      const lookupPayload = await guardRequestWithMessage(
        Promise.all([fetchGetRoleOptions({}), fetchGetDeptTree({})]),
        null,
        {
          timeoutMessage: '用户页字典加载超时,已停止等待'
        }
      )
      if (!lookupPayload) {
        roleOptions.value = []
        deptTreeOptions.value = []
        return
      }
      const [roles, depts] = lookupPayload
      roleOptions.value = normalizeRoleOptions(roles)
      deptTreeOptions.value = normalizeDeptTreeOptions(depts)
    } catch (error) {
      console.error('加载用户页字典失败', error)
    }
  }
 
  onMounted(() => {
    loadLookups()
  })
 
  const handleSearch = (params) => {
    replaceSearchParams(buildUserSearchParams(params))
    getData()
  }
 
  const handleSelectionChange = (rows) => {
    selectedRows.value = Array.isArray(rows) ? rows : []
  }
 
  const handleReset = () => {
    Object.assign(searchForm.value, createUserSearchState())
    resetSearchParams()
  }
 
  const showDialog = (type, row) => {
    dialogType.value = type
    currentUserData.value = type === 'edit' ? buildUserDialogModel(row) : buildUserDialogModel()
    dialogVisible.value = true
  }
 
  const loadUserDetail = async (id) => {
    detailLoading.value = true
    try {
      return await fetchGetUserDetail(id)
    } finally {
      detailLoading.value = false
    }
  }
 
  const openEditDialog = async (row) => {
    try {
      const detail = await loadUserDetail(row.id)
      currentUserData.value = buildUserDialogModel(mergeUserDetailRecord(detail, row))
      dialogType.value = 'edit'
      dialogVisible.value = true
    } catch (error) {
      ElMessage.error(error?.message || '获取用户详情失败')
    }
  }
 
  const openDetail = async (row) => {
    detailDrawerVisible.value = true
    try {
      detailUserData.value = mergeUserDetailRecord(await loadUserDetail(row.id), row)
    } catch (error) {
      detailDrawerVisible.value = false
      detailUserData.value = {}
      ElMessage.error(error?.message || '获取用户详情失败')
    }
  }
 
  const handleDialogSubmit = async (formData) => {
    const payload = buildUserSavePayload(formData)
    try {
      if (dialogType.value === 'edit') {
        await fetchUpdateUser(payload)
        ElMessage.success('修改成功')
        dialogVisible.value = false
        currentUserData.value = buildUserDialogModel()
        await refreshUpdate()
        return
      }
      await fetchSaveUser(payload)
      ElMessage.success('新增成功')
      dialogVisible.value = false
      currentUserData.value = buildUserDialogModel()
      await refreshCreate()
    } catch (error) {
      ElMessage.error(error?.message || '提交失败')
    }
  }
 
  const handleDelete = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除用户「${row.username || row.nickname || row.id}」吗?`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      await fetchDeleteUser(row.id)
      ElMessage.success('删除成功')
      await refreshRemove()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error?.message || '删除失败')
      }
    }
  }
 
  const handleBatchDelete = async () => {
    if (!selectedRows.value.length) return
    const ids = selectedRows.value
      .map((item) => item?.id)
      .filter((id) => id !== void 0 && id !== null)
 
    if (!ids.length) return
 
    try {
      await ElMessageBox.confirm(`确定要批量删除选中的 ${ids.length} 个用户吗?`, '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await fetchDeleteUser(ids.join(','))
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      await refreshRemove()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error?.message || '批量删除失败')
      }
    }
  }
 
  const handleResetPassword = async (row) => {
    try {
      await ElMessageBox.confirm(
        `确定将用户「${row.username || row.nickname || row.id}」的密码重置为 ${RESET_PASSWORD} 吗?`,
        '重置密码',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
      await fetchResetUserPassword({
        id: row.id,
        password: RESET_PASSWORD
      })
      ElMessage.success(`密码已重置为 ${RESET_PASSWORD}`)
      await refreshUpdate()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error(error?.message || '重置密码失败')
      }
    }
  }
 
  const handleStatusChange = async (row, checked) => {
    const previousStatus = row.status
    const previousStatusBool = row.statusBool
    const nextStatus = checked ? 1 : 0
    row._statusLoading = true
    row.status = nextStatus
    row.statusBool = checked
 
    try {
      await fetchUpdateUserStatus({
        id: row.id,
        status: nextStatus
      })
      ElMessage.success('状态已更新')
      await refreshUpdate()
    } catch (error) {
      row.status = previousStatus
      row.statusBool = previousStatusBool
      ElMessage.error(error?.message || '状态更新失败')
    } finally {
      row._statusLoading = false
    }
  }
 
  const handleExport = async () => {
    exportLoading.value = true
    try {
      const response = await guardRequestWithMessage(
        fetchExportUserReport(buildUserSearchParams(searchForm.value), {
          headers: {
            Authorization: userStore.accessToken || ''
          }
        }),
        null,
        {
          timeoutMessage: '用户导出超时,已停止等待'
        }
      )
      if (!response) {
        return
      }
      if (!response.ok) {
        throw new Error(`导出失败,状态码:${response.status}`)
      }
      const blob = await response.blob()
      const downloadUrl = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = downloadUrl
      link.download = 'user.xlsx'
      document.body.appendChild(link)
      link.click()
      link.remove()
      window.URL.revokeObjectURL(downloadUrl)
      ElMessage.success('导出成功')
    } catch (error) {
      ElMessage.error(error?.message || '导出失败')
    } finally {
      exportLoading.value = false
    }
  }
</script>