index.vue 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. <script setup lang="ts">
  2. import { onMounted, reactive, ref, unref, watch } from 'vue'
  3. import dayjs from 'dayjs'
  4. import {
  5. ElTag,
  6. ElInput,
  7. ElCard,
  8. ElTree,
  9. ElTreeSelect,
  10. ElSelect,
  11. ElOption,
  12. ElTransfer,
  13. ElForm,
  14. ElFormItem,
  15. ElUpload,
  16. ElSwitch,
  17. ElCheckbox,
  18. UploadInstance,
  19. UploadRawFile
  20. } from 'element-plus'
  21. import { handleTree } from '@/utils/tree'
  22. import { DICT_TYPE } from '@/utils/dict'
  23. import { useI18n } from '@/hooks/web/useI18n'
  24. import { useTable } from '@/hooks/web/useTable'
  25. import { FormExpose } from '@/components/Form'
  26. import type { UserVO } from '@/api/system/user/types'
  27. import type { PostVO } from '@/api/system/post/types'
  28. import type { PermissionAssignUserRoleReqVO } from '@/api/system/permission/types'
  29. import { listSimpleDeptApi } from '@/api/system/dept'
  30. import { listSimplePostsApi } from '@/api/system/post'
  31. import { listSimpleRolesApi } from '@/api/system/role'
  32. import { aassignUserRoleApi, listUserRolesApi } from '@/api/system/permission'
  33. import { rules, allSchemas } from './user.data'
  34. import * as UserApi from '@/api/system/user'
  35. import download from '@/utils/download'
  36. import { useRouter } from 'vue-router'
  37. import { CommonStatusEnum } from '@/utils/constants'
  38. import { getAccessToken, getTenantId } from '@/utils/auth'
  39. import { useMessage } from '@/hooks/web/useMessage'
  40. const message = useMessage()
  41. interface Tree {
  42. id: number
  43. name: string
  44. children?: Tree[]
  45. }
  46. const defaultProps = {
  47. children: 'children',
  48. label: 'name',
  49. value: 'id'
  50. }
  51. const { t } = useI18n() // 国际化
  52. // ========== 列表相关 ==========
  53. const tableTitle = ref('用户列表')
  54. const { register, tableObject, methods } = useTable<UserVO>({
  55. getListApi: UserApi.getUserPageApi,
  56. delListApi: UserApi.deleteUserApi,
  57. exportListApi: UserApi.exportUserApi
  58. })
  59. const { getList, setSearchParams, delList, exportList } = methods
  60. // ========== 创建部门树结构 ==========
  61. const filterText = ref('')
  62. const deptOptions = ref<any[]>([]) // 树形结构
  63. const searchForm = ref<FormExpose>()
  64. const treeRef = ref<InstanceType<typeof ElTree>>()
  65. const getTree = async () => {
  66. const res = await listSimpleDeptApi()
  67. deptOptions.value.push(...handleTree(res))
  68. }
  69. const filterNode = (value: string, data: Tree) => {
  70. if (!value) return true
  71. return data.name.includes(value)
  72. }
  73. const handleDeptNodeClick = (data: { [key: string]: any }) => {
  74. tableObject.params = {
  75. deptId: data.id
  76. }
  77. tableTitle.value = data.name
  78. methods.getList()
  79. }
  80. const { push } = useRouter()
  81. const handleDeptEdit = () => {
  82. push('/system/dept')
  83. }
  84. watch(filterText, (val) => {
  85. treeRef.value!.filter(val)
  86. })
  87. // ========== CRUD 相关 ==========
  88. const loading = ref(false) // 遮罩层
  89. const actionType = ref('') // 操作按钮的类型
  90. const dialogVisible = ref(false) // 是否显示弹出层
  91. const dialogTitle = ref('edit') // 弹出层标题
  92. const formRef = ref<FormExpose>() // 表单 Ref
  93. const deptId = ref(0) // 部门ID
  94. const postIds = ref<string[]>([]) // 岗位ID
  95. const postOptions = ref<PostVO[]>([]) //岗位列表
  96. // 获取岗位列表
  97. const getPostOptions = async () => {
  98. const res = await listSimplePostsApi()
  99. postOptions.value.push(...res)
  100. }
  101. // 设置标题
  102. const setDialogTile = async (type: string) => {
  103. dialogTitle.value = t('action.' + type)
  104. actionType.value = type
  105. dialogVisible.value = true
  106. }
  107. // 新增操作
  108. const handleAdd = () => {
  109. setDialogTile('create')
  110. // 重置表单
  111. deptId.value = 0
  112. unref(formRef)?.getElFormRef()?.resetFields()
  113. }
  114. // 修改操作
  115. const handleUpdate = async (row: UserVO) => {
  116. await setDialogTile('update')
  117. // 设置数据
  118. const res = await UserApi.getUserApi(row.id)
  119. deptId.value = res.deptId
  120. postIds.value = res.postIds
  121. unref(formRef)?.setValues(res)
  122. }
  123. // 提交按钮
  124. const submitForm = async () => {
  125. loading.value = true
  126. // 提交请求
  127. try {
  128. const data = unref(formRef)?.formModel as UserVO
  129. data.deptId = deptId.value
  130. data.postIds = postIds.value
  131. if (actionType.value === 'create') {
  132. await UserApi.createUserApi(data)
  133. message.success(t('common.createSuccess'))
  134. } else {
  135. await UserApi.updateUserApi(data)
  136. message.success(t('common.updateSuccess'))
  137. }
  138. // 操作成功,重新加载列表
  139. dialogVisible.value = false
  140. await getList()
  141. } finally {
  142. loading.value = false
  143. }
  144. }
  145. // 改变用户状态操作
  146. const handleStatusChange = async (row: UserVO) => {
  147. const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
  148. message
  149. .confirm('确认要"' + text + '""' + row.username + '"用户吗?', t('common.reminder'))
  150. .then(async () => {
  151. row.status =
  152. row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.ENABLE : CommonStatusEnum.DISABLE
  153. await UserApi.updateUserStatusApi(row.id, row.status)
  154. message.success(text + '成功')
  155. await getList()
  156. })
  157. .catch(() => {
  158. row.status =
  159. row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
  160. })
  161. }
  162. // 重置密码
  163. const handleResetPwd = (row: UserVO) => {
  164. message.prompt('请输入"' + row.username + '"的新密码', t('common.reminder')).then(({ value }) => {
  165. UserApi.resetUserPwdApi(row.id, value).then(() => {
  166. message.success('修改成功,新密码是:' + value)
  167. })
  168. })
  169. }
  170. // 分配角色
  171. const roleDialogVisible = ref(false)
  172. const roleOptions = ref()
  173. const userRole = reactive({
  174. id: 0,
  175. username: '',
  176. nickname: '',
  177. roleIds: []
  178. })
  179. const handleRole = async (row: UserVO) => {
  180. userRole.id = row.id
  181. userRole.username = row.username
  182. userRole.nickname = row.nickname
  183. // 获得角色拥有的权限集合
  184. const roles = await listUserRolesApi(row.id)
  185. userRole.roleIds = roles
  186. // 获取角色列表
  187. const roleOpt = await listSimpleRolesApi()
  188. roleOptions.value = roleOpt
  189. roleDialogVisible.value = true
  190. }
  191. // 提交
  192. const submitRole = async () => {
  193. const data = ref<PermissionAssignUserRoleReqVO>({
  194. userId: userRole.id,
  195. roleIds: userRole.roleIds
  196. })
  197. await aassignUserRoleApi(data.value)
  198. message.success(t('common.updateSuccess'))
  199. roleDialogVisible.value = false
  200. }
  201. // ========== 详情相关 ==========
  202. const detailRef = ref()
  203. // 详情操作
  204. const handleDetail = async (row: UserVO) => {
  205. // 设置数据
  206. detailRef.value = row
  207. await setDialogTile('detail')
  208. }
  209. // ========== 导入相关 ==========
  210. const importDialogVisible = ref(false)
  211. const uploadDisabled = ref(false)
  212. const importDialogTitle = ref('用户导入')
  213. const updateSupport = ref(0)
  214. let updateUrl = import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/system/user/import'
  215. const uploadHeaders = ref()
  216. // 下载导入模版
  217. const handleImportTemp = async () => {
  218. const res = await UserApi.importUserTemplateApi()
  219. download.excel(res, '用户导入模版.xls')
  220. }
  221. // 文件上传之前判断
  222. const beforeExcelUpload = (file: UploadRawFile) => {
  223. const isExcel =
  224. file.type === 'application/vnd.ms-excel' ||
  225. file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
  226. const isLt5M = file.size / 1024 / 1024 < 5
  227. if (!isExcel) message.error('上传文件只能是 xls / xlsx 格式!')
  228. if (!isLt5M) message.error('上传文件大小不能超过 5MB!')
  229. return isExcel && isLt5M
  230. }
  231. // 文件上传
  232. const uploadRef = ref<UploadInstance>()
  233. const submitFileForm = () => {
  234. uploadHeaders.value = {
  235. Authorization: 'Bearer ' + getAccessToken(),
  236. 'tenant-id': getTenantId()
  237. }
  238. uploadDisabled.value = true
  239. uploadRef.value!.submit()
  240. }
  241. // 文件上传成功
  242. const handleFileSuccess = (response: any): void => {
  243. if (response.code !== 0) {
  244. message.error(response.msg)
  245. return
  246. }
  247. importDialogVisible.value = false
  248. uploadDisabled.value = false
  249. const data = response.data
  250. let text = '上传成功数量:' + data.createUsernames.length + ';'
  251. for (let username of data.createUsernames) {
  252. text += '< ' + username + ' >'
  253. }
  254. text += '更新成功数量:' + data.updateUsernames.length + ';'
  255. for (const username of data.updateUsernames) {
  256. text += '< ' + username + ' >'
  257. }
  258. text += '更新失败数量:' + Object.keys(data.failureUsernames).length + ';'
  259. for (const username in data.failureUsernames) {
  260. text += '< ' + username + ': ' + data.failureUsernames[username] + ' >'
  261. }
  262. message.alert(text)
  263. }
  264. // 文件数超出提示
  265. const handleExceed = (): void => {
  266. message.error('最多只能上传一个文件!')
  267. }
  268. // 上传错误提示
  269. const excelUploadError = (): void => {
  270. message.error('导入数据失败,请您重新上传!')
  271. }
  272. // ========== 初始化 ==========
  273. onMounted(async () => {
  274. await getTree()
  275. await getPostOptions()
  276. })
  277. getList()
  278. </script>
  279. <template>
  280. <div class="flex">
  281. <el-card class="w-1/5 user" :gutter="12" shadow="always">
  282. <template #header>
  283. <div class="card-header">
  284. <span>部门列表</span>
  285. <el-button link class="button" type="primary" @click="handleDeptEdit">
  286. 修改部门
  287. </el-button>
  288. </div>
  289. </template>
  290. <el-input v-model="filterText" placeholder="搜索部门" />
  291. <el-tree
  292. ref="treeRef"
  293. node-key="id"
  294. default-expand-all
  295. :data="deptOptions"
  296. :props="defaultProps"
  297. :highlight-current="true"
  298. :filter-node-method="filterNode"
  299. :expand-on-click-node="false"
  300. @node-click="handleDeptNodeClick"
  301. />
  302. </el-card>
  303. <!-- 搜索工作区 -->
  304. <el-card class="w-4/5 user" style="margin-left: 10px" :gutter="12" shadow="hover">
  305. <template #header>
  306. <div class="card-header">
  307. <span>{{ tableTitle }}</span>
  308. </div>
  309. </template>
  310. <Search
  311. :schema="allSchemas.searchSchema"
  312. @search="setSearchParams"
  313. @reset="setSearchParams"
  314. ref="searchForm"
  315. />
  316. <!-- 操作工具栏 -->
  317. <div class="mb-10px">
  318. <el-button type="primary" v-hasPermi="['system:user:create']" @click="handleAdd">
  319. <Icon icon="ep:zoom-in" class="mr-5px" /> {{ t('action.add') }}
  320. </el-button>
  321. <el-button
  322. type="info"
  323. v-hasPermi="['system:user:import']"
  324. @click="importDialogVisible = true"
  325. >
  326. <Icon icon="ep:upload" class="mr-5px" /> {{ t('action.import') }}
  327. </el-button>
  328. <el-button
  329. type="warning"
  330. v-hasPermi="['system:user:export']"
  331. @click="exportList('用户数据.xls')"
  332. >
  333. <Icon icon="ep:download" class="mr-5px" /> {{ t('action.export') }}
  334. </el-button>
  335. </div>
  336. <!-- 列表 -->
  337. <Table
  338. :columns="allSchemas.tableColumns"
  339. :selection="false"
  340. :data="tableObject.tableList"
  341. :loading="tableObject.loading"
  342. :pagination="{
  343. total: tableObject.total
  344. }"
  345. v-model:pageSize="tableObject.pageSize"
  346. v-model:currentPage="tableObject.currentPage"
  347. @register="register"
  348. >
  349. <template #sex="{ row }">
  350. <DictTag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="row.sex" />
  351. </template>
  352. <template #status="{ row }">
  353. <el-switch
  354. v-model="row.status"
  355. :active-value="0"
  356. :inactive-value="1"
  357. @change="handleStatusChange(row)"
  358. />
  359. </template>
  360. <template #loginDate="{ row }">
  361. <span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
  362. </template>
  363. <template #action="{ row }">
  364. <el-button
  365. link
  366. type="primary"
  367. v-hasPermi="['system:user:update']"
  368. @click="handleUpdate(row)"
  369. >
  370. <Icon icon="ep:edit" class="mr-1px" /> {{ t('action.edit') }}
  371. </el-button>
  372. <el-button
  373. link
  374. type="primary"
  375. v-hasPermi="['system:user:update']"
  376. @click="handleDetail(row)"
  377. >
  378. <Icon icon="ep:view" class="mr-1px" /> {{ t('action.detail') }}
  379. </el-button>
  380. <el-button
  381. link
  382. type="primary"
  383. v-hasPermi="['system:user:update-password']"
  384. @click="handleResetPwd(row)"
  385. >
  386. <Icon icon="ep:key" class="mr-1px" /> 重置密码
  387. </el-button>
  388. <el-button
  389. link
  390. type="primary"
  391. v-hasPermi="['system:permission:assign-user-role']"
  392. @click="handleRole(row)"
  393. >
  394. <Icon icon="ep:key" class="mr-1px" /> 分配角色
  395. </el-button>
  396. <el-button
  397. link
  398. type="primary"
  399. v-hasPermi="['system:user:delete']"
  400. @click="delList(row.id, false)"
  401. >
  402. <Icon icon="ep:delete" class="mr-1px" /> {{ t('action.del') }}
  403. </el-button>
  404. </template>
  405. </Table>
  406. </el-card>
  407. </div>
  408. <Dialog v-model="dialogVisible" :title="dialogTitle">
  409. <!-- 对话框(添加 / 修改) -->
  410. <Form
  411. v-if="['create', 'update'].includes(actionType)"
  412. :rules="rules"
  413. :schema="allSchemas.formSchema"
  414. ref="formRef"
  415. >
  416. <template #deptId>
  417. <el-tree-select
  418. node-key="id"
  419. v-model="deptId"
  420. :props="defaultProps"
  421. :data="deptOptions"
  422. check-strictly
  423. />
  424. </template>
  425. <template #postIds>
  426. <el-select v-model="postIds" multiple :placeholder="t('common.selectText')">
  427. <el-option
  428. v-for="item in postOptions"
  429. :key="item.id"
  430. :label="item.name"
  431. :value="item.id"
  432. />
  433. </el-select>
  434. </template>
  435. </Form>
  436. <!-- 对话框(详情) -->
  437. <Descriptions
  438. v-if="actionType === 'detail'"
  439. :schema="allSchemas.detailSchema"
  440. :data="detailRef"
  441. >
  442. <template #deptId="{ row }">
  443. <span>{{ row.dept?.name }}</span>
  444. </template>
  445. <template #postIds="{ row }">
  446. <el-tag v-for="(post, index) in row.postIds" :key="index" index="">
  447. <template v-for="postObj in postOptions">
  448. {{ post === postObj.id ? postObj.name : '' }}
  449. </template>
  450. </el-tag>
  451. </template>
  452. <template #sex="{ row }">
  453. <DictTag :type="DICT_TYPE.SYSTEM_USER_SEX" :value="row.sex" />
  454. </template>
  455. <template #status="{ row }">
  456. <DictTag :type="DICT_TYPE.COMMON_STATUS" :value="row.status" />
  457. </template>
  458. <template #loginDate="{ row }">
  459. <span>{{ dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss') }}</span>
  460. </template>
  461. </Descriptions>
  462. <!-- 操作按钮 -->
  463. <template #footer>
  464. <el-button
  465. v-if="['create', 'update'].includes(actionType)"
  466. type="primary"
  467. :loading="loading"
  468. @click="submitForm"
  469. >
  470. {{ t('action.save') }}
  471. </el-button>
  472. <el-button @click="dialogVisible = false">{{ t('dialog.close') }}</el-button>
  473. </template>
  474. </Dialog>
  475. <!-- 分配用户角色 -->
  476. <Dialog v-model="roleDialogVisible" title="分配角色" maxHeight="450px">
  477. <el-form :model="userRole" label-width="80px">
  478. <el-form-item label="用户名称">
  479. <el-input v-model="userRole.username" :disabled="true" />
  480. </el-form-item>
  481. <el-form-item label="用户昵称">
  482. <el-input v-model="userRole.nickname" :disabled="true" />
  483. </el-form-item>
  484. <el-form-item label="角色">
  485. <el-transfer
  486. v-model="userRole.roleIds"
  487. :titles="['角色列表', '已选择']"
  488. :props="{
  489. key: 'id',
  490. label: 'name'
  491. }"
  492. :data="roleOptions"
  493. />
  494. </el-form-item>
  495. </el-form>
  496. <!-- 操作按钮 -->
  497. <template #footer>
  498. <el-button type="primary" :loading="loading" @click="submitRole">
  499. {{ t('action.save') }}
  500. </el-button>
  501. <el-button @click="roleDialogVisible = false">{{ t('dialog.close') }}</el-button>
  502. </template>
  503. </Dialog>
  504. <!-- 导入 -->
  505. <Dialog
  506. v-model="importDialogVisible"
  507. :title="importDialogTitle"
  508. :destroy-on-close="true"
  509. maxHeight="350px"
  510. >
  511. <el-form class="drawer-multiColumn-form" label-width="150px">
  512. <el-form-item label="模板下载 :">
  513. <el-button type="primary" @click="handleImportTemp">
  514. <Icon icon="ep:download" />
  515. 点击下载
  516. </el-button>
  517. </el-form-item>
  518. <el-form-item label="文件上传 :">
  519. <el-upload
  520. ref="uploadRef"
  521. :action="updateUrl + '?updateSupport=' + updateSupport"
  522. :headers="uploadHeaders"
  523. :drag="true"
  524. :limit="1"
  525. :multiple="true"
  526. :show-file-list="true"
  527. :disabled="uploadDisabled"
  528. :before-upload="beforeExcelUpload"
  529. :on-exceed="handleExceed"
  530. :on-success="handleFileSuccess"
  531. :on-error="excelUploadError"
  532. :auto-upload="false"
  533. accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
  534. >
  535. <Icon icon="ep:upload-filled" />
  536. <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
  537. <template #tip>
  538. <div class="el-upload__tip">请上传 .xls , .xlsx 标准格式文件</div>
  539. </template>
  540. </el-upload>
  541. </el-form-item>
  542. <el-form-item label="是否更新已经存在的用户数据:">
  543. <el-checkbox v-model="updateSupport" />
  544. </el-form-item>
  545. </el-form>
  546. <template #footer>
  547. <el-button type="primary" @click="submitFileForm">
  548. <Icon icon="ep:upload-filled" />
  549. {{ t('action.save') }}
  550. </el-button>
  551. <el-button @click="importDialogVisible = false">{{ t('dialog.close') }}</el-button>
  552. </template>
  553. </Dialog>
  554. </template>
  555. <style scoped>
  556. .user {
  557. height: 900px;
  558. max-height: 960px;
  559. }
  560. .card-header {
  561. display: flex;
  562. justify-content: space-between;
  563. align-items: center;
  564. }
  565. </style>